KL Divergence (Relative Entropy)
What does it cost to predict with Q when the outcomes really come from P?
The idea
KL divergence is the extra surprise you pay, on average, for scoring outcomes with when they are drawn from : each outcome costs , weighted by how often produces it. The average is taken over , so swapping the two can change the answer.
Builds on Distributions and Cross-Entropy.
The picture
A model answers questions, and its answers fall into four kinds: true, paraphrase, distractor and off-topic. says how often each kind really turns up. is the model's guess at the same four frequencies. The first panel sets them side by side.
What one outcome costs. When an outcome happens, a model that believed is surprised by ; one that knew would have been surprised by only . The difference, , is what believing cost on that draw. It is positive where underrates the outcome and negative where overrates it. The second panel weights each difference by how often produces that outcome, because that is how often the cost is paid.
The total. Add the weighted costs and you have . The negative terms never win: has only 100% to hand out, so rating one outcome too high means rating another too low, and the shortfall always costs more than the excess gives back. The total is zero only when equals , and it is infinite if calls impossible something does.
Both ways round. Nothing makes special except that it does the averaging. averages over what produces instead, so it charges for different mistakes, and the third panel shows the two totals disagreeing. That is why KL is called a divergence and not a distance.
The mathematics
Let and be probability distributions on the same finite or countable outcome space . The KL divergence from to is
Equivalently,
Logarithms are natural, so the units are nats. Terms with contribute . If and for any outcome, then : the model has ruled out something the data does.
KL is nonnegative:
with equality exactly when as distributions, up to events with probability zero.
To see why, let for outcomes where . Since is concave,
But , so . Multiplying by gives . Single terms can be negative; the total cannot.
KL is generally asymmetric:
The asymmetry comes from the expectation. In , samples are drawn from . In , samples are drawn from . Changing the averaging distribution changes which mistakes are visited often. Which one goes first is a choice: in supervised training it is the data; in the penalty used when fine-tuning a policy, it is the model being trained.
The cross-entropy identity is
Here
and
The identity is just the pointwise equality
averaged under . With fixed, minimizing cross-entropy over is the same as minimizing , because does not depend on the model. This is the bridge to maximum likelihood: the data define , the model supplies .
For continuous variables with densities and relative to the same base measure,
It is still an average of a log ratio, taken under the first distribution.
Support first
On a finite set of outcomes, is finite exactly when wherever , so the first thing to check is support. Take on three outcomes. If , then , because produces the third outcome and rules it out, while is finite, because never visits that outcome. Replace the zero by a near miss, , and both directions become finite:
The first term of the forward sum is negative, , where overrates the first outcome; the total is not. The forward direction happens to be the larger one here; that is a property of these numbers, not a rule about the two directions.
Beyond finite sets, the condition becomes absolute continuity: must give probability zero to every event that does. That is necessary for a finite divergence but not sufficient. On the positive integers, take and . Every is positive, yet grows like , and diverges, so .
Try it
First a worked example, then one to finish, then problems on your own. Check your answer before you look at the solution. Answers typed here are not kept when you leave.
1 · Worked example
The figure's total, by hand
and . Find in nats.
Ratios. for each outcome: .
Say the next step to yourself first.2 · Finish it
The other direction
Same and , but now find : the ratios flip, and does the weighting. The first steps are done. Give the total to three decimal places.
Ratios. : .
Logs. .
Weight by , first two. and .
- Your turn.
3 · On your own
What the loss is hiding
The data follow . After more training, a model's cross-entropy on them falls to nats. How far is the model from now, measured as ?
4 · On your own
Ruling an outcome out
The model moves its 1% on off-topic to true: . is unchanged. What happens to the two directions?
5 · Finish it
A near miss instead of a zero
Three outcomes A, B, C with . A model that gave C probability would make infinite. This one gives it a little: . The first two terms are done. What is , in nats? Give four decimal places.
A. . Negative: Q overrates A.
B. .
- Your turn.
6 · On your own
Which direction survives?
Two new distributions on A, B, C: and . One of and is infinite. Find the one that is finite, in nats, to four decimal places.
The code
import math
import numpy as np
def check_distribution(v):
v = np.asarray(v, dtype=float)
assert np.all(v >= 0)
assert abs(v.sum() - 1.0) < 1e-12
return v
def entropy(p):
p = check_distribution(p)
return float(sum(-px * math.log(px) for px in p if px > 0))
def cross_entropy(p, q):
p = check_distribution(p)
q = check_distribution(q)
assert p.shape == q.shape
if np.any((p > 0) & (q == 0)):
return math.inf
return float(sum(-px * math.log(qx) for px, qx in zip(p, q) if px > 0))
def kl(p, q):
p = check_distribution(p)
q = check_distribution(q)
assert p.shape == q.shape
if np.any((p > 0) & (q == 0)):
return math.inf
return float(sum(px * (math.log(px) - math.log(qx)) for px, qx in zip(p, q) if px > 0))
# Shapes: p and q are length-K categorical distributions.
# Supervised reading: p=data/target, q=model.
# Policy-regularization reading for KL(q||p): q=new policy, p=reference.
p = [0.55, 0.25, 0.15, 0.05]
q = [0.80, 0.15, 0.04, 0.01]
h_p = entropy(p)
h_pq = cross_entropy(p, q)
kl_pq = kl(p, q)
kl_qp = kl(q, p)
assert abs(h_pq - (h_p + kl_pq)) < 1e-12
print("KL(p || q):", round(kl_pq, 4))
print("KL(q || p):", round(kl_qp, 4))
print("H(p,q):", round(h_pq, 4))
print("H(p)+KL(p||q):", round(h_p + kl_pq, 4))
It prints 0.2004 and 0.1542 for the two directions, and 1.3101 twice: cross-entropy is entropy plus KL. When gives zero probability to an outcome can produce, kl returns infinity rather than failing.
Keep it
Why is usually different from ?
Answer from memory, then check
Each direction averages over its first distribution. charges for mistakes where puts mass; charges where does. Different outcomes get visited, so different mistakes get counted.
A single term can be negative. Why can the total never be?
Answer from memory, then check
has only a total of 1 to hand out, so overrating one outcome means underrating another, and the cost of underrating always outweighs the refund. The total is 0 only when .
When is infinite?
Answer from memory, then check
When gives probability 0 to an outcome that can produce: that outcome costs . The reverse, putting mass where has none, makes infinite instead.
Before computing term by term, what should you check?
Answer from memory, then check
That is positive on every outcome can produce. If not, the divergence is infinite and no arithmetic is needed. On a finite set of outcomes, if it is, the divergence is finite.
How are cross-entropy, entropy and KL related, and what does it mean for training?
Answer from memory, then check
. With the data fixed, is a constant, so minimising cross-entropy is exactly minimising .
You fit to a two-peaked . Which direction punishes for missing one of the peaks, and which lets settle on just one?
Answer from memory, then check
punishes a missed peak, because samples there and scores it badly; spreads to cover both. only looks where puts mass, so can sit on one peak and pay little.
Recalling an answer from memory makes it last longer than rereading it (Roediger and Karpicke, 2006). Add these 6 cards and they come back tomorrow, then after gaps of 3, 7, 16, 35 and 75 days while you still remember them. They stay in this browser only.
The edge
Which direction to minimise is a modelling choice with real consequences, and there is no single right answer. Fitting by minimising , as maximum likelihood does, spreads to cover everything does. Minimising , as standard variational inference does, lets lock onto one mode and understate uncertainty (Bishop, 2006, §10.1; Blei, Kucukelbir & McAuliffe, 2017). Variational inference uses the reverse direction largely because it can be computed without the true posterior, not because it is the better fit. Language-model fine-tuning with human feedback adds a penalty that keeps the new policy near the model it started from (Ouyang et al., 2022). How strong that leash should be, what it protects, and what it lets through are still being worked out.