Khush Shah

KL-Divergence

Khush Shah Updated 23 min read Mathematics, Statistics, Machine Learning

KL divergence turns up all over machine learning. The cross-entropy loss behind most classifiers is an entropy plus a KL divergence (see Loss Functions for Regression and Classification for that loss), variational autoencoders use it as a regulariser, and fine-tuned language models are kept close to where they started with a KL penalty. It is also easy to misuse, because it is not a distance and its two directions behave very differently. In this post I build it up from a simple question, how much has a distribution changed, derive it for two Gaussians, and estimate it by Monte Carlo when no formula exists.

Introduction to KL-Divergence

In this blog we want to discuss the "KL-Divergence". But first, we need to understand what is "distance".

Distance

Distance is a measure of how much two objects are different.

  • Take two scalars $x$ and $y$. The distance between them is $|x-y|$. For example, the distance between $3$ and $5$ is $|3-5|=2$.

  • Similarly, the distance between two vectors $\mathbf{x}$ and $\mathbf{y}$ is $||\mathbf{x}-\mathbf{y}||$. For example, the distance between $(1,2)$ and $(3,4)$

    $$||(1,2)-(3,4)||=||(-2,-2)||=\sqrt{(-2)^2+(-2)^2}=\sqrt{8}\approx 2.83$$

Distance between two distributions

But what about the distance between two distributions $P$ and $Q$? For example, two Bernoulli Distribution $P$ and $Q$ of probabilities of Heads & Tails on two different coins (One fair-coin and the other unbalanced). Say, $P=[0.5, 0.5]$ and $Q=[0.3,0.7]$?

We can use the same formula $||P-Q||$.

$$||P-Q||=||[0.5,0.5]-[0.3,0.7]||=||[0.2,-0.2]||=\sqrt{0.2^2+(-0.2)^2}=\sqrt{0.08}$$

But this formula is not good enough for comparing distributions, because it only looks at the size of each difference and not at what the difference means. A change from $0.1$ to $0.4$ in a rare event and a change from $0.5$ to $0.8$ in a common event are both differences of $0.3$, so the Euclidean distance treats them the same. The first one is a much bigger surprise, though: the rare event became four times as likely, the common one only 1.6 times. KL-Divergence measures the surprise through the ratio of the two probabilities, and weights it by how likely the event is under $P$.

Take the weather as an example. Let $P$ be the distribution of the weather in the winter and $Q$ the distribution of the weather in the monsoon. Think of a forecaster who learnt the weather in the monsoon and keeps predicting with $Q$. We want to measure how surprised this monsoon-based forecaster ($Q$) is by winter weather ($P$).

Look at the example below:

Show code
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots

pio.renderers.default = "plotly_mimetype+notebook_connected"

weather = ["rainy", "cloudy", "sunny"]
monsoon = [0.4, 0.5, 0.1]   # Q
winter = [0.1, 0.5, 0.4]    # P

fig = make_subplots(rows=1, cols=2, shared_yaxes=True,
                    subplot_titles=("Monsoon, Q", "Winter, P"))
fig.add_trace(go.Bar(x=weather, y=monsoon, name="Monsoon (Q)"), row=1, col=1)
fig.add_trace(go.Bar(x=weather, y=winter, name="Winter (P)"), row=1, col=2)
fig.update_yaxes(title_text="probability", row=1, col=1)
fig.update_layout(showlegend=False)
fig.show()

Building a better distance measure

We will try to find a better formula for the distance between two distributions

The relative change in each type of weather, from the monsoon ($Q$) to the winter ($P$), is $P/Q$:

$$\begin{align*} \text{rainy:}\quad \frac{P(\text{rainy})}{Q(\text{rainy})} &= \frac{0.1}{0.4} = \frac{1}{4}\\ \text{cloudy:}\quad \frac{P(\text{cloudy})}{Q(\text{cloudy})} &= \frac{0.5}{0.5} = 1\\ \text{sunny:}\quad \frac{P(\text{sunny})}{Q(\text{sunny})} &= \frac{0.4}{0.1} = 4 \end{align*}$$

The average relative change from monsoon to winter is:

$$\begin{align*} \frac{1}{3}\left(\frac{1}{4}+1+4\right) &= \frac{1}{3}\left(\frac{1+4+16}{4}\right)\\ &= \frac{21}{12} = 1.75 \end{align*}$$

Issues with the relative change

However, this is skewed by large changes in the distribution like at the change values $4$ and $0.25$. We need to make the change in the distribution more balanced by finding some function $f$ such that...

$$\begin{align*} f(4) &= y\\ f(0.25) &= -y \end{align*}$$

And in general

$$\begin{align*} f(x) &= y\\ f\left(\dfrac{1}{x}\right) &= -y \end{align*}$$

The logarithm function

This function is $f(x)=\log(x)$. So, we take the average of the log of the relative change in the distribution. The average log relative change from monsoon to winter is:

$$\begin{align*} &\frac{1}{3}\left(\log\frac{1}{4}+\log 1+\log 4\right)\\ &\quad= \frac{1}{3}\left(\log\frac{1}{4}+\log 4\right)\\ &\quad= \frac{1}{3}\log\left(\frac{1}{4}\times 4\right)\\ &\quad= \frac{1}{3}\log 1 = 0 \end{align*}$$

Problem with average log relative change

BUT!! This is clearly wrong. Because the change in the distribution from the monsoon to the winter is definitely not $0$. Then what is the problem and what are we missing?

The problem is that we are taking a plain average of the log relative changes, so every type of weather counts the same. Rather, we should take a weighted average, and weight each log relative change by how often that weather actually happens in the winter, i.e., by $P$. The weights $P$ sum to $1$, so the weighted sum is already a weighted average.

The weighted sum of the log relative changes from monsoon to winter is:

