Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

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.

published · difficulty 3/5 · 14 min read

01

01

Intuition

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

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

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

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.logp(X)logq(X),Xp.

If ppp says an event happens and qqq assigns it tiny probability, the regret is large. If ppp says an event never happens, that event does not directly matter for KL(pq)\mathrm{KL}(p\|q)KL(pq) 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)KL(qp) versus KL(pq)\mathrm{KL}(p\|q)KL(pq) 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 ppp, but your code was optimized for qqq, KL is the expected extra number of nats you spend per sample.

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

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

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

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let ppp and qqq be probability distributions on the same finite or countable outcome space X\mathcal XX. The KL divergence from ppp to qqq 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)}.KL(pq)=xXp(x)logq(x)p(x).

Equivalently,

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

All logarithms here are natural logs, so the units are nats. Terms with p(x)=0p(x)=0p(x)=0 contribute 000. If p(x)>0p(x)>0p(x)>0 and q(x)=0q(x)=0q(x)=0, then KL(pq)=\mathrm{KL}(p\|q)=\inftyKL(pq)=. 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,KL(pq)0,

with equality exactly when p=qp=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)R=q(X)/p(X) for outcomes where p(X)>0p(X)>0p(X)>0. Since log\loglog is concave,

Ep[logR]logEp[R].\mathbb E_p[\log R]\le \log \mathbb E_p[R].Ep[logR]logEp[R].

But Ep[R]=x:p(x)>0q(x)1\mathbb E_p[R]=\sum_{x:p(x)>0}q(x)\le 1Ep[R]=x:p(x)>0q(x)1, so Ep[logR]0\mathbb E_p[\log R]\le 0Ep[logR]0. Multiplying by 1-11 gives KL(pq)0\mathrm{KL}(p\|q)\ge 0KL(pq)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).KL(pq)=KL(qp).

The asymmetry comes from the expectation. In KL(pq)\mathrm{KL}(p\|q)KL(pq), samples are drawn from ppp. In KL(qp)\mathrm{KL}(q\|p)KL(qp), samples are drawn from qqq. 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).H(p,q)=H(p)+KL(pq).

Here

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

and

H(p)=xp(x)logp(x).H(p)=-\sum_x p(x)\log p(x).H(p)=xp(x)logp(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}logq(x)=logp(x)+logq(x)p(x)

averaged under ppp. If ppp is fixed, minimizing cross-entropy over qθq_\thetaqθ is the same as minimizing KL(pqθ)\mathrm{KL}(p\|q_\theta)KL(pqθ), because H(p)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 ppp, the model supplies qθq_\thetaqθ, and training punishes low probability on observed outcomes.

For continuous variables with densities p(x)p(x)p(x) and q(x)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.KL(pq)=p(x)logq(x)p(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.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

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

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
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 qqq assigns zero probability to an event that ppp can sample, forward KL is infinite.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

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

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

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 inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Variational Autoencoders

Choose what to inspect in KL Divergence (Relative Entropy). This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the presets or sliders to change qqq while ppp stays fixed. Before the KL totals appear, predict whether KL(pq)\mathrm{KL}(p\|q)KL(pq), KL(qp)\mathrm{KL}(q\|p)KL(qp), 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)KL(pq) and KL(qp)\mathrm{KL}(q\|p)KL(qp). Individual terms can be negative, but the total KL is nonnegative.

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

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

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: KL Divergence (Relative Entropy)

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

BeforeDistributionsNow4/4 sections readyTryManipulate one control and predict the visible change.NextVariational Autoencoders
Object contextInformation Theory
ConceptLearner lens

KL Divergence (Relative Entropy)

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

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inDistributions

Bring the mental model from Distributions; this page will reuse it instead of restarting from zero.

Work hereKL 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.

Carry outVariational Autoencoders

The next edge should feel earned: use the demo prediction here before following Variational Autoencoders.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptKL Divergence (Relative Entropy)Information Theory

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.

Demo notes 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 readyDemo notes 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.

Object - ConceptKL Divergence (Relative Entropy)Question

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

concept:information-theory/kl-divergence
Boundary

sources: goodfellow-2016-deep-learning

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · book · 2016Deep LearningGoodfellow, Bengio, and Courville
Located CF editorial boundary

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

Used here as

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...

Caveat

Reviewed 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...

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.

Object - ConceptKL Divergence (Relative Entropy)Question

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

concept:information-theory/kl-divergence
Boundary

sources: goodfellow-2016-deep-learning

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

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.
Used here as

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.

Local witness
Equation 1
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)}.
Equation 2
KL(pq)=EXp[logp(X)logq(X)].\mathrm{KL}(p\|q)=\mathbb E_{X\sim p}[\log p(X)-\log q(X)].
Caveat

Reviewed 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, cont...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. 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 notebook

Use the idea, then test it somewhere new

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

AttemptNo learning claim inferred
Object - ConceptKL Divergence (Relative Entropy)Question

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

concept:information-theory/kl-divergence
Boundary

sources: goodfellow-2016-deep-learning

Check

Use one state from KL Divergence (Relative Entropy) to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from KL Divergence (Relative Entropy) to explain what changes, why it changes, and which assumption the explanation needs.

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.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: goodfellow-2016-deep-learning
  1. ObjectConceptKL Divergence (Relative Entropy)
  2. PredictBefore revealKL Divergence (Relative Entropy) prediction
  3. WitnessCompare codeKL Divergence (Relative Entropy) code witness 1
  4. RoomAsk groundedChecking local snapshot
ConceptKL Divergence (Relative Entropy)Information Theory
Code witness comparisonKL Divergence (Relative Entropy) code witness 1assert np.all(v >= 0)Prediction before revealKL Divergence (Relative Entropy) predictionManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?Checking local snapshot

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?

Source boundaryInspect source ids: goodfellow-2016-deep-learningStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk what would make "KL Divergence (Relative Entropy)" feel predictable rather than familiar.
Assumption

Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic.

Source-checking summary

Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

Proposed experiment

Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: goodfellow-2016-deep-learning
04Next moveSave one next action
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
Object-attached 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 Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "KL Divergence (Relative Entropy)" feel predictable rather than familiar." | assumption: Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: goodfellow-2016-deep-learning" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. 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. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "KL Divergence (Relative Entropy)" feel predictable rather than familiar. - Assumption to keep visible: Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

concept/concept-notebook/information-theory/kl-divergence concept:information-theory/kl-divergence