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 QQ when they are drawn from PP: each outcome costs log⁡(p/q)\log(p/q), weighted by how often PP produces it. The average is taken over PP, 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. PP says how often each kind really turns up. QQ 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 QQ is surprised by −log⁡q-\log q; one that knew PP would have been surprised by only −log⁡p-\log p. The difference, log⁡(p/q)\log(p/q), is what believing QQ cost on that draw. It is positive where QQ underrates the outcome and negative where QQ overrates it. The second panel weights each difference by how often PP produces that outcome, because that is how often the cost is paid.

The total. Add the weighted costs and you have KL(P∥Q)\mathrm{KL}(P\|Q). The negative terms never win: QQ 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 QQ equals PP, and it is infinite if QQ calls impossible something PP does.

Both ways round. Nothing makes PP special except that it does the averaging. KL(Q∥P)\mathrm{KL}(Q\|P) averages over what QQ 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.

Predict first

P=[0.55, 0.25, 0.15, 0.05]P = [0.55,\ 0.25,\ 0.15,\ 0.05] over true, paraphrase, distractor, off-topic; the model's Q=[0.80, 0.15, 0.04, 0.01]Q = [0.80,\ 0.15,\ 0.04,\ 0.01]. Before you touch the figure: which outcome adds the most to KL(P∥Q)\mathrm{KL}(P\|Q)?

The mathematics

Let pp and qq be probability distributions on the same finite or countable outcome space X\mathcal X. The KL divergence from pp to qq is

KL(p∥q)=∑x∈Xp(x)log⁡p(x)q(x).\mathrm{KL}(p\|q)=\sum_{x\in\mathcal X}p(x)\log\frac{p(x)}{q(x)}.

Equivalently,

KL(p∥q)=EX∼p[log⁡p(X)−log⁡q(X)].\mathrm{KL}(p\|q)=\mathbb E_{X\sim p}[\log p(X)-\log q(X)].

Logarithms are natural, so the units are nats. Terms with p(x)=0p(x)=0 contribute 00. If p(x)>0p(x)>0 and q(x)=0q(x)=0 for any outcome, then KL(p∥q)=∞\mathrm{KL}(p\|q)=\infty: the model has ruled out something the data does.

KL is nonnegative:

KL(p∥q)≥0,\mathrm{KL}(p\|q)\ge 0,

with equality exactly when p=qp=q as distributions, up to events with probability zero.

To see why, let R=q(X)/p(X)R=q(X)/p(X) for outcomes where p(X)>0p(X)>0. Since log⁡\log is concave,

Ep[log⁡R]≤log⁡Ep[R].\mathbb E_p[\log R]\le \log \mathbb E_p[R].

But Ep[R]=∑x:p(x)>0q(x)≤1\mathbb E_p[R]=\sum_{x:p(x)>0}q(x)\le 1, so Ep[log⁡R]≤0\mathbb E_p[\log R]\le 0. Multiplying by −1-1 gives KL(p∥q)≥0\mathrm{KL}(p\|q)\ge 0. Single terms can be negative; the total cannot.

KL is generally asymmetric:

KL(p∥q)≠KL(q∥p).\mathrm{KL}(p\|q)\ne\mathrm{KL}(q\|p).

The asymmetry comes from the expectation. In KL(p∥q)\mathrm{KL}(p\|q), samples are drawn from pp. In KL(q∥p)\mathrm{KL}(q\|p), samples are drawn from qq. 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 KL(πθ∥πref)\mathrm{KL}(\pi_\theta\|\pi_{\mathrm{ref}}) used when fine-tuning a policy, it is the model being trained.

The cross-entropy identity is

H(p,q)=H(p)+KL(p∥q).H(p,q)=H(p)+\mathrm{KL}(p\|q).

Here

H(p,q)=−∑xp(x)log⁡q(x),H(p,q)=-\sum_x p(x)\log q(x),

and

H(p)=−∑xp(x)log⁡p(x).H(p)=-\sum_x p(x)\log p(x).

The identity is just the pointwise equality

−log⁡q(x)=−log⁡p(x)+log⁡p(x)q(x)\begin{aligned} -\log q(x) &= -\log p(x) \\ &\quad + \log\frac{p(x)}{q(x)} \end{aligned}