$$\begin{align*} &P(\text{rainy})\log\frac{1}{4} + P(\text{cloudy})\log 1\\ &\qquad + P(\text{sunny})\log 4\\ &\quad= 0.1\log\frac{1}{4} + 0.5\log 1 + 0.4\log 4\\ &\quad= 0.1\left(\log\frac{1}{4} + 4\log 4\right)\\ &\quad= 0.1\log\left(\frac{1}{4}\times 4^4\right)\\ &\quad= 0.1\log\left(4^3\right) = \frac{\log 64}{10}\\ &\quad\approx 0.416\ \text{nats} \end{align*}$$

Hence the formula for the KL-Divergence between two distributions $P$ and $Q$.

The Kullback-Leibler Divergence

The KL-Divergence for discrete distributions is defined as follows:

$$D_{KL}(P\|Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)}$$

It is the average, under $P$, of the log relative change $\log\frac{P(x)}{Q(x)}$: how surprised, on average, someone who predicts with $Q$ is by data that really come from $P$. Throughout this post $\log$ is the natural logarithm, so the KL-Divergence is measured in nats (with $\log_2$ it would be in bits). For the weather, $D_{KL}(P\|Q) \approx 0.416$ nats.

For continuous probability distributions $P$ and $Q$ the KL-Divergence is defined as:

$$\begin{align*} D_{KL}(P\|Q) = \int P(x) \cdot \log\left(\dfrac{P(x)}{Q(x)} \right) dx \end{align*}$$

Properties

Three properties of the KL-Divergence come up again and again:

  • It is never negative, $D_{KL}(P\|Q) \ge 0$. This is Gibbs' inequality.
  • It is zero only when $P = Q$.
  • It is infinite if $Q$ rules out something that $P$ allows. If $Q(x) = 0$ at some $x$ where $P(x) > 0$, the term $P(x)\log\frac{P(x)}{Q(x)}$ is infinite, and so is the sum. Where $P(x) = 0$ the term counts as $0$ (the convention $0 \log 0 = 0$), whatever $Q(x)$ is.

For the weather, think of a forecaster who learnt in the monsoon that it is never sunny, $Q' = (0.5, 0.5, 0)$ for rainy, cloudy and sunny. The first sunny winter day is an infinite surprise for them, so $D_{KL}(P\|Q') = \infty$. The other direction is finite: data from $Q'$ are never sunny, and $P$ gives some probability to everything $Q'$ produces. This is why a model that is scored with KL or cross-entropy should never put exactly zero probability on anything that can happen. scipy.stats.entropy(p, q) computes the KL-Divergence in nats and follows both conventions:

import numpy as np
from scipy.stats import entropy   # entropy(p) is H(p); entropy(p, q) is KL(p || q); both in nats

P_winter = np.array([0.1, 0.5, 0.4])     # P: rainy, cloudy, sunny
Q_monsoon = np.array([0.4, 0.5, 0.1])    # Q
Q_no_sun = np.array([0.5, 0.5, 0.0])     # Q': a monsoon forecaster who never expects sun

