Bring the mental model from Distributions; this page will reuse it instead of restarting from zero.
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.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
You have two distributions over the same outcomes. Distribution p is the one you use for averaging, and distribution q is the one whose probabilities you are testing. How much worse are the log-probabilities from q on outcomes drawn from p?
KL divergence answers that directional question. It is not a symmetric distance between two shapes. It is an expected regret:
If p says an event happens and q assigns it tiny probability, the regret is large. If p says an event never happens, that event does not directly matter for 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) versus 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 p, but your code was optimized for q, KL is the expected extra number of nats you spend per sample.
The letters are local. In supervised learning below, p is usually the data or target distribution and q is the model distribution. In a policy penalty such as 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.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let p and q be probability distributions on the same finite or countable outcome space X. The KL divergence from p to q is
Equivalently,
All logarithms here are natural logs, so the units are nats. Terms with p(x)=0 contribute 0. If p(x)>0 and q(x)=0, then KL(p∥q)=∞. That support condition is not a technical footnote; it is the source of the "missing data mode" failure.
KL is nonnegative:
with equality exactly when p=q as distributions, up to events with probability zero.
One quick way to see the nonnegativity is to let R=q(X)/p(X) for outcomes where p(X)>0. Since log is concave,
But Ep[R]=∑x:p(x)>0q(x)≤1, so Ep[logR]≤0. Multiplying by −1 gives KL(p∥q)≥0. This is why individual signed terms can be negative while the total divergence is never negative.
KL is generally asymmetric:
The asymmetry comes from the expectation. In KL(p∥q), samples are drawn from p. In KL(q∥p), samples are drawn from q. Changing the averaging distribution changes which mistakes are visited often.
The cross-entropy identity is
Here
and
The identity is just the pointwise equality
averaged under p. If p is fixed, minimizing cross-entropy over qθ is the same as minimizing KL(p∥qθ), because H(p) does not depend on the model. This is the clean finite-discrete version of the maximum-likelihood bridge: empirical data define p, the model supplies qθ, and training punishes low probability on observed outcomes.
For continuous variables with densities p(x) and q(x) relative to the same base measure,
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.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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 q assigns zero probability to an event that p can sample, forward KL is infinite.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Live Concept Demo
Explore KL Divergence (Relative Entropy)
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Choose what to inspect in KL Divergence (Relative Entropy). This shared fallback is an observation guide, not evidence of learning.
Use the presets or sliders to change q while p stays fixed. Before the KL totals appear, predict whether KL(p∥q), 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) and KL(q∥p). Individual terms can be negative, but the total KL is nonnegative.
Missing a data mode makes KL(p∥q) spike because p samples that mode and q scores it poorly. Putting extra mass where the reference distribution is small makes KL(q∥p) spike because q now samples from places the reference considers unlikely.
The sliders keep every q weight positive, so the browser demo shows near-misses rather than exact infinities. The exact q(x)=0 support-failure case is handled in the math definition and code above.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
Concept: KL Divergence (Relative Entropy)
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
Object contextInformation Theory
concept:information-theory/kl-divergenceKL Divergence (Relative Entropy)
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
Start with the prediction checkpoint, then compare the reveal to the mental model.
Take this moveStudy modes
Keep the object fixed; change the lens.Route back through the notebook
Carry the same object through intuition, math, code, and demo.
KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.
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.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.

Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
concept:information-theory/kl-divergencesources: goodfellow-2016-deep-learning
Open the closest source note before trusting the local explanation.
1 selected-object source shown first; 1 reference total.
Audit the claim boundary, then ask from the same selected object.
Chapter 3 grounds KL divergence, cross-entropy, and information-theoretic notation used in deep learning.
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...
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...
Claim Review
KL divergence is a directional expected log-probability mismatch between distributions; it explains cross-entropy training, variational inference, and KL-regularized alignment.
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
concept:information-theory/kl-divergencesources: goodfellow-2016-deep-learning
Treat every claim as provisional until source support and a local witness agree.
1 structured claim check on this concept.
Run the prediction or practice transfer before asking for a grounded review.
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.
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.
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...
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-07Practice 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.
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
concept:information-theory/kl-divergencesources: goodfellow-2016-deep-learning
Use one state from KL Divergence (Relative Entropy) to explain what changes, why it changes, and which assumption the explanation needs.
No learner move yet; no learning state is inferred.
Write first, use only the help you need, then try a new case without it.
Use one state from KL Divergence (Relative Entropy) to explain what changes, why it changes, and which assumption the explanation needs.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Write an attempt before asking the companion.
0 of 3 progressive hints opened.
This draft and any AI response do not establish mastery; a later unassisted case can.
- ObjectConceptKL Divergence (Relative Entropy)
- PredictBefore revealKL Divergence (Relative Entropy) prediction
- WitnessCompare codeKL Divergence (Relative Entropy) code witness 1
- RoomAsk groundedChecking 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.Open the draft below to save one note and next action in this browser.
KL Divergence (Relative Entropy)
What is the smallest example that makes KL Divergence (Relative Entropy) click without losing the math?
These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.
Source ids goodfellow-2016-deep-learning must support the exact object, not just the surrounding topic.
Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.
Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.
The learner can state the mechanism in their own words
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays locally in this browser for concept:information-theory/kl-divergence.
- 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
- 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
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