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

Reading map and next steps

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

log⁡p(X)−log⁡q(X),X∼p.\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(p∥q)\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(q∥p)\mathrm{KL}(q\|p) versus KL(p∥q)\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.

Section prompt

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

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

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(p∥q)=∞\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(p∥q)≥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[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. This is why individual signed terms can be negative while the total divergence is never negative.

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.

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. If pp is 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 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(p∥q)=∫p(x)log⁡p(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.

Section prompt

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

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 qq assigns zero probability to an event that pp 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.

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 qq while pp stays fixed. Before the KL totals appear, predict whether KL(p∥q)\mathrm{KL}(p\|q), KL(q∥p)\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(p∥q)\mathrm{KL}(p\|q) and KL(q∥p)\mathrm{KL}(q\|p). Individual terms can be negative, but the total KL is nonnegative.

Missing a data mode makes KL(p∥q)\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(q∥p)\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.

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(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)}.
Equation 2
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)].
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 · KL Divergence (Relative Entropy)

Try the idea in your own words

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

Concept · Current object

KL Divergence (Relative Entropy)

Source boundary: sources: goodfellow-2016-deep-learning

Object context and links

Information Theory

concept:information-theory/kl-divergence
Choose a task

Explain the mechanism

For KL Divergence (Relative Entropy): What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Local to this page session. Not saved after leaving or reloading.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer does not erase help history. Outside help cannot be verified here.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    This draft and any AI response do not establish mastery. Try a different case later without help; this page has not measured that learning.

    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