print(f"KL(P || Q') = {entropy(P_winter, Q_no_sun)}")
print(f"KL(Q' || P) = {entropy(Q_no_sun, P_winter):.3f}")
KL(P || Q') = inf
KL(Q' || P) = 0.805

Cross-entropy is entropy plus KL

The cross-entropy loss is the KL-Divergence in disguise. Split the log of the ratio into two sums:

$$\begin{align*} D_{KL}(P\|Q) &= \sum_x P(x)\log P(x)\\ &\qquad - \sum_x P(x)\log Q(x)\\ &= -H(P) + H(P, Q) \end{align*}$$

where $H(P) = -\sum_x P(x)\log P(x)$ is the entropy of $P$ and $H(P, Q) = -\sum_x P(x)\log Q(x)$ is the cross-entropy of $Q$ relative to $P$. So

$$H(P, Q) = H(P) + D_{KL}(P\|Q)$$

The entropy is how surprised you are on average when you predict with the true $P$, the cross-entropy is how surprised you are when you predict with $Q$, and the KL-Divergence is the extra surprise you pay for using the wrong distribution. When we train a classifier, $P$ is the data and $Q$ is the model. $H(P)$ does not depend on the model, so minimising the cross-entropy loss is the same as minimising $D_{KL}(P\|Q)$ (more on that loss in Loss Functions for Regression and Classification). For the weather:

H_P = -np.sum(P_winter * np.log(P_winter))       # entropy H(P)
H_PQ = -np.sum(P_winter * np.log(Q_monsoon))     # cross-entropy H(P, Q)
kl_weather = entropy(P_winter, Q_monsoon)        # KL(P || Q)

print(f"H(P)              = {H_P:.3f} nats")
print(f"KL(P || Q)        = {kl_weather:.3f} nats")
print(f"H(P) + KL(P || Q) = {H_P + kl_weather:.3f} nats")
print(f"H(P, Q)           = {H_PQ:.3f} nats")
H(P)              = 0.943 nats
KL(P || Q)        = 0.416 nats
H(P) + KL(P || Q) = 1.359 nats
H(P, Q)           = 1.359 nats

Is it a distance?

I started this post with distances, so it is fair to ask whether the KL-Divergence is one. The first two properties above are also properties of a distance. But it does not have the other two:

  • It is not symmetric: in general $D_{KL}(P\|Q) \ne D_{KL}(Q\|P)$. For the two Gaussians later in this post, $P = N(0, 1)$ and $Q = N(-1, 2)$, we get $D_{KL}(P\|Q) = 0.443$ but $D_{KL}(Q\|P) = 1.307$. (The weather example happens to give $0.416$ nats both ways, only because the two distributions are mirror images of each other.)
  • It does not satisfy the triangle inequality.

So it is not a distance, and that is why it is called a divergence. The direction we compute matters, and at the end of this post we will see what each direction does.

KL-Divergence between two Normal/Gaussian distributions

In the case of $P(x)\sim N(\mu_1, \sigma_1)$ and $Q(x)\sim N(\mu_2, \sigma_2)$, we would like to find the KL-Divergence.

I will do it in three steps: (i) split the KL-Divergence into two expectations under $P$, (ii) recognise the first one as minus the entropy of $P$, and (iii) work out the second one from the mean and variance of $P$.

(i) Split the logarithm. The log of a ratio is a difference of logs, so

$$\begin{align*} D_{KL}(P\|Q) &= \int P(x)\log\frac{P(x)}{Q(x)}\,dx\\ &= \int P(x)\log P(x)\,dx\\ &\qquad - \int P(x)\log Q(x)\,dx\\ &= \mathbb{E}_P[\log P(x)] - \mathbb{E}_P[\log Q(x)] \end{align*}$$

Both terms need the log of a Gaussian density:

Note

The $\log$ PDF of $N(\mu, \sigma)$ is

$$\begin{align*} &\log\left(\frac{1}{\sqrt{2\pi}\,\sigma}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\right)\\ &\quad= -\frac{1}{2}\log(2\pi) - \log\sigma - \frac{(x-\mu)^2}{2\sigma^2} \end{align*}$$

(ii) The first term is minus the entropy of $P$. Under $P$ the squared distance from the mean averages to the variance, $\mathbb{E}_P[(x-\mu_1)^2] = \sigma_1^2$, so

$$\begin{align*} \mathbb{E}_P[\log P(x)] &= -\frac{1}{2}\log(2\pi) - \log\sigma_1 - \frac{\sigma_1^2}{2\sigma_1^2}\\ &= -\frac{1}{2}\log\left(2\pi e\,\sigma_1^2\right) \end{align*}$$

which is minus the entropy of a Gaussian.

(iii) The second term needs one expectation. Now the squared distance is measured from $\mu_2$, but $x$ still comes from $P$, whose mean is $\mu_1$. The average squared distance is the variance plus the squared offset of the mean,

$$\mathbb{E}_P[(x-\mu_2)^2] = \sigma_1^2 + (\mu_1-\mu_2)^2$$

so

$$\begin{align*} \mathbb{E}_P[\log Q(x)] &= -\frac{1}{2}\log(2\pi) - \log\sigma_2\\ &\qquad - \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} \end{align*}$$
The expansion, step by step

Write $x - \mu_2 = (x - \mu_1) + (\mu_1 - \mu_2)$ and expand the square:

$$\begin{align*} \mathbb{E}_P[(x-\mu_2)^2] &= \mathbb{E}_P[(x-\mu_1)^2]\\ &\quad + 2(\mu_1-\mu_2)\,\mathbb{E}_P[x-\mu_1]\\ &\quad + (\mu_1-\mu_2)^2\\ &= \sigma_1^2 + 0 + (\mu_1-\mu_2)^2 \end{align*}$$

The middle term is $0$ because $P$ has mean $\mu_1$. The last term is a constant, and its expectation is the constant itself because $P$ integrates to $1$.

Putting it together. Subtracting the second term from the first, the $\frac{1}{2}\log(2\pi)$ terms cancel:

$$\begin{align*} D_{KL}(P\|Q) &= \log\sigma_2 - \log\sigma_1 - \frac{1}{2}\\ &\qquad + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} \end{align*}$$
$$D_{KL}(P\|Q) = \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} - \frac{1}{2}$$

Comparison with TensorFlow Probability (TFP)

TFP Implementation

This is the Normal-Normal KL-Divergence in TensorFlow Probability, from tensorflow_probability/python/distributions/normal.py. It needs TFP, so it is shown here but not run.

@kullback_leibler.RegisterKL(Normal, Normal)
def _kl_normal_normal(a, b, name=None):
  """Calculate the batched KL divergence KL(a || b) with a and b Normal.

  Args:
    a: instance of a Normal distribution object.
    b: instance of a Normal distribution object.
    name: Name to use for created operations.
      Default value: `None` (i.e., `'kl_normal_normal'`).

  Returns:
    kl_div: Batchwise KL(a || b)
  """
  with tf.name_scope(name or 'kl_normal_normal'):
    b_scale = tf.convert_to_tensor(b.scale)  # We'll read it thrice.
    diff_log_scale = tf.math.log(a.scale) - tf.math.log(b_scale)
    return (
        0.5 * tf.math.squared_difference(a.loc / b_scale, b.loc / b_scale) +
        0.5 * tf.math.expm1(2. * diff_log_scale) -
        diff_log_scale)
Copyright The TensorFlow Probability Authors, Apache License 2.0.

Simplified Terms

$$\mathrm{diff\_ log\_ scale} = \log(\sigma_1) - \log(\sigma_2) = \log\left(\dfrac{\sigma_1}{\sigma_2}\right)$$
$$\mathrm{expm1(x)} = e^x - 1$$
$$\mathrm{squared\_ difference(x, y)} = (x - y)^2$$
Why expm1?

TFP writes $\sigma_1^2/\sigma_2^2 - 1$ as expm1(2. * diff_log_scale) rather than exp(2. * diff_log_scale) - 1. When $\sigma_1 \approx \sigma_2$, the exponential is very close to $1$, and subtracting $1$ cancels most of its significant digits. expm1 computes $e^x - 1$ directly and keeps them. See Numerical Hygiene for more on this. For $x = 10^{-12}$ the naive version has a relative error of about $10^{-4}$, while expm1 is right to the last digit:

import math

x = 1e-12
print(f"exp(x) - 1 = {math.exp(x) - 1:.15e}")
print(f"expm1(x)   = {math.expm1(x):.15e}")
exp(x) - 1 = 1.000088900582341e-12
expm1(x)   = 1.000000000000500e-12

Verifying it with our derivation