averaged under pp. With pp fixed, minimizing cross-entropy over qθq_\theta is the same as minimizing KL(p∥qθ)\mathrm{KL}(p\|q_\theta), because H(p)H(p) does not depend on the model. This is the bridge to maximum likelihood: the data define pp, the model supplies qθq_\theta.

For continuous variables with densities p(x)p(x) and q(x)q(x) relative to the same base measure,

KL(p∥q)=∫p(x)log⁡p(x)q(x) dx.\mathrm{KL}(p\|q)=\int p(x)\log\frac{p(x)}{q(x)}\,dx.

It is still an average of a log ratio, taken under the first distribution.

Support first

On a finite set of outcomes, KL(p∥q)\mathrm{KL}(p\|q) is finite exactly when q(x)>0q(x)>0 wherever p(x)>0p(x)>0, so the first thing to check is support. Take p=(1/2,1/4,1/4)p=(1/2,1/4,1/4) on three outcomes. If q0=(3/4,1/4,0)q_0=(3/4,1/4,0), then KL(p∥q0)=∞\mathrm{KL}(p\|q_0)=\infty, because pp produces the third outcome and q0q_0 rules it out, while KL(q0∥p)=34log⁡32≈0.304\mathrm{KL}(q_0\|p)=\tfrac34\log\tfrac32\approx0.304 is finite, because q0q_0 never visits that outcome. Replace the zero by a near miss, qε=(3/4,3/16,1/16)q_\varepsilon=(3/4,3/16,1/16), and both directions become finite:

KL(p∥qε)=12log⁡23+14log⁡43+14log⁡4=34log⁡43≈0.216,KL(qε∥p)=516log⁡2716≈0.164.\mathrm{KL}(p\|q_\varepsilon)=\tfrac12\log\tfrac23+\tfrac14\log\tfrac43+\tfrac14\log4=\tfrac34\log\tfrac43\approx0.216, \qquad \mathrm{KL}(q_\varepsilon\|p)=\tfrac5{16}\log\tfrac{27}{16}\approx0.164 .

The first term of the forward sum is negative, 12log⁡23≈−0.203\tfrac12\log\tfrac23\approx-0.203, where qεq_\varepsilon 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: pp must give probability zero to every event that qq does. That is necessary for a finite divergence but not sufficient. On the positive integers, take p(k)=6/(π2k2)p(k)=6/(\pi^2k^2) and q(k)=2−kq(k)=2^{-k}. Every q(k)q(k) is positive, yet log⁡(p(k)/q(k))\log\big(p(k)/q(k)\big) grows like klog⁡2k\log2, and ∑kp(k) k\sum_k p(k)\,k diverges, so KL(p∥q)=∞\mathrm{KL}(p\|q)=\infty.

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. 1 · Worked example

    The figure's total, by hand

    P=[0.55, 0.25, 0.15, 0.05]P = [0.55,\ 0.25,\ 0.15,\ 0.05] and Q=[0.80, 0.15, 0.04, 0.01]Q = [0.80,\ 0.15,\ 0.04,\ 0.01]. Find KL(P∥Q)\mathrm{KL}(P\|Q) in nats.

    1. Ratios. p/qp/q for each outcome: [0.6875, 1.667, 3.75, 5][0.6875,\ 1.667,\ 3.75,\ 5].

    Say the next step to yourself first.
  2. 2 · Finish it

    The other direction

    Same PP and QQ, but now find KL(Q∥P)\mathrm{KL}(Q\|P): the ratios flip, and QQ does the weighting. The first steps are done. Give the total to three decimal places.

    1. Ratios. q/pq/p: [1.455, 0.600, 0.267, 0.200][1.455,\ 0.600,\ 0.267,\ 0.200].

    2. Logs. [0.375, −0.511, −1.322, −1.609][0.375,\ -0.511,\ -1.322,\ -1.609].

    3. Weight by qq, first two. 0.80×0.375=+0.3000.80 \times 0.375 = +0.300 and 0.15×(−0.511)=−0.0770.15 \times (-0.511) = -0.077.

    4. Your turn.

  3. 3 · On your own

    What the loss is hiding

    The data follow PP. After more training, a model's cross-entropy on them falls to 1.1501.150 nats. How far is the model from PP now, measured as KL(P∥Q)\mathrm{KL}(P\|Q)?

  4. 4 · On your own

    Ruling an outcome out

    The model moves its 1% on off-topic to true: Q=[0.81, 0.15, 0.04, 0]Q = [0.81,\ 0.15,\ 0.04,\ 0]. PP is unchanged. What happens to the two directions?

    Choose one

  5. 5 · Finish it

    A near miss instead of a zero

    Three outcomes A, B, C with P=[1/2, 1/4, 1/4]P = [1/2,\ 1/4,\ 1/4]. A model that gave C probability 00 would make KL(P∥Q)\mathrm{KL}(P\|Q) infinite. This one gives it a little: Q=[3/4, 3/16, 1/16]Q = [3/4,\ 3/16,\ 1/16]. The first two terms are done. What is KL(P∥Q)\mathrm{KL}(P\|Q), in nats? Give four decimal places.

    1. A. 12log⁡1/23/4=12log⁡23=−0.2027\tfrac12 \log\frac{1/2}{3/4} = \tfrac12\log\tfrac23 = -0.2027. Negative: Q overrates A.

    2. B. 14log⁡1/43/16=14log⁡43=0.0719\tfrac14 \log\frac{1/4}{3/16} = \tfrac14\log\tfrac43 = 0.0719.

    3. Your turn.

  6. 6 · On your own

    Which direction survives?

    Two new distributions on A, B, C: R=[1/2, 1/2, 0]R = [1/2,\ 1/2,\ 0] and S=[1/2, 1/4, 1/4]S = [1/2,\ 1/4,\ 1/4]. One of KL(R∥S)\mathrm{KL}(R\|S) and KL(S∥R)\mathrm{KL}(S\|R) 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 qq gives zero probability to an outcome pp can produce, kl returns infinity rather than failing.

