Information Theory

KL Divergence (Relative Entropy)

KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 14mlive demo
Editorial information-theory illustration of two probability distributions with asymmetric mismatch regions and local contribution bars.

Concept Structure

KL Divergence (Relative Entropy)

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
3next concepts
2related links

Learner Contract

What this page should let you do.

You are here becauseKL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

This Information Theory concept is the current object: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | code witness expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Then go nextVariational Autoencoders

Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.

Test the linkManipulate one control and predict the visible change.Then continue to Variational Autoencoders

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources1 cited
Codeattached
Demolive
Reviewed2026-05-07
Updatedpage 2026-05-05

Object flow

4/4 sections readyAsk about thisResearch room
ConceptKL Divergence (Relative Entropy)Information Theory
1 source attachedLocal snapshot ready
concept:information-theory/kl-divergence
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You have two distributions over the same outcomes. Distribution pp is the one you use for averaging, and distribution qq is the one whose probabilities you are testing. How much worse are the log-probabilities from qq on outcomes drawn from pp?

KL divergence answers that directional question. It is not a symmetric distance between two shapes. It is an expected regret:

logp(X)logq(X),Xp.\log p(X)-\log q(X),\qquad X\sim p.

If pp says an event happens and qq assigns it tiny probability, the regret is large. If pp says an event never happens, that event does not directly matter for KL(pq)\mathrm{KL}(p\|q) because it is never sampled under the averaging distribution.

This direction is why KL appears in several different guises:

  • In maximum likelihood and cross-entropy, the data distribution is the averaging distribution, so missing a data mode is expensive.
  • In KL-regularized alignment, the averaging distribution is often the new policy and the second distribution is a reference policy, so putting new-policy mass where the reference has little mass is expensive.
  • In variational inference, with a restricted approximation family, choosing KL(qp)\mathrm{KL}(q\|p) versus KL(pq)\mathrm{KL}(p\|q) changes whether an approximation tends to seek one mode or cover many modes.

The extra-code-length analogy is useful: if samples really come from pp, but your code was optimized for qq, KL is the expected extra number of nats you spend per sample.

The letters are local. In supervised learning below, pp is usually the data or target distribution and qq is the model distribution. In a policy penalty such as KL(πθπref)\mathrm{KL}(\pi_\theta\|\pi_{\mathrm{ref}}), the first distribution is the new policy and the second distribution is the reference. The invariant idea is the direction of the expectation.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

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(pq)=xXp(x)logp(x)q(x).\mathrm{KL}(p\|q)=\sum_{x\in\mathcal X}p(x)\log\frac{p(x)}{q(x)}.

Equivalently,

KL(pq)=EXp[logp(X)logq(X)].\mathrm{KL}(p\|q)=\mathbb E_{X\sim p}[\log p(X)-\log q(X)].

All logarithms here are natural logs, 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, then KL(pq)=\mathrm{KL}(p\|q)=\infty. That support condition is not a technical footnote; it is the source of the "missing data mode" failure.

KL is nonnegative:

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

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

One quick way to see the nonnegativity is to 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[logR]logEp[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[logR]0\mathbb E_p[\log R]\le 0. Multiplying by 1-1 gives KL(pq)0\mathrm{KL}(p\|q)\ge 0. This is why individual signed terms can be negative while the total divergence is never negative.

KL is generally asymmetric:

KL(pq)KL(qp).\mathrm{KL}(p\|q)\ne\mathrm{KL}(q\|p).

The asymmetry comes from the expectation. In KL(pq)\mathrm{KL}(p\|q), samples are drawn from pp. In KL(qp)\mathrm{KL}(q\|p), samples are drawn from qq. Changing the averaging distribution changes which mistakes are visited often.

The cross-entropy identity is

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

Here

H(p,q)=xp(x)logq(x),H(p,q)=-\sum_x p(x)\log q(x),

and

H(p)=xp(x)logp(x).H(p)=-\sum_x p(x)\log p(x).

The identity is just the pointwise equality

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

averaged under pp. If pp is fixed, minimizing cross-entropy over qθq_\theta is the same as minimizing KL(pqθ)\mathrm{KL}(p\|q_\theta), because H(p)H(p) does not depend on the model. This is the clean finite-discrete version of the maximum-likelihood bridge: empirical data define pp, the model supplies qθq_\theta, and training punishes low probability on observed outcomes.

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

KL(pq)=p(x)logp(x)q(x)dx.\mathrm{KL}(p\|q)=\int p(x)\log\frac{p(x)}{q(x)}\,dx.

Density values are not probabilities by themselves, and the common-reference-measure assumption matters. The practical lesson remains the same: KL compares log density ratios under one chosen averaging distribution.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
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))