$$\begin{align*} D_{KL}(P\|Q) &= \frac{1}{2}\left(\frac{\mu_1}{\sigma_2} - \frac{\mu_2}{\sigma_2}\right)^2\\ &\quad + \frac{1}{2}\left(\exp\left(2\log\frac{\sigma_1}{\sigma_2}\right) - 1\right)\\ &\quad - \log\frac{\sigma_1}{\sigma_2}\\ &= \frac{1}{2}\left(\frac{\mu_1-\mu_2}{\sigma_2}\right)^2\\ &\quad + \frac{1}{2}\left(\exp\left(\log\left(\frac{\sigma_1}{\sigma_2}\right)^2\right) - 1\right)\\ &\quad + \log\frac{\sigma_2}{\sigma_1}\\ &= \frac{1}{2}\left(\frac{\mu_1-\mu_2}{\sigma_2}\right)^2\\ &\quad + \frac{1}{2}\left(\left(\frac{\sigma_1}{\sigma_2}\right)^2 - 1\right)\\ &\quad + \log\frac{\sigma_2}{\sigma_1}\\ &= \frac{(\mu_1-\mu_2)^2}{2\sigma_2^2} + \frac{\sigma_1^2}{2\sigma_2^2} - \frac{1}{2}\\ &\quad + \log\frac{\sigma_2}{\sigma_1}\\ &= \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} - \frac{1}{2} \end{align*}$$

This is the same result as our derivation.

My Implementation

import torch
import plotly.express as px
u1, s1 = 0, 1
u2, s2 = -1, 2

x = torch.arange(-10, 10, 0.01)

P = torch.distributions.Normal(u1, s1)
Q = torch.distributions.Normal(u2, s2)
fig = px.line()
fig.add_scatter(x=x, y=P.log_prob(x).exp(), name='P')
fig.add_scatter(x=x, y=Q.log_prob(x).exp(), name='Q')
fig.show()
u1 = torch.tensor(u1)
s1 = torch.tensor(s1)

u2 = torch.tensor(u2)
s2 = torch.tensor(s2)

torch_klPQ = torch.distributions.kl.kl_divergence(P, Q)
torch_klQP = torch.distributions.kl.kl_divergence(Q, P)

print('KL Divergence of P with respect to Q: ', round(torch_klPQ.item(), 3))
print('KL Divergence of Q with respect to P: ', round(torch_klQP.item(), 3))

klPQ = torch.log(s2/s1) + (s1**2 + (u1-u2)**2)/(2*s2**2) - 0.5
klQP = torch.log(s1/s2) + (s2**2 + (u2-u1)**2)/(2*s1**2) - 0.5

print('KL Divergence of P with respect to Q: ', round(klPQ.item(), 3))
print('KL Divergence of Q with respect to P: ', round(klQP.item(), 3))
KL Divergence of P with respect to Q:  0.443
KL Divergence of Q with respect to P:  1.307
KL Divergence of P with respect to Q:  0.443
KL Divergence of Q with respect to P:  1.307

Monte Carlo Estimation

Suppose we have a function $f$, that is really complicated. We can evaluate $f$, but we are interested in the integral of this function. Unfortunately for us, we can not analytically compute the integral of this function - maybe it’s just impossible, or maybe our maths skills are not at a high enough level. The idea is to estimate the integral of a function, over a defined interval, only knowing the function expression. For such an aim, Monte Carlo Integration is a technique for numerical integration using random numbers.

Example

For example, suppose we want to estimate the integral of the function $f(x) = x^3 + x^2 - x + 2$ over the interval $[-1, 1]$. We know that the integral can be interpreted as the area below the function's curve. This one we can also do by hand, which gives us something to check the estimate against. The odd terms $x^3$ and $-x$ integrate to $0$ over $[-1, 1]$, so

$$\int_{-1}^{1} f(x)\,dx = 0 + \frac{2}{3} + 0 + 4 = \frac{14}{3} \approx 4.667$$
from scipy.integrate import quad

def f(x):
    return x**3 + x**2 - x + 2

exact, _ = quad(f, -1, 1)
print(f"Exact value: {exact:.3f}")
Exact value: 4.667
x = torch.arange(-1, 1, 0.01)

y = f(x)

fig = px.area(x=x, y=y, labels={'x':'x', 'y':'f(x)'})
fig.show()

If we take a random point $x_i$ between $a$ and $b$, we can multiply $f(x_i)$ by $(b-a)$ to get the area of a rectangle of width $(b-a)$ and height $f(x_i)$. The idea behind Monte Carlo Integration is to approximate the integral value by the averaged area of rectangles computed for randomly picked $x_i$. Here $a = -1$ and $b = 1$, so every rectangle is $2$ wide.

torch.manual_seed(0)

a, b = -1, 1
n_mc_sample = 4

random_x = (b - a) * torch.rand(n_mc_sample) + a
random_y = f(random_x)
areas = (b - a) * random_y          # width (b - a) times height f(x_i)

titles = [f"x = {xi:.2f}, area = {area:.2f}" for xi, area in zip(random_x.tolist(), areas.tolist())]
fig = make_subplots(rows=2, cols=2, shared_xaxes=True, shared_yaxes=True,
                    vertical_spacing=0.1, subplot_titles=titles)

# One colour for each kind of line, so the four panels read the same way.
for i in range(n_mc_sample):
    row, col = i // 2 + 1, i % 2 + 1
    height = random_y[i].item()
    fig.add_trace(go.Scatter(x=[a, a, b, b, a], y=[0, height, height, 0, 0], mode="lines",
                             fill="toself", fillcolor="rgba(199, 87, 22, 0.25)", line_color="#C75716",
                             name="rectangle", legendgroup="rectangle", showlegend=i == 0), row=row, col=col)
    fig.add_trace(go.Scatter(x=x, y=y, mode="lines", line_color="#5C86B0",
                             name="f(x)", legendgroup="f", showlegend=i == 0), row=row, col=col)
    fig.add_trace(go.Scatter(x=[random_x[i].item()], y=[height], mode="markers", marker_color="#C75716",
                             marker_size=9, name="random point", legendgroup="point", showlegend=i == 0),
                  row=row, col=col)
fig.update_annotations(font_size=13)
fig.update_layout(height=480)
fig.show()

