A Deep Dive into KL Divergence
A deep dive into KL divergence and how the direction shapes the pre- and post-training of LLMs
A lot of progress has been made in post-training algorithms in recent years, and KL divergence has proven to be a critical component in a number of loss functions used in post-training. This article aims to provide a mathematical understanding of KL divergence and how the direction of KL divergence shapes the pre- and post-training of LLMs.
The Formula
KL divergence is a measure of how different two probability distributions are. The inputs are two probability distributions, say $P$ and $Q$, and the output is a non-negative scalar value. The formula for KL divergence is given by:
\[D_{KL}(P \parallel Q) = \sum_i P(x_i) \log \frac{P(x_i)}{Q(x_i)}\]The continuous version of the formula is given by:
\[D_{KL}(P \parallel Q) = \int_{-\infty}^{\infty} p(x) \log \frac{p(x)}{q(x)} dx\]$x_i$ is an event in the sample space and $P(x_i)$ and $Q(x_i)$ are the probabilities of that event under distributions $P$ and $Q$ respectively. Consider two biased coins. Each coin has two possible outcomes (events), heads and tails, with different probabilities.
Asymmetry of KL Divergence
Unlike distance metrics such as Euclidean distance, KL divergence is asymmetric. This means that $D_{KL}(P \parallel Q) \neq D_{KL}(Q \parallel P)$.
Let’s demonstrate this by expanding our example of two biased coins. Let’s say we have two coins, Coin A and Coin B. Coin A has a 90% chance of landing heads and a 10% chance of landing tails, while Coin B has a 40% chance of landing heads and a 60% chance of landing tails.
KL divergence from Coin A to Coin B is given by:
\[D_{KL}(A \parallel B) = 0.9 \log \frac{0.9}{0.4} + 0.1 \log \frac{0.1}{0.6} \approx 0.5507\]KL divergence from Coin B to Coin A is given by:
\[D_{KL}(B \parallel A) = 0.4 \log \frac{0.4}{0.9} + 0.6 \log \frac{0.6}{0.1} \approx 0.7507\]The two values are different ($0.5507$ vs. $0.7507$), which shows us that the direction of KL divergence matters.
Non-Negativity of KL Divergence
Looking at the formula for KL divergence, it isn’t immediately clear why KL divergence is always non-negative.
If two distributions are exactly the same, then $\log \frac{P(x_i)}{Q(x_i)} = \log 1 = 0$ for all $x_i$, and therefore $D_{KL}(P \parallel Q) = 0$.
However, if they aren’t the same, there can be certain events for which $P(x_i) > Q(x_i)$, and for those events $\log \frac{P(x_i)}{Q(x_i)} > 0$. For other events, where $P(x_i) < Q(x_i)$, $\log \frac{P(x_i)}{Q(x_i)} < 0$.
Remember that $\log(x)$ is negative when $x < 1$ and positive when $x > 1$.
So why is KL divergence non-negative? The proof relies on the fact that $\log(x) \leq x - 1$ for all $x > 0$. It’s collapsed below since it isn’t needed to follow the rest of the post. The takeaway is that $D_{KL}(P \parallel Q) \geq 0$, with equality only when $P = Q$.
Show the proof that KL divergence is non-negative
Let’s first convince ourselves that $\log(x) \leq x - 1$ for all $x > 0$ by plotting both $\log(x)$ and $x - 1$ on the same graph. We can see that $\log(x)$ always stays below or touches $x - 1$.
Show the plotting code
1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.01, 5, 100)
plt.plot(x, np.log(x), label='log(x)')
plt.plot(x, x - 1, label='x - 1')
plt.axhline(0, color='black', lw=0.5, ls='--')
plt.axvline(1, color='black', lw=0.5, ls='--')
plt.title('log(x) vs x - 1')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
We can confirm our observation by taking the derivative of $f(x) = \log(x) - (x - 1)$ and showing that its global maximum is at $x = 1$ and $f(1) = 0$. If the maximum value of $f$ is $0$, then $f(x) \leq 0$ for all $x > 0$, which is exactly the claim $\log(x) \leq x - 1$.
\[\frac{d}{dx} f(x) = \frac{1}{x} - 1\] \[\frac{d}{dx} f(x) = \frac{1 - x}{x}\]Since $x > 0$, the sign of the derivative is determined by the sign of $1 - x$:
- For $0 < x < 1$, $\frac{d}{dx} f(x) > 0$, so $f$ is strictly increasing.
- For $x > 1$, $\frac{d}{dx} f(x) < 0$, so $f$ is strictly decreasing.
- At $x = 1$, $\frac{d}{dx} f(x) = 0$.
So $f$ rises until $x = 1$ and falls afterwards, which makes $x = 1$ the global maximum. Evaluating $f$ there:
\[f(1) = \log(1) - (1 - 1) = 0 - 0 = 0\]Therefore $f(x) \leq f(1) = 0$ for all $x > 0$, which gives us
\[\log(x) \leq x - 1 \quad \text{for all } x > 0\]with equality only at $x = 1$.
Putting it together
Now we can prove that $D_{KL}(P \parallel Q) \geq 0$. Start by flipping the ratio inside the log, using $-\log(a) = \log\frac{1}{a}$ to move a minus sign out front:
\[D_{KL}(P \parallel Q) = \sum_i P(x_i) \log \frac{P(x_i)}{Q(x_i)} = -\sum_i P(x_i) \log \frac{Q(x_i)}{P(x_i)}\]Apply $\log(x) \leq x - 1$ with $x = \frac{Q(x_i)}{P(x_i)}$:
\[\log \frac{Q(x_i)}{P(x_i)} \leq \frac{Q(x_i)}{P(x_i)} - 1\]Now multiply both sides by $-P(x_i)$. Since $P(x_i) \geq 0$, we are multiplying by a non-positive number, which flips the direction of the inequality:
\[-P(x_i) \log \frac{Q(x_i)}{P(x_i)} \geq -P(x_i)\left(\frac{Q(x_i)}{P(x_i)} - 1\right)\]Next, let’s expand the right-hand side:
\[-P(x_i)\left(\frac{Q(x_i)}{P(x_i)} - 1\right) = -P(x_i) \cdot \frac{Q(x_i)}{P(x_i)} + P(x_i) \cdot 1\]The $P(x_i)$ in the first term cancels with the denominator:
\[-P(x_i) \cdot \frac{Q(x_i)}{P(x_i)} + P(x_i) = -Q(x_i) + P(x_i) = P(x_i) - Q(x_i)\]Putting the pieces together, for every event $x_i$ we have:
\[-P(x_i) \log \frac{Q(x_i)}{P(x_i)} \geq P(x_i) - Q(x_i)\]Flipping the fraction inside a log flips the sign of the log, i.e., $\log\frac{Q(x_i)}{P(x_i)} = -\log\frac{P(x_i)}{Q(x_i)}$. So the minus sign on the left-hand side cancels with the sign of the log:
\[-P(x_i) \log \frac{Q(x_i)}{P(x_i)} = -P(x_i) \cdot \left(-\log \frac{P(x_i)}{Q(x_i)}\right) = P(x_i) \log \frac{P(x_i)}{Q(x_i)}\]The right-hand side is exactly the $i$-th term of the original definition of $D_{KL}(P \parallel Q)$. So the left-hand side of our per-event inequality is the $i$-th term of the KL divergence, and summing it over all events $x_i$ gives:
\[\sum_i \left[-P(x_i) \log \frac{Q(x_i)}{P(x_i)}\right] = \sum_i P(x_i) \log \frac{P(x_i)}{Q(x_i)} = D_{KL}(P \parallel Q)\]Summing the right-hand side of the per-event inequality over all events gives $\sum_i \left(P(x_i) - Q(x_i)\right)$, so:
\[D_{KL}(P \parallel Q) \geq \sum_i \left(P(x_i) - Q(x_i)\right) = \sum_i P(x_i) - \sum_i Q(x_i)\]Both $P$ and $Q$ are probability distributions, so each sums to $1$:
\[\sum_i P(x_i) - \sum_i Q(x_i) = 1 - 1 = 0\]Therefore:
\[D_{KL}(P \parallel Q) \geq 0\]KL Divergence and Cross-Entropy Loss
Cross-entropy loss is commonly used to train language models during both pre-training and supervised fine-tuning (SFT). The cross-entropy loss between two probability distributions $P$ and $Q$ is defined as:
\[H(P, Q) = -\sum_i P(x_i) \log Q(x_i)\]In the context of language models, $P$ represents the true distribution of the data (often represented as one-hot vectors for the correct tokens), while $Q$ represents the predicted distribution output by the model being trained.
Let’s show how cross-entropy loss is related to KL divergence. We can rewrite the KL divergence formula as follows:
\[D_{KL}(P \parallel Q) = \sum_i P(x_i) \log \frac{P(x_i)}{Q(x_i)} = \sum_i P(x_i) \log P(x_i) - \sum_i P(x_i) \log Q(x_i)\]Note that the first term, $\sum_i P(x_i) \log P(x_i)$, is the negative entropy of $P$, denoted as $-H(P)$. Therefore, we can express KL divergence in terms of cross-entropy:
\[D_{KL}(P \parallel Q) = -H(P) + H(P, Q)\]or equivalently:
\[H(P, Q) = D_{KL}(P \parallel Q) + H(P)\]Therefore, minimizing the cross-entropy loss $H(P, Q)$ is equivalent to minimizing the KL divergence $D_{KL}(P \parallel Q)$, up to an additive constant $H(P)$ that does not depend on the model’s predictions.
Forward vs Reverse KL Divergence
The asymmetrical nature of KL divergence raises the question of which direction of KL divergence should be used in a given scenario.
To better gauge this, let’s take a look at when forward KL and reverse KL become large. If you’re wondering why we don’t look at the minimum instead, it’s because both forward and reverse KL have the same minimum when both distributions are the same, i.e. $D_{KL}(P \parallel Q) = D_{KL}(Q \parallel P) = 0$ when $P = Q$.
Let’s call $P$ our target distribution, i.e., the distribution we want to approximate as well as possible. $Q$ is the distribution of the model we’re actively training. This could be the policy model for RL, a student model for distillation, or a model being pre-trained.
Forward KL Divergence is Mode-Covering
Revisiting the formula for forward KL divergence:
\[D_{KL}(P \parallel Q) = \sum_i P(x_i) \log \frac{P(x_i)}{Q(x_i)}\]When $Q(x_i) \ll P(x_i)$ for some event $x_i$, the ratio $P(x_i)/Q(x_i)$ becomes very large, and $\log(P(x_i)/Q(x_i))$ becomes very positive.
Since $P(x_i)$ is also positive, the term $P(x_i) \cdot \log(P(x_i)/Q(x_i))$ contributes a large positive value to the sum, increasing the overall KL divergence.
In cases where $P(x_i)$ has a low probability mass, it doesn’t matter what $Q(x_i)$ is; the contribution to the KL divergence will be small.
This means that forward KL divergence is sensitive to events that are likely under the target distribution $P$ but unlikely under the model distribution $Q$.
In other words, $Q$ needs to assign a non-zero probability to every event that has a non-zero probability under the target distribution $P$.
For a continuous distribution, a mode is defined as:
A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a locally maximum value.
This means that $Q$ needs to align with all the modes of $P$ to minimize forward KL divergence. This is why forward KL divergence is often referred to as “mode-covering” because it encourages the model to cover all modes of the target distribution.
Reverse KL Divergence is Mode-Seeking
Revisiting the formula for reverse KL divergence:
\[D_{KL}(Q \parallel P) = \sum_i Q(x_i) \log \frac{Q(x_i)}{P(x_i)}\]In contrast to forward KL divergence, when $Q(x_i) \gg P(x_i)$ for some event $x_i$, the ratio $Q(x_i)/P(x_i)$ becomes very large, and $\log(Q(x_i)/P(x_i))$ becomes very positive.
So $Q$ should be trained to predict low probabilities whenever $P$ predicts low probabilities, and its peaks should align with a peak of $P$.
In cases where $Q(x_i)$ has a low probability mass, it doesn’t matter what $P(x_i)$ is; the contribution to the KL divergence will be small. That is, unlike forward KL divergence, a peak in $P$ that is not aligned with a peak in $Q$ will not contribute to the KL divergence.
So $Q$ needs to seek a mode of $P$ to minimize reverse KL divergence. This is why reverse KL divergence is often referred to as “mode-seeking” because it encourages the model to seek a mode of the target distribution.
Visualizing Forward vs Reverse KL Divergence
To illustrate this, let’s assume that $P$ is a bimodal distribution and $Q$ is a unimodal distribution. Let’s visualize how forward and reverse KL divergence behave in this scenario.
We’ll take $P$ to be an equal mixture of two Gaussians centered at $-3$ and $3$, and $Q$ to be a single Gaussian with a fixed standard deviation of 1. We then slide the mean of $Q$ from left to right and compute both $D_{KL}(P \parallel Q)$ and $D_{KL}(Q \parallel P)$ numerically at each position by approximating the integral with a sum over a fine grid.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np
# ---- Distributions -------------------------------------------------------
x = np.linspace(-10, 10, 4000)
dx = x[1] - x[0]
def log_normal(x, mu, sigma):
z = (x - mu) / sigma
return -0.5 * z ** 2 - np.log(sigma * np.sqrt(2 * np.pi))
# P: bimodal target, an equal mixture of N(-3, 1) and N(3, 1)
log_p = np.logaddexp(log_normal(x, -3, 1.0),
log_normal(x, 3, 1.0)) - np.log(2)
p = np.exp(log_p)
# Q: unimodal model N(mu, SIGMA); we slide mu from left to right
SIGMA = 1.0
def kl_scores(mu):
log_q = log_normal(x, mu, SIGMA)
q = np.exp(log_q)
forward = np.sum(p * (log_p - log_q)) * dx # D_KL(P || Q)
reverse = np.sum(q * (log_q - log_p)) * dx # D_KL(Q || P)
return forward, reverse
mus = np.linspace(-6, 6, 241)
fwd, rev = np.array([kl_scores(m) for m in mus]).T
Show the plotting and animation code (continues from the code above)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
# ---- Plot ----------------------------------------------------------------
Y_MAX = 12 # forward KL explodes when Q misses a mode; clip the axis
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 7), constrained_layout=True)
# Top panel: the two densities
ax1.fill_between(x, p, color="#cfcfcf", label="P (target, bimodal)")
q_line, = ax1.plot([], [], color="#191919", lw=2, label="Q (model, unimodal)")
ax1.set_xlim(-8, 8)
ax1.set_ylim(0, 0.5)
ax1.set_xlabel("x")
ax1.set_ylabel("density")
ax1.legend(loc="upper left", frameon=False)
score_txt = ax1.text(0.98, 0.95, "", transform=ax1.transAxes,
ha="right", va="top", fontsize=11, family="monospace")
# Bottom panel: both KL scores as a function of where Q sits
ax2.plot(mus, np.clip(fwd, 0, Y_MAX), color="#257de0", lw=2,
label=r"forward KL $D_{KL}(P\,\|\,Q)$")
ax2.plot(mus, np.clip(rev, 0, Y_MAX), color="#f47230", lw=2,
label=r"reverse KL $D_{KL}(Q\,\|\,P)$")
dot_f, = ax2.plot([], [], "o", color="#257de0", ms=9, mec="white", mew=2)
dot_r, = ax2.plot([], [], "o", color="#f47230", ms=9, mec="white", mew=2)
vline = ax2.axvline(mus[0], color="#666666", lw=0.8, ls="--")
ax2.set_xlim(mus[0], mus[-1])
ax2.set_ylim(0, Y_MAX)
ax2.set_xlabel(r"mean of Q ($\mu$)")
ax2.set_ylabel("KL divergence (nats, clipped)")
ax2.legend(loc="upper center", frameon=False)
for ax in (ax1, ax2):
ax.spines[["top", "right"]].set_visible(False)
def update(i):
mu = mus[i]
q_line.set_data(x, np.exp(log_normal(x, mu, SIGMA)))
dot_f.set_data([mu], [min(fwd[i], Y_MAX)])
dot_r.set_data([mu], [min(rev[i], Y_MAX)])
vline.set_xdata([mu, mu])
score_txt.set_text(f"mu = {mu:+.2f}\nforward KL = {fwd[i]:7.2f}\n"
f"reverse KL = {rev[i]:7.2f}")
return q_line, dot_f, dot_r, vline, score_txt
# Slide left -> right, then pause on the last frame
frames = list(range(len(mus))) + [len(mus) - 1] * 15
anim = FuncAnimation(fig, update, frames=frames, interval=50)
anim.save("kl_sliding.gif", writer=PillowWriter(fps=20), dpi=80)
Watch the bottom panel as $Q$ slides across:
- Reverse KL (orange) has two minima, one at each mode of $P$. Its lowest value is about $0.69 = \ln 2$, which is what you get when $Q$ sits perfectly on one mode and completely ignores the other (that mode carries half of $P$’s mass). Reverse KL doesn’t care which mode $Q$ picks, only that it picks one. This is mode-seeking.
- Forward KL (blue) has a single minimum at $\mu = 0$, where $Q$ sits in the valley between the two modes. Parking $Q$ on one mode would leave the other mode with almost no probability under $Q$, and forward KL punishes that heavily, so it prefers to straddle both. This is mode-covering.
Note: In this example we only optimized the mean of $Q$ while keeping its standard deviation fixed. In practice, the model can also adjust its variance, which can help it cover multiple modes more effectively.
Visualizing with Gradient Descent
Instead of sliding $Q$ by hand, let’s let both its mean $\mu$ and its standard deviation $\sigma$ be learned by gradient descent, once with forward KL as the loss and once with reverse KL. Both runs start from exactly the same $Q$, a narrow Gaussian ($\sigma = 0.5$) at a random position ($\mu \approx -1.66$, drawn with a fixed seed), and use the same learning rate.
We also clip the gradient norm to $5$ in both runs, just for the sake of the visualization. Forward KL’s gradient is huge when $Q$ starts narrow and misses a mode, so without clipping $\sigma$ would jump from $0.5 \to 6$ in a single step.
We parameterize $Q$ by $(\mu, \log \sigma)$ so that $\sigma$ always stays positive, and let PyTorch’s autograd compute the gradients.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import math
import numpy as np
import torch
# ---- Target P and grid ---------------------------------------------------
x = torch.linspace(-12, 12, 4000, dtype=torch.float64)
dx = (x[1] - x[0]).item()
def log_normal(x, mu, sigma):
z = (x - mu) / sigma
return -0.5 * z ** 2 - torch.log(sigma) - 0.5 * math.log(2 * math.pi)
one = torch.tensor(1.0, dtype=torch.float64)
log_p = torch.logaddexp(log_normal(x, -3 * one, one),
log_normal(x, 3 * one, one)) - math.log(2)
p = log_p.exp()
# ---- Losses --------------------------------------------------------------
# Q = N(mu, sigma). We optimise theta = (mu, log_sigma) so that sigma
# always stays positive.
def forward_kl(theta):
mu, log_sigma = theta
log_q = log_normal(x, mu, log_sigma.exp())
return (p * (log_p - log_q)).sum() * dx # D_KL(P || Q)
def reverse_kl(theta):
mu, log_sigma = theta
log_q = log_normal(x, mu, log_sigma.exp())
return (log_q.exp() * (log_q - log_p)).sum() * dx # D_KL(Q || P)
# ---- Gradient descent ----------------------------------------------------
def optimise(loss_fn, theta0, lr=0.05, steps=50, max_norm=5.0):
theta = torch.tensor(theta0, dtype=torch.float64, requires_grad=True)
opt = torch.optim.SGD([theta], lr=lr)
history = []
for _ in range(steps + 1):
opt.zero_grad()
loss = loss_fn(theta)
history.append((theta[0].item(), theta[1].exp().item(), loss.item()))
loss.backward()
# Clip the gradient norm. Forward KL's gradient is huge when Q starts
# narrow and misses a mode; without clipping, sigma would jump from
# 0.5 to 6 in a single step.
torch.nn.utils.clip_grad_norm_([theta], max_norm)
opt.step()
# columns of the result: mu, sigma, loss
return np.array(history)
# Same init for both runs: a random mu and a narrow sigma (0.5)
rng = np.random.default_rng(3)
START = (rng.uniform(-2, 2), np.log(0.5))
fwd_hist = optimise(forward_kl, START)
rev_hist = optimise(reverse_kl, START)
for name, h in (("forward", fwd_hist), ("reverse", rev_hist)):
print(f"{name}: mu={h[-1,0]:+.3f} sigma={h[-1,1]:.3f} loss={h[-1,2]:.4f}")
Show the plotting and animation code (continues from the code above)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
# ---- Animation -----------------------------------------------------------
xs, ps = x.numpy(), p.numpy()
def q_density(mu, sigma):
mu = torch.tensor(mu, dtype=torch.float64)
sigma = torch.tensor(sigma, dtype=torch.float64)
return log_normal(x, mu, sigma).exp().numpy()
C_FWD, C_REV, C_P, INK = "#257de0", "#f47230", "#cfcfcf", "#191919"
runs = [("Forward KL $D_{KL}(P\\,\\|\\,Q)$", fwd_hist, C_FWD),
("Reverse KL $D_{KL}(Q\\,\\|\\,P)$", rev_hist, C_REV)]
fig, axes = plt.subplots(2, 2, figsize=(10, 6.5), constrained_layout=True)
q_lines, texts, dots = [], [], []
for col, (title, hist, color) in enumerate(runs):
ax_d, ax_l = axes[0, col], axes[1, col]
ax_d.fill_between(xs, ps, color=C_P, label="P")
line, = ax_d.plot([], [], color=color, lw=2.5, label="Q")
ax_d.set_xlim(-8, 8); ax_d.set_ylim(0, 0.9)
ax_d.set_title(title)
ax_d.set_xlabel("x"); ax_d.set_ylabel("density")
ax_d.legend(loc="upper left", frameon=False)
txt = ax_d.text(0.98, 0.95, "", transform=ax_d.transAxes, ha="right",
va="top", fontsize=10, family="monospace", color=INK)
ax_l.plot(hist[:, 2], color=color, lw=2)
dot, = ax_l.plot([], [], "o", color=color, ms=9, mec="white", mew=2)
ax_l.set_xlim(0, len(hist) - 1)
# clip the huge initial forward loss so the rest of the curve is visible
ax_l.set_ylim(0, min(hist[:, 2].max(), 3) * 1.05)
ax_l.set_xlabel("gradient step"); ax_l.set_ylabel("loss (nats)")
for ax in (ax_d, ax_l):
ax.spines[["top", "right"]].set_visible(False)
q_lines.append(line); texts.append(txt); dots.append(dot)
def update(step):
for i, (_, hist, _) in enumerate(runs):
mu, sigma, loss = hist[step]
q_lines[i].set_data(xs, q_density(mu, sigma))
dots[i].set_data([step], [loss])
texts[i].set_text(f"step = {step}\nmu = {mu:+.2f}\n"
f"sigma = {sigma:.2f}\nloss = {loss:.3f}")
# one frame per gradient step, then pause on the last frame
step_frames = list(range(len(fwd_hist)))
frames = step_frames + [step_frames[-1]] * 12
anim = FuncAnimation(fig, update, frames=frames, interval=250)
# fps=4 is slow enough to follow the optimization
anim.save("kl_gradient_descent.gif", writer=PillowWriter(fps=4), dpi=80)
Visualizing just the first 50 steps highlights the mode-covering and mode-seeking behavior of forward and reverse KL respectively. Both runs begin from the same $Q$, yet within those 50 steps they head to very different places:
Forward KL widens $\sigma$ quickly (from $0.5$ to about $3$ within roughly 15 steps) as it tries to cover the far mode, and settles at $\sigma \approx 3.4$ with $\mu \approx -1.2$ after 50 steps. Its mean is still drifting slowly towards the center. This is mode-covering since it’s trying to cover all the peaks.
Reverse KL shows us how $Q$ starts drifting towards one of the modes and converges to overlapping with that mode after 50 steps. This is mode-seeking. The exact mode that $Q$ converges to is determined by the random initialization.
What does this mean for training LLMs?
Pre-training. During pre-training, we want our model to learn everything about the world, so we want it to cover all the modes of the target distribution. The cross-entropy loss used during pre-training has the same effect as minimizing forward KL divergence, as we showed in an earlier section.
Online (on-policy) distillation. This matches our toy example directly: the teacher is the target $P$ and the student is the model $Q$. The student samples its own outputs and is trained to minimize $D_{KL}(Q_{student} \parallel P_{teacher})$. Since reverse KL is mode-seeking, the student doesn’t have to spread its limited capacity over everything the teacher could say. It can lock onto the teacher’s high-probability behavior, and it is penalized for generating things the teacher considers unlikely.
RLHF/RLVR (PPO, GRPO). Here the KL term is $D_{KL}(\pi_\theta \parallel \pi_{ref})$, where the policy $\pi_\theta$ is $Q$ and the reference model $\pi_{ref}$ (the model we started from) plays the role of $P$. In RL-based training, the purpose of the KL term is to keep the policy model $Q$ from drifting too far from the reference model $P$. Since reverse KL penalizes putting probability mass where the reference model thinks it is unlikely, it makes it costly for the policy to move into behavior the reference considers very unlikely, which includes many reward hacks.
Conclusion
KL divergence measures how far one distribution is from another, and the two directions of it behave very differently:
- It is always non-negative, and it is zero only when the two distributions are identical. It is also asymmetric, so $D_{KL}(P \parallel Q) \neq D_{KL}(Q \parallel P)$ in general.
- Forward KL, $D_{KL}(P \parallel Q)$, weights every event by how likely it is under the target $P$. A model $Q$ that assigns almost no probability to something $P$ considers likely is punished heavily, so $Q$ is pushed to cover all the modes of $P$. In our toy example, a single Gaussian trained with forward KL stretched into a wide blob that spans both peaks, putting a lot of its mass in the valley between them.
- Reverse KL, $D_{KL}(Q \parallel P)$, weights every event by how likely it is under the model $Q$. Peaks of $P$ that $Q$ never visits cost nothing, but putting probability where $P$ is low is expensive, so $Q$ is pushed to lock onto a single mode. In our toy example, the Gaussian trained with reverse KL settled tightly on one peak, and which peak it chose depended on where it started.
Choosing a direction is really choosing which kind of mistake you are willing to tolerate: missing part of the target distribution (forward KL), or producing outputs in regions where the target is unlikely (reverse KL).
That is why pre-training, which minimizes cross-entropy and so forward KL, pushes a model to cover everything in its data. Post-training uses reverse KL too: against a teacher in distillation, and as a leash toward a reference model in RLHF/RLVR. In both cases the model is free to commit to a subset of behaviors instead of trying to cover everything.
References:
- Hamad, Hassan, “Forward vs Reverse KL Divergence: Why the Direction Matters”, hassanhamad.com, Sep 2025.
- Forward KL vs. Reverse KL Divergence: Mode Covering, Mode Seeking, and the Alignment Dynamics of Large Language Models
- https://stats.stackexchange.com/questions/335197/why-kl-divergence-is-non-negative