Keep it

  1. Why is KL(P∥Q)\mathrm{KL}(P\|Q) usually different from KL(Q∥P)\mathrm{KL}(Q\|P)?

    Answer from memory, then check

    Each direction averages over its first distribution. KL(P∥Q)\mathrm{KL}(P\|Q) charges for mistakes where PP puts mass; KL(Q∥P)\mathrm{KL}(Q\|P) charges where QQ does. Different outcomes get visited, so different mistakes get counted.

  2. A single term plog⁡(p/q)p\log(p/q) can be negative. Why can the total never be?

    Answer from memory, then check

    QQ 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 Q=PQ = P.

  3. When is KL(P∥Q)\mathrm{KL}(P\|Q) infinite?

    Answer from memory, then check

    When QQ gives probability 0 to an outcome that PP can produce: that outcome costs log⁡(p/0)=∞\log(p/0) = \infty. The reverse, QQ putting mass where PP has none, makes KL(Q∥P)\mathrm{KL}(Q\|P) infinite instead.

  4. Before computing KL(P∥Q)\mathrm{KL}(P\|Q) term by term, what should you check?

    Answer from memory, then check

    That QQ is positive on every outcome PP 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.

  5. How are cross-entropy, entropy and KL related, and what does it mean for training?

    Answer from memory, then check

    H(P,Q)=H(P)+KL(P∥Q)H(P,Q) = H(P) + \mathrm{KL}(P\|Q). With the data PP fixed, H(P)H(P) is a constant, so minimising cross-entropy is exactly minimising KL(P∥Q)\mathrm{KL}(P\|Q).

  6. You fit QQ to a two-peaked PP. Which direction punishes QQ for missing one of the peaks, and which lets QQ settle on just one?

    Answer from memory, then check

    KL(P∥Q)\mathrm{KL}(P\|Q) punishes a missed peak, because PP samples there and QQ scores it badly; QQ spreads to cover both. KL(Q∥P)\mathrm{KL}(Q\|P) only looks where QQ puts mass, so QQ 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 QQ by minimising KL(P∥Q)\mathrm{KL}(P\|Q), as maximum likelihood does, spreads QQ to cover everything PP does. Minimising KL(Q∥P)\mathrm{KL}(Q\|P), as standard variational inference does, lets QQ 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 KL(π∥πref)\mathrm{KL}(\pi\|\pi_{\text{ref}}) 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.