print(f"Exact value: {exact:.3f}")
print(f"Estimate:    {areas.mean().item():.3f}  (the average of the four areas)")
Exact value: 4.667
Estimate:    4.868  (the average of the four areas)

By finding the area of the rectangles and averaging them, the resulting number gets closer and closer to the actual result of the integral. In fact, the rectangles which are too large compensate for the rectangles which are too small. This idea is formalised with the following formula, which is the Monte Carlo Estimator.

Formula for Monte Carlo Estimator

$$\int_a^b f(x)\,dx \approx \frac{b-a}{N}\sum_{i=1}^{N} f(x_i), \quad x_i\sim U(a,b)$$

where $N$ is the number of random points we pick, and $x_i$ is a random point distributed uniformly between $a$ and $b$. The factor $(b-a)$ is the width of each rectangle: without it we would be estimating the average height of $f$ (here $\frac{14}{3} / 2 \approx 2.333$), not the area under it. The more points we pick, the more accurate the estimation will be. Let's see how quickly, by repeating the estimate with more and more points.

torch.manual_seed(0)

sample_sizes = [4, 10, 100, 1_000, 10_000, 100_000]
estimates = []
for n in sample_sizes:
    random_x = (b - a) * torch.rand(n, dtype=torch.float64) + a
    estimates.append(((b - a) * f(random_x)).mean().item())

# The spread of f(x) for x ~ U(a, b), from E[f] and E[f^2] computed exactly.
mean_f = exact / (b - a)
mean_f2 = quad(lambda t: f(t) ** 2, a, b)[0] / (b - a)
sigma_f = math.sqrt(mean_f2 - mean_f**2)

n_grid = torch.logspace(math.log10(4), 5, 200, dtype=torch.float64)
std_error = sigma_f * (b - a) / n_grid.sqrt()

fig = go.Figure()
fig.add_trace(go.Scatter(x=sample_sizes, y=estimates, mode="lines+markers", name="Monte Carlo estimate"))
fig.add_trace(go.Scatter(x=[4, 100_000], y=[exact, exact], mode="lines", line_dash="dash", name="exact value"))
fig.add_trace(go.Scatter(x=n_grid, y=exact + std_error, mode="lines", line_width=0,
                         showlegend=False, hoverinfo="skip"))
fig.add_trace(go.Scatter(x=n_grid, y=exact - std_error, mode="lines", line_width=0, fill="tonexty",
                         fillcolor="rgba(128, 128, 128, 0.25)", name="exact ± one standard error",
                         hoverinfo="skip"))
fig.update_xaxes(type="log", title_text="number of samples N")
fig.update_yaxes(title_text="estimate of the integral")
fig.show()

for n, estimate in zip(sample_sizes, estimates):
    print(f"N = {n:>7,}: {estimate:.3f}")
N =       4: 4.577
N =      10: 4.479
N =     100: 4.648
N =   1,000: 4.681
N =  10,000: 4.663
N = 100,000: 4.669

With $4$ points the estimate is $4.577$ and with $10$ it is $4.479$, still wrong in the first decimal place. (These are fresh random points, so the $N = 4$ value is not the same as the four rectangles above.) By $100{,}000$ points it is $4.669$, within $0.003$ of the exact $4.667$. The grey band is the exact value plus or minus one standard error, $\sigma_f\,(b-a)/\sqrt{N}$, where $\sigma_f$ is the standard deviation of $f(x)$ for $x \sim U(a, b)$, and here every estimate lands inside it. The error shrinks like $1/\sqrt{N}$: a hundred times more points buys one more correct decimal place.

Formula for Monte Carlo Estimator of Expectation

Consider a case where $X \sim P$, where $P$ is a probability density function of $x$. Then, the Monte Carlo Estimator of the expectation is defined as the following:

$$\int f(x) \cdot P(x)\, dx \approx \dfrac{1}{N}\sum_{i=1}^{N}{f(x_i)}$$

where $x_i \sim P(x)$.

Implementation

torch.manual_seed(0)

n_mc_sample = 10000

xP = P.sample((n_mc_sample,))
xQ = Q.sample((n_mc_sample,))

mc_klPQ = (P.log_prob(xP) - Q.log_prob(xP)).mean()
mc_klQP = (Q.log_prob(xQ) - P.log_prob(xQ)).mean()

print('Monte Carlo KL Divergence of P with respect to Q: ', round(mc_klPQ.item(), 3))
print('Monte Carlo KL Divergence of Q with respect to P: ', round(mc_klQP.item(), 3))
Monte Carlo KL Divergence of P with respect to Q:  0.439
Monte Carlo KL Divergence of Q with respect to P:  1.356

As we can see, it's fairly similar to the values we got earlier.

$$D_{KL}\left(P\|Q\right) = 0.443$$
$$D_{KL}\left(Q\|P\right) = 1.307$$

For this sample size it was a decent estimation. Now let's see how the estimation changes as we change the sample size. Rather than recomputing the mean over a growing list at every step, I draw all the samples once and take a running (cumulative) mean of the per-sample values.

torch.manual_seed(0)

n_mc_sample = 1000

xP = P.sample((n_mc_sample,))
xQ = Q.sample((n_mc_sample,))

vP = P.log_prob(xP) - Q.log_prob(xP)     # one term of the KL(P||Q) average per sample
vQ = Q.log_prob(xQ) - P.log_prob(xQ)     # one term of the KL(Q||P) average per sample

n = torch.arange(1, n_mc_sample + 1)
yP = torch.cumsum(vP, 0) / n             # the estimate after 1, 2, ..., N samples
yQ = torch.cumsum(vQ, 0) / n
grey = 'rgba(128, 128, 128, 0.9)'

fig = go.Figure()
fig.add_scatter(x=n.numpy(), y=yP.numpy(), mode='lines', name='estimate of KL(P||Q)')
fig.add_scatter(x=n.numpy(), y=yQ.numpy(), mode='lines', name='estimate of KL(Q||P)')
fig.add_scatter(x=[1, n_mc_sample], y=[klPQ.item()] * 2, mode='lines', line_dash='dash', line_color=grey,
                name=f'exact KL(P||Q) = {klPQ.item():.3f}')