The code keeps the support behavior explicit: if qq assigns zero probability to an event that pp can sample, forward KL is infinite.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the presets or sliders to change qq while pp stays fixed. Before the KL totals appear, predict whether KL(pq)\mathrm{KL}(p\|q), KL(qp)\mathrm{KL}(q\|p), or neither direction should dominate.

The top bars compare the two distributions. After the reveal, the contribution rows show the signed per-outcome terms for KL(pq)\mathrm{KL}(p\|q) and KL(qp)\mathrm{KL}(q\|p). Individual terms can be negative, but the total KL is nonnegative.

Missing a data mode makes KL(pq)\mathrm{KL}(p\|q) spike because pp samples that mode and qq scores it poorly. Putting extra mass where the reference distribution is small makes KL(qp)\mathrm{KL}(q\|p) spike because qq now samples from places the reference considers unlikely.

The sliders keep every qq weight positive, so the browser demo shows near-misses rather than exact infinities. The exact q(x)=0q(x)=0 support-failure case is handled in the math definition and code above.

Live Concept Demo

Explore KL Divergence (Relative Entropy)

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what KL Divergence (Relative Entropy) should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

Prediction open01 / Intuition
Editorial information-theory illustration of two probability distributions with asymmetric mismatch regions and local contribution bars.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change KL Divergence (Relative Entropy) should make visible.

Visual Inquiry

Make the image answer a mathematical question

KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make KL Divergence (Relative Entropy) easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

book · 2016Deep LearningGoodfellow, Bengio, and Courville

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

Open source

Claim Review

KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources1 reference

goodfellow-2016-deep-learning

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedKL 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.Claim metadata: source checked

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.

Sources: Deep LearningReviewed finite/countable same-space distributions and Ch3 cross-entropy identity with first distribution fixed. Demo keeps q positive, showing near-misses, not infinite-KL failures. Not measure theory, continuous edge cases, optimization guarantees, VI, or KL alignment uses.A bounded review summary is present; still check caveats and exact source scope.

Checked Goodfellow Ch.3: KL is E_{x~P}[log(P/Q)], nonnegative, generally asymmetric, and cross-entropy is H(P,Q)=H(P)+D_KL(P||Q)=-E_P log Q. With P fixed, H(P) is constant, so cross-entropy differs from forward KL by fixed target entropy. Local math/code/demo match finite/countable p-weighted log-ratio, support rules, directional terms, nonnegative totals, and H(p,q)=H(p)+KL(p||q).

Reviewer: codex+oracle; reviewed 2026-05-07

Practice Loop

Try the idea before it explains itself

KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in KL Divergence (Relative Entropy).

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptKL Divergence (Relative Entropy)Information Theory

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptInformation Theory

KL Divergence (Relative Entropy)

Anchored question

What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:information-theory/kl-divergence.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: goodfellow-2016-deep-learning
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - KL Divergence (Relative Entropy) Object key: concept:information-theory/kl-divergence Context: Information Theory Anchor id: concept/concept-notebook/information-theory/kl-divergence Open question: What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math? Evidence to inspect: - Source ids to inspect: goodfellow-2016-deep-learning - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/information-theory/kl-divergence concept:information-theory/kl-divergence