Next thoughtIf a KL penalty holds a model near its old self, how do you train it towards what people prefer without letting it drift into gaming the reward?RLHF: Reward Modeling + KL-Regularized Policy Optimization →
The prediction check: for five preset models, predict which KL direction is larger, then reveal the totals and cross-entropy

Limits of this page

  • Four outcomes and a hand-chosen PP and QQ. A language model compares distributions over tens of thousands of tokens, one term per token, exactly as here.
  • Logarithms are natural, so every value is in nats; divide by ln⁡2≈0.693\ln 2 \approx 0.693 for bits.
  • Only discrete distributions appear. For densities the sum becomes an integral, and a density value is not itself a probability.
  • The figure moves bars in steps of 0.1%, so it can reach an exact 0 (and an infinite KL), but not every real-valued QQ.
  • The Python runs on your machine, not in the page.

Sources

  1. Goodfellow, Bengio, and Courville (2016). Deep Learning.

    Chapter 3 grounds KL divergence, cross-entropy, and information-theoretic notation used in deep learning.

  2. Kullback and Leibler (1951). On Information and Sufficiency.

    Annals of Mathematical Statistics 22(1), 79–86. Introduces I(1:2), the mean information per observation for discriminating one distribution from another (today's KL divergence), and shows it is nonnegative.

  3. Cover and Thomas (2006). Elements of Information Theory (2nd ed.).

    Wiley. Chapter 2 defines relative entropy, proves it is nonnegative (the information inequality) and shows it is not symmetric.

  4. Bishop (2006). Pattern Recognition and Machine Learning.

    Springer. Section 10.1 compares minimizing KL(q‖p) and KL(p‖q): the first tends to lock onto one mode, the second spreads to cover all of them.

  5. Blei, Kucukelbir, and McAuliffe (2017). Variational Inference: A Review for Statisticians.

    Journal of the American Statistical Association 112(518), 859–877. Variational inference minimizes KL(q‖p) through the ELBO, which avoids the intractable evidence and tends to underestimate posterior variance.

  6. Ouyang et al. (2022). Training language models to follow instructions with human feedback.

    NeurIPS 2022. Fine-tunes with reinforcement learning from human feedback, adding a per-token KL penalty that keeps the policy close to the supervised starting model.

What the claims rest on

Central claim: KL divergence is the average log-probability ratio between two distributions, taken under the first. Training with cross-entropy minimizes it, variational inference minimizes it in the other direction, and KL-regularized fine-tuning uses it as a penalty.

Each claim below lists the passages it cites and how far it has been checked against them. These are the site’s own checks, not independent replication.

Claim (checked against the cited passages): KL divergence is a directional expectation under the first distribution of a log probability ratio; it is nonnegative, generally asymmetric, and differs from cross-entropy by the fixed entropy of the target distribution.

Sources: Deep Learning

What the sources support: Goodfellow et al. define KL divergence as relative entropy with an expected log-ratio form, relate it to cross-entropy, and use the same probability-information notation for deep learning objectives.

On this page: the note on Deep Learning, Equation 1, Equation 2, Code example 1, the figure

Caveat: Covers distributions on the same finite or countable space and the cross-entropy identity with the first distribution fixed; not measure-theoretic or continuous edge cases, optimization guarantees, or the uses of KL in variational inference and alignment.

Connections

Builds on Distributions and Cross-Entropy.

Leads to Variational Autoencoders, RLHF: Reward Modeling + KL-Regularized Policy Optimization and Direct Preference Optimization.

Cite this page

Continuous Function. “KL Divergence (Relative Entropy).” Revised 2026-10-09. https://continuousfunction.ai/domains/information-theory/kl-divergence/

BibTeX
@misc{cf-kl-divergence,
  title = {KL Divergence (Relative Entropy)},
  author = {{Continuous Function}},
  year = {2026},
  note = {Revised 2026-10-09},
  url = {https://continuousfunction.ai/domains/information-theory/kl-divergence/}
}