fig.add_scatter(x=[1, n_mc_sample], y=[klQP.item()] * 2, mode='lines', line_dash='dot', line_color=grey,
                name=f'exact KL(Q||P) = {klQP.item():.3f}')
fig.update_xaxes(type='log', title_text='number of samples N')
fig.update_yaxes(range=[0, 3], title_text='KL estimate (nats)')
fig.show()

print(f"KL(P||Q): estimate {yP[-1].item():.3f}, exact {klPQ.item():.3f}, per-sample sd {vP.std().item():.2f}")
print(f"KL(Q||P): estimate {yQ[-1].item():.3f}, exact {klQP.item():.3f}, per-sample sd {vQ.std().item():.2f}")
print(f"Samples KL(Q||P) needs for the same standard error: {(vQ.std() / vP.std()).item() ** 2:.0f} times as many")
KL(P||Q): estimate 0.429, exact 0.443, per-sample sd 0.64
KL(Q||P): estimate 1.163, exact 1.307, per-sample sd 2.81
Samples KL(Q||P) needs for the same standard error: 19 times as many

The two directions do not converge equally fast. After $1{,}000$ samples the estimate of $D_{KL}(P\|Q)$ is $0.429$, close to the exact $0.443$, but the estimate of $D_{KL}(Q\|P)$ is still $1.163$ against $1.307$, and its first few values are off the top of the chart. The difference is the spread of the per-sample values, $2.81$ against $0.64$. Samples from $Q$, the wider of the two, often land in the tails of $P$, where $\log P(x)$ is very negative. The standard error shrinks like $\sigma/\sqrt{N}$ in both directions, so $D_{KL}(Q\|P)$ needs about $19$ times as many samples for the same accuracy.

Mixture of Gaussians

A mixture of Gaussians, as the name suggests, is a mixture of multiple Gaussian distributions. It is defined as follows:

$$P(x) = \sum_{i=1}^{K}{\pi_i \cdot \mathcal{N}(x|\mu_i, \sigma_i)}$$

where $\pi_i$ is the weight of the $i$-th Gaussian distribution, and $\sum_{i=1}^{K}{\pi_i} = 1$.

For example, let us consider a mixture of two Gaussian distributions. The first Gaussian distribution has a mean of $0$ and a standard deviation of $1$. The second Gaussian distribution has a mean of $5$ and a standard deviation of $2$. The weight of the first Gaussian distribution is $0.3$, and the weight of the second Gaussian distribution is $0.7$. Then, the probability density function of the mixture of two Gaussian distributions is defined as follows:

$$P(x) = 0.3 \cdot \mathcal{N}(x|0, 1) + 0.7 \cdot \mathcal{N}(x|5, 2)$$
u1, s1, w1 = 0, 1, 0.3
u2, s2, w2 = 5, 2, 0.7

x = torch.arange(-5, 10, 0.01)

N1 = torch.distributions.Normal(u1, s1)
N2 = torch.distributions.Normal(u2, s2)

mix = torch.distributions.Categorical(torch.tensor((w1, w2)))
comp = torch.distributions.Normal(torch.tensor((u1, u2)), torch.tensor((s1, s2)))

gmm = torch.distributions.MixtureSameFamily(mix, comp)

yn1 = N1.log_prob(x).exp()
yn2 = N2.log_prob(x).exp()

y = gmm.log_prob(x).exp()

fig = px.line()
fig.add_scatter(x=x, y=yn1, mode="lines", name=f"N({u1}, {s1})")
fig.add_scatter(x=x, y=yn2, mode="lines", name=f"N({u2}, {s2})")
fig.add_scatter(x=x, y=y, mode="lines", name="MOG")

fig.show()

KL-Divergence between a Mixture of Gaussians and a Gaussian

Consider that $P$ is the mixture of two Gaussian Distributions we just saw, and $Q$ is a Gaussian Distribution with mean $2$ and standard deviation $1$. In this case, we can not compute the KL-Divergence analytically. However, we can estimate the KL-Divergence using Monte Carlo Estimation.

$$D_{KL}\left(P\|Q\right) = \int P(x) \cdot \log\left(\dfrac{P(x)}{Q(x)}\right) dx \approx \dfrac{1}{N}\sum_{i=1}^{N}{\log\left(\dfrac{P(x_i)}{Q(x_i)}\right)}$$

where $x_i \sim P(x)$.

Implementation

u1, s1, w1 = 0., 1., 0.3
u2, s2, w2 = 5., 2., 0.7

mix = torch.distributions.Categorical(torch.tensor((w1, w2)).float())
comp = torch.distributions.Normal(torch.tensor((u1, u2)), torch.tensor((s1, s2)))

P = torch.distributions.MixtureSameFamily(mix, comp)
Q = torch.distributions.Normal(2, 1)
x = torch.arange(-5, 12, 0.02)

fig = go.Figure()
fig.add_scatter(x=x, y=P.log_prob(x).exp(), name='P: mixture')
fig.add_scatter(x=x, y=Q.log_prob(x).exp(), name='Q = N(2, 1)')
fig.update_layout(xaxis_title='x', yaxis_title='density')
fig.show()
torch.manual_seed(0)

n_mc_sample = 10000

xP = P.sample((n_mc_sample,))
xQ = Q.sample((n_mc_sample,))

mc_klPQ = (P.log_prob(xP) - Q.log_prob(xP)).mean()
mc_klQP = (Q.log_prob(xQ) - P.log_prob(xQ)).mean()

print('Monte Carlo KL Divergence of P with respect to Q: ', round(mc_klPQ.item(), 3))
print('Monte Carlo KL Divergence of Q with respect to P: ', round(mc_klQP.item(), 3))
Monte Carlo KL Divergence of P with respect to Q:  3.826
Monte Carlo KL Divergence of Q with respect to P:  1.123

Fitting a Gaussian to the mixture: forward or reverse KL?

This is where the mixture earns its place. A common job is to approximate a complicated distribution $P$ by a simple one, here a single Gaussian $Q_\theta = N(\mu, \sigma)$, by choosing $\theta = (\mu, \sigma)$ to make the KL-Divergence small. KL is not symmetric, so there are two ways to do it:

  • forward KL, minimise $D_{KL}(P\|Q_\theta)$, an average over samples from $P$;
  • reverse KL, minimise $D_{KL}(Q_\theta\|P)$, an average over samples from $Q_\theta$.

Neither has a closed form for a mixture, so I minimise both with Monte Carlo gradients: at each of 2,000 Adam steps I draw 1,000 fresh samples, estimate the KL as above and step down its gradient. For the reverse direction the samples come from $Q_\theta$ itself, so they are drawn as $x = \mu + \sigma\varepsilon$ with $\varepsilon \sim N(0, 1)$ (rsample), which lets the gradient flow through them. Both fits start from $Q = N(2, 1)$.

def fit_gaussian(P, direction, steps=2000, n_samples=1000, lr=0.05):
    """Fit Q_theta = N(mu, sigma) to P by minimising the forward or the reverse KL with Adam."""
    torch.manual_seed(0)
    mu = torch.tensor(2.0, requires_grad=True)           # start at Q = N(2, 1)
    log_sigma = torch.tensor(0.0, requires_grad=True)    # sigma = exp(log_sigma) stays positive
    optimiser = torch.optim.Adam([mu, log_sigma], lr=lr)
    for _ in range(steps):
        Q_theta = torch.distributions.Normal(mu, log_sigma.exp())
        if direction == "forward":                        # KL(P || Q_theta), x ~ P
            x = P.sample((n_samples,))
            loss = (P.log_prob(x) - Q_theta.log_prob(x)).mean()
        else:                                             # KL(Q_theta || P), x ~ Q_theta
            x = Q_theta.rsample((n_samples,))
            loss = (Q_theta.log_prob(x) - P.log_prob(x)).mean()
        optimiser.zero_grad()
        loss.backward()
        optimiser.step()
    return torch.distributions.Normal(mu.detach(), log_sigma.exp().detach())


def plot_fits(P, forward_fit, reverse_fit):
    x = torch.arange(-5, 12, 0.02)
    fig = go.Figure()
    fig.add_scatter(x=x, y=P.log_prob(x).exp(), name='P: mixture')
    fig.add_scatter(x=x, y=forward_fit.log_prob(x).exp(), name='forward KL fit', line_dash='dash')
    fig.add_scatter(x=x, y=reverse_fit.log_prob(x).exp(), name='reverse KL fit', line_dash='dot')
    fig.update_layout(xaxis_title='x', yaxis_title='density')
    return fig


def describe(name, d):
    print(f"{name:<12} mean = {d.mean.item():.2f}, sd = {d.stddev.item():.2f}")
forward_fit = fit_gaussian(P, "forward")
reverse_fit = fit_gaussian(P, "reverse")

describe("P", P)
describe("forward fit", forward_fit)
describe("reverse fit", reverse_fit)
P            mean = 3.50, sd = 2.89
forward fit  mean = 3.49, sd = 2.88
reverse fit  mean = 3.81, sd = 2.61
plot_fits(P, forward_fit, reverse_fit).show()

For this mixture the two fits are close. The forward fit, $N(3.49, 2.88)$, has the mean and standard deviation of $P$ itself ($3.50$ and $2.89$): minimising the forward KL over Gaussians matches the moments. The reverse fit, $N(3.81, 2.61)$, is a little narrower and pulled towards the heavier mode, but it still spans both. The right-hand bump is wide ($\sigma = 2$), so the valley between the modes is shallow, and one wide Gaussian is the best compromise in either direction.

The difference shows when the modes are well apart. Here is the same mixture with the right-hand component narrowed to $\sigma = 1$, that is $P(x) = 0.3 \cdot \mathcal{N}(x|0, 1) + 0.7 \cdot \mathcal{N}(x|5, 1)$:

P_apart = torch.distributions.MixtureSameFamily(
    torch.distributions.Categorical(torch.tensor((0.3, 0.7))),
    torch.distributions.Normal(torch.tensor((0., 5.)), torch.tensor((1., 1.))),
)

forward_apart = fit_gaussian(P_apart, "forward")
reverse_apart = fit_gaussian(P_apart, "reverse")

describe("P", P_apart)
describe("forward fit", forward_apart)
describe("reverse fit", reverse_apart)
P            mean = 3.50, sd = 2.50
forward fit  mean = 3.49, sd = 2.49
reverse fit  mean = 4.96, sd = 1.05
plot_fits(P_apart, forward_apart, reverse_apart).show()

Now the two directions disagree completely. The forward fit, $N(3.49, 2.49)$, again matches the mean and spread of $P$, and sits over the valley between the modes, where $P$ has almost no mass. The reverse fit, $N(4.96, 1.05)$, has locked onto the taller mode at $5$ and ignores the one at $0$. The reason is where each average is taken:

  • Forward KL is mode-covering. $D_{KL}(P\|Q_\theta)$ averages $\log\frac{P(x)}{Q_\theta(x)}$ over samples from $P$. Wherever $P$ has mass and $Q_\theta$ is tiny, that log ratio is huge, so $Q_\theta$ has to put mass everywhere $P$ does. It covers both modes, and the price is a wide Gaussian with plenty of mass in the valley.
  • Reverse KL is mode-seeking. $D_{KL}(Q_\theta\|P)$ averages $\log\frac{Q_\theta(x)}{P(x)}$ over samples from $Q_\theta$. Wherever $Q_\theta$ has mass and $P$ is tiny, that log ratio is huge, so $Q_\theta$ stays out of the valley and squeezes into one mode. Missing the other mode costs little, because no samples are drawn there.

This is why the direction matters in practice. Fitting a model by maximum likelihood minimises the forward KL, so the fit tends to spread over everything the data do. Variational inference minimises the reverse KL, so its approximations tend to lock onto one mode and underestimate the spread.

Where KL shows up

The two directions and the closed form for two Gaussians are not just exercises. Here are three places they turn up in machine learning.

Variational autoencoders. The encoder of a VAE maps each input to a Gaussian over a latent code $z$, $q(z \mid x) = N(\mu(x), \sigma(x))$, and the decoder rebuilds the input from a sample of $z$. The loss is a reconstruction error plus $D_{KL}(q(z \mid x)\,\|\,N(0, 1))$. That KL term is the regulariser: it pulls the code of every input towards the same standard normal prior, so the codes overlap and a $z$ drawn from $N(0, 1)$ decodes to something sensible. Both distributions are Gaussian, so it is the closed form derived above with $\mu_2 = 0$ and $\sigma_2 = 1$, one term per latent dimension:

$$\begin{align*} &D_{KL}\big(N(\mu, \sigma)\,\|\,N(0, 1)\big)\\ &\quad= -\log\sigma + \frac{\sigma^2 + \mu^2}{2} - \frac{1}{2} \end{align*}$$

which is the $-\frac{1}{2}\sum\left(1 + \log\sigma^2 - \mu^2 - \sigma^2\right)$ you see in VAE code.

Knowledge distillation. To compress a large teacher network into a small student, the student learns to match the teacher's output probabilities, not only the hard labels. Hinton, Vinyals and Dean divide both networks' logits by a temperature $T > 1$ before the softmax, so that the small probabilities the teacher gives to wrong classes still carry a signal, and train the student on the cross-entropy against these soft targets. The teacher is fixed, so its entropy is a constant and, by the identity above, this is the same as minimising $D_{KL}(\text{teacher}\,\|\,\text{student})$, which is how most code writes it. One trap: PyTorch's F.kl_div(input, target) takes the student's log-probabilities as input and computes $D_{KL}(\text{target}\,\|\,\text{input})$, so the student goes first in the call but second in the maths.

PPO and GRPO. When a language model is fine-tuned by reinforcement learning against a learned reward model, as in InstructGPT, the policy $\pi_\theta$ is penalised for drifting away from a frozen reference model $\pi_{\text{ref}}$, the supervised model it started from. For a prompt $x$ and a sampled response $y$, PPO maximises

$$r(x, y) - \beta\log\frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)}$$

whose second term averages to $\beta\,D_{KL}(\pi_\theta\|\pi_{\text{ref}})$ over responses from $\pi_\theta$: it is the Monte Carlo estimate from this post. Without it the policy learns to exploit the reward model, writing text that scores well without being any better. The policy comes first, so this is the reverse, mode-seeking direction. GRPO, from the DeepSeekMath paper, drops PPO's value network and puts the KL straight into the loss, estimated at each sampled token as $\rho - \log\rho - 1$ with $\rho = \pi_{\text{ref}}/\pi_\theta$. That estimate is never negative and, on tokens sampled from $\pi_\theta$, averages to the KL. (PPO's own optional KL penalty, between the old and the new policy, is a different use: it limits the size of each update.)

Takeaways

  • The KL-Divergence $D_{KL}(P\|Q) = \sum_x P(x)\log\frac{P(x)}{Q(x)}$ is the $P$-weighted average of the log relative change from $Q$ to $P$: how surprised a model $Q$ is by data from $P$, in nats when $\log$ is the natural logarithm. It is the cross-entropy minus the entropy, $H(P, Q) - H(P)$, so minimising a cross-entropy loss minimises a KL-Divergence.
  • It is not a distance. It is never negative and is zero only when $P = Q$, but it is not symmetric ($0.443$ against $1.307$ for our two Gaussians), and the direction matters: forward KL tends to cover every mode, while reverse KL tends to lock onto one.
  • For two Gaussians there is a closed form, $\log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} - \frac{1}{2}$. When there is none, as for a mixture, the Monte Carlo average of $\log P(x) - \log Q(x)$ over samples from $P$ works, with an error that shrinks like $1/\sqrt{N}$.

References

  1. S. Kullback and R. A. Leibler, "On Information and Sufficiency", The Annals of Mathematical Statistics 22(1), 79–86, 1951.
  2. T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd edition, Wiley, 2006. Chapter 2 covers relative entropy and Gibbs' inequality.
  3. K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press, 2022. Section 6.2 covers relative entropy (KL divergence), including the KL between two Gaussians and forward versus reverse KL.
  4. C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006. Section 10.1.2 compares the two directions of KL on a mixture of two Gaussians.
  5. TensorFlow Probability, tensorflow_probability/python/distributions/normal.py, the source of the Normal-Normal KL quoted above (Apache License 2.0).
  6. PyTorch, torch.distributions.kl.kl_divergence, used above to check the formula. The page lists every pair of distributions it has a closed form for; a mixture is not among them.
  7. D. P. Kingma and M. Welling, "Auto-Encoding Variational Bayes", ICLR 2014, arXiv:1312.6114. Appendix B gives the closed-form KL term for a Gaussian encoder.
  8. G. Hinton, O. Vinyals and J. Dean, "Distilling the Knowledge in a Neural Network", 2015, arXiv:1503.02531.
  9. J. Schulman, F. Wolski, P. Dhariwal, A. Radford and O. Klimov, "Proximal Policy Optimization Algorithms", 2017, arXiv:1707.06347.
  10. L. Ouyang et al., "Training language models to follow instructions with human feedback", NeurIPS 2022, arXiv:2203.02155. The KL penalty to the supervised model in RLHF.
  11. Z. Shao et al., "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", 2024, arXiv:2402.03300. Section 4.1 introduces GRPO.
  12. J. Schulman, "Approximating KL Divergence", 2020. The per-token estimator that GRPO uses.