Module contents
Lesson 2 of 19Core 95 min

The Kullback-Leibler divergence

Introduce relative entropy as a measure of how wrong model q is relative to reality p. Prove nonnegativity (Gibbs' inequality), log-sum inequality, joint convexity and chain rule, and study asymmetry and differing supports. Interpret KL as expected excess surprise and mean evidence per observation for p against q.

After this lesson you can

  • Calculate D(p‖q) for discrete distributions and identify infinite values from support differences.
  • Prove Gibbs' inequality with Jensen and log-sum, including equality conditions.
  • Prove joint convexity of KL and apply its chain rule to joint and product distributions.
  • Interpret KL as expected log-likelihood ratio, or mean evidence per sample.
  • Construct counterexamples showing KL is asymmetric and fails the triangle inequality.

Before you start

Motivation: the cost of choosing the wrong model

A source emits four symbols with probabilities p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18). Each has surprise −log⁡2p(x)=1,2,3,3-\log_2 p(x) = 1, 2, 3, 3 bits, and its entropy, mean surprise, is H⁡(p)=1.75\Ent(p) = 1.75 bits: the minimum average cost of describing a source symbol. An engineer who does not know pp assumes all four symbols equally likely and designs a 2-bit-per-symbol code. It works, but pays 2−1.75=0.252 - 1.75 = 0.25 extra bits per symbol. This overhead is not a code defect: it is the cost of the engineer’s ignorance of pp, measurable without constructing a code.

That quantity is Kullback–Leibler divergence, among the objects you will encounter most on this platform. Whenever you fit a model qq to data from an unknown distribution pp, you are, knowingly or not, performing the same experiment:

  • Train with cross-entropy. A classifier or language model’s mean loss is H⁡(p^)+KL⁡(p^ ∥ qθ)\Ent(\hat p) + \KL(\hat p\,\|\,q_\theta): a parameter-independent term, data entropy, plus divergence between data and model. Minimizing loss minimizes divergence, and maximum likelihood is exactly that.
  • Regularize. RLHF adds penalty β KL⁡(πθ ∥ πref)\beta\,\KL(\pi_\theta\,\|\,\pi_{\text{ref}}) to reward to keep policy near a reference model (KL penalty control). A variational autoencoder contains a KL term between encoder and prior (VAE), and variational inference minimizes KL between an approximation and posterior.
  • Test hypotheses. Divergence sets the rate at which data distinguish hypotheses: see the following sections and the formal Stein lemma.

This lesson carefully builds divergence. First its definition and support conventions (where it breaks), then its two interpretations, informational and statistical. Next we prove structural properties with all assumptions: nonnegativity (Gibbs’ inequality), log-sum inequality, joint convexity and chain rule. It ends with what it is not: neither symmetric nor a distance. Unless stated otherwise, log⁡\log is base-2 logarithm and quantities are in bits; multiply by ln⁡2\ln 2 to convert to nats.

Definition and conventions

Let X\mathcal{X} be a finite alphabet (lesson 11 extends everything to continuous variables) and p,qp, q two distributions on X\mathcal{X}. Write supp⁡(p)={x:p(x)>0}\operatorname{supp}(p) = \{x : p(x) > 0\} for the support of pp.

The conventions are not arbitrary; they are natural limits: tlog⁡t→0t \log t \to 0 as t→0+t \to 0^+, and plog⁡(p/q)→+∞p \log(p/q) \to +\infty as q→0+q \to 0^+ with fixed p>0p > 0. This reveals asymmetric roles. The first distribution pp samples: it decides which terms count and their weights. The second qq describes: the model whose surprise is measured. A model assigning zero probability to something that occurs is infinitely wrong; a model reserving mass for something that never occurs merely wastes some probability, at finite cost.

The following histograms show where each term comes from. The sign matters.

InteractiveDrag q and see excess surprise
Probabilities of the 6 categories (drag the bars)
0.00.20.40.60.050.2010.150.2020.350.2030.250.1540.150.1550.050.106pq
Contribution of each category, pilog⁡2(pi/qi)p_i\log_2(p_i/q_i), and their sum, in bits
−0.2500.250.50−0.101−0.062+0.283+0.1845−0.0560.25Σ
q assigns less mass than p: costq assigns more mass than p: saving
Direction
KL⁡(p ∥ q)\KL(p\,\|\,q)0.255 bits
KL⁡(q ∥ p)\KL(q\,\|\,p)0.311 bits
Sum of positive terms+0.467
Sum of negative terms−0.212
H⁡(p)\Ent(p)2.283 bits
H(p,q)H(p, q)2.538 bits
Category 3 (p = 0.35, q = 0.20)+0.283
Green categories contribute negatively (where qq assigns more mass than pp), but the red contributions always outweigh them: the total is nonnegative.
Above, two six-category histograms: pp in blue and qq in orange. Drag them; remaining bars rescale so the sum remains 1. Below is each category's contribution pilog⁡2(pi/qi)p_i \log_2(p_i/q_i) and at right their sum Σ\Sigma, which is KL⁡(p ∥ q)\KL(p\,\|\,q). Green categories have negative contribution: there qq puts more mass than pp. But can the total drop below 0? Try ‘q = p’, then lower a qq bar to zero where pp has mass, and finally reverse direction and compare divergences.

Three things the figure shows and the rest of the lesson proves:

  1. Some terms are negative but the total never is. Since ∑xp(x)=∑xq(x)=1\sum_x p(x) = \sum_x q(x) = 1, wherever qq puts more mass than pp in one category it must put less in another. What is paid where qq underestimates pp always exceeds savings where it overestimates. This is Gibbs’ inequality, proved below.
  2. Lowering q(x)q(x) toward zero where p(x)>0p(x) > 0 makes divergence explode. Contribution p(x)log⁡p(x)q(x)p(x)\log\frac{p(x)}{q(x)} grows without bound; at q(x)=0q(x) = 0 it is ∞\infty and other bars cannot compensate.
  3. Directions differ. Switch from KL⁡(p ∥ q)\KL(p\,\|\,q) to KL⁡(q ∥ p)\KL(q\,\|\,p) and watch which categories dominate.

Two interpretations of the same sum

Expected excess surprise

Expand the logarithm of the ratio. For p≪qp \ll q,

KL⁡(p ∥ q)=Ep[−log⁡q(X)]⏟sorpresa media de q ante datos de p−Ep[−log⁡p(X)]⏟H⁡(p).\KL(p\,\|\,q) = \underbrace{\E_{p}\big[-\log q(X)\big]}_{\text{sorpresa media de } q \text{ ante datos de } p} - \underbrace{\E_{p}\big[-\log p(X)\big]}_{\Ent(p)} .

The first term is cross-entropy H(p,q)H(p, q): the mean bits paid when describing pp data with a code fitted to qq (lesson 5 constructs actual prefix codes and 6 studies it in depth). The second is the minimum possible cost, entropy of pp. Divergence is the difference: expected excess surprise,

H(p,q)=H⁡(p)+KL⁡(p ∥ q).H(p, q) = \Ent(p) + \KL(p\,\|\,q).

This is the motivating identity: 2=1.75+0.252 = 1.75 + 0.25. In a real code lengths are integers, and using lengths ⌈−log⁡q(x)⌉\lceil -\log q(x) \rceil costs less than one extra bit per symbol above H(p,q)H(p, q) (cost of coding with the wrong model); arithmetic coding (lesson 7) makes that rounding disappear on long sequences and excess per symbol approaches KL⁡(p ∥ q)\KL(p\,\|\,q).

The same in learning terms: if p^\hat p is a dataset’s empirical distribution and qθq_\theta a model, cross-entropy loss is H(p^,qθ)=H⁡(p^)+KL⁡(p^ ∥ qθ)H(\hat p, q_\theta) = \Ent(\hat p) + \KL(\hat p\,\|\,q_\theta). The first term does not depend on θ\theta, so training reduces a KL toward the data distribution. Minimum loss is not 0 but H⁡(p^)\Ent(\hat p): irreducible noise. Excess over that minimum, measuring model error, is exactly divergence.

Mean evidence per observation

A second statistical interpretation explains why direction matters. Given hypotheses pp (data from pp) and qq (from qq), the likelihood ratio of observation xx is p(x)/q(x)p(x)/q(x), and by the Neyman–Pearson lemma the most powerful test at a given level is based on it. Its logarithm,

Λ(x)=log⁡p(x)q(x),\Lambda(x) = \log \frac{p(x)}{q(x)},

is the evidence xx supplies for pp in bits: +1+1 bit means xx is twice as likely under pp as qq. If data come from pp, mean evidence per observation is

Ep[Λ(X)]=KL⁡(p ∥ q)≥0,y si vienen de q:Eq[Λ(X)]=−KL⁡(q ∥ p)≤0.\E_{p}[\Lambda(X)] = \KL(p\,\|\,q) \ge 0, \qquad \text{y si vienen de } q:\quad \E_{q}[\Lambda(X)] = -\KL(q\,\|\,p) \le 0 .

Divergence is evidence each observation from pp supplies on average to distinguish it from qq. With nn independent observations total evidence Sn=∑i≤nΛ(xi)S_n = \sum_{i \le n} \Lambda(x_i) is a sum of iid variables, and by the strong law of large numbers Sn/n→KL⁡(p ∥ q)S_n / n \to \KL(p\,\|\,q) almost surely: evidence for the true hypothesis grows linearly with divergence as slope. Since there is a divergence for each direction, the next simulation’s slopes differ.

InteractiveAccumulate evidence: p or q?
Accumulated evidence Sn=∑i≤nlog⁡2p(xi)q(xi)S_n = \sum_{i \le n} \log_2 \frac{p(x_i)}{q(x_i)} over 30 sequences, in bits
0102030405060010203040samples ndecide p (+6)decide q (−6)
  • 30 sequences
  • mean of 30
  • theoretical slope
  • first threshold crossing
0.50
0.90
Data come from
40
6
KL⁡(p ∥ q)\KL(p\,\|\,q)0.737 bits
KL⁡(q ∥ p)\KL(q\,\|\,p)0.531 bits
Theoretical slope KL⁡(p ∥ q)\KL(p\,\|\,q)+0.737
Measured slope Sˉn/n\bar S_n/n (n = 40)+0.769
Decided (cross ±A\pm A)30 of 30
Mean nn to decide7.8 (A/D ≈ 8.1)
Data come from pp: evidence grows at 0.737 bits per sample. From qq it would grow at 0.531: the rate depends on which hypothesis is true.
Each trajectory is Sn=∑ilog⁡2p(xi)/q(xi)S_n = \sum_i \log_2 p(x_i)/q(x_i) for a sequence of nn Bernoulli trials. Data come from pp (blue) or qq (orange). All 30 trajectories are random, but their mean (thick line) follows the line of slope KL⁡(p ∥ q)\KL(p\,\|\,q), or −KL⁡(q ∥ p)-\KL(q\,\|\,p) if data come from qq; band is μn±2σn\mu n \pm 2\sigma\sqrt{n}. Circles mark the first crossing of thresholds ±A\pm A (Wald sequential decision). Choose the example with q=Bern(0.95)q = \mathrm{Bern}(0.95) and swap pp and qq: speed changes. How many samples on average reach the threshold, and what does A/DA/D predict? What happens in the symmetric example?

Notice two things. First, slope is divergence in the true-hypothesis direction. With p=Bern(0.5)p = \mathrm{Bern}(0.5) and q=Bern(0.9)q = \mathrm{Bern}(0.9), KL⁡(p ∥ q)=0.737\KL(p\,\|\,q) = 0.737 bits and KL⁡(q ∥ p)=0.531\KL(q\,\|\,p) = 0.531 bits: if data come from pp, evidence rises by 0.7370.737 bits per sample; if from qq, it falls by 0.5310.531 bits per sample. Distinguishing one hypothesis from the other does not cost the same in both directions. Second, time to accumulate AA bits of evidence is approximately A/KL⁡A / \KL. There is an exact version. If NN is the first time ∣Sn∣≥A\abs{S_n} \ge A (Wald’s sequential test), Wald’s identity gives E[SN]=E[N]⋅KL⁡(p ∥ q)\E[S_N] = \E[N] \cdot \KL(p\,\|\,q) when data come from pp and E[N]<∞\E[N] < \infty; if probability of crossing the wrong threshold −A-A is small, SNS_N is almost always just over AA (an overshoot of a few bits), so E[N]≳A/KL⁡\E[N] \gtrsim A/\KL. With A=6A = 6 bits and the parameters above theory gives 8.18.1 samples and a simulation of 20 00020\,000 sequences averages 9.39.3 (with E[SN]≈6.8\E[S_N] \approx 6.8 bits of overshoot and only 1% crossing −A-A).

Finally, fixed-sample hypothesis testing. If type-I error (deciding qq when pp is true) is bounded by a constant, best type-II error (deciding pp when qq is true) decays as 2−nKL⁡(p ∥ q)2^{-n \KL(p\,\|\,q)} with sample size nn. This is Stein’s lemma (lesson 16), why KL⁡\KL rather than another quantity appears when asking “how much data is needed”.

Gibbs’ inequality

The earlier figure suggested the total is never negative. Now we prove it, also finding exactly when it is zero.

Proof

Let S=supp⁡(p)S = \operatorname{supp}(p). If q(x)=0q(x) = 0 for some x∈Sx \in S, then KL⁡(p ∥ q)=+∞>0\KL(p\,\|\,q) = +\infty > 0 and there is nothing to prove or equality possible (also p≠qp \ne q). So assume q(x)>0q(x) > 0 throughout SS. Function log⁡\log is strictly concave, and numbers p(x)p(x), x∈Sx \in S are positive weights summing to 1. By Jensen’s inequality,

−KL⁡(p ∥ q)=∑x∈Sp(x)log⁡q(x)p(x)  ≤  log⁡(∑x∈Sp(x) q(x)p(x))=log⁡q(S)  ≤  log⁡1=0,-\KL(p\,\|\,q) = \sum_{x \in S} p(x) \log \frac{q(x)}{p(x)} \;\le\; \log\Big(\sum_{x \in S} p(x)\, \frac{q(x)}{p(x)}\Big) = \log q(S) \;\le\; \log 1 = 0,

where q(S)=∑x∈Sq(x)≤1q(S) = \sum_{x \in S} q(x) \le 1. Hence KL⁡(p ∥ q)≥0\KL(p\,\|\,q) \ge 0.

Equality. If KL⁡(p ∥ q)=0\KL(p\,\|\,q) = 0 both inequalities are equalities. In Jensen, strict concavity forces ratio q(x)/p(x)q(x)/p(x) to be constant cc on SS. In the second, log⁡q(S)=0\log q(S) = 0 forces q(S)=1q(S) = 1. Thus 1=q(S)=∑x∈Sc p(x)=c1 = q(S) = \sum_{x \in S} c\,p(x) = c, so q=pq = p on SS, and since q(S)=1q(S) = 1, qq is zero outside SS like pp. That is, q=pq = p. The converse is immediate: if p=qp = q every ratio is 1.

∎

Another shorter proof is worth keeping handy. Use ln⁡t≤t−1\ln t \le t - 1, with equality only at t=1t = 1:

−KL⁡(p ∥ q)ln⁡2=∑x∈Sp(x)ln⁡q(x)p(x)≤∑x∈Sp(x)(q(x)p(x)−1)=q(S)−1≤0.-\KL(p\,\|\,q)\ln 2 = \sum_{x \in S} p(x) \ln\frac{q(x)}{p(x)} \le \sum_{x \in S} p(x)\Big(\frac{q(x)}{p(x)} - 1\Big) = q(S) - 1 \le 0 .

A third geometric interpretation connects it with optimization convexity. Function φ(p)=∑xp(x)log⁡p(x)\varphi(p) = \sum_x p(x) \log p(x) (negative entropy) is convex on the simplex, and its Bregman divergence φ(p)−φ(q)−∇φ(q)⊤(p−q)\varphi(p) - \varphi(q) - \nabla\varphi(q)\T(p - q) is exactly KL⁡(p ∥ q)\KL(p\,\|\,q) after simplifying ∑x(p(x)−q(x))=0\sum_x (p(x) - q(x)) = 0. KL nonnegativity is the first-order convexity condition of φ\varphi (a convex function lies above its tangent), and strict positivity follows from strict convexity of xlog⁡xx \log x (whose second derivative is 1/(xln⁡2)>01/(x \ln 2) > 0, the second-order condition).

Immediate corollaries

This follows from KL⁡(p ∥ u)=∑xp(x)log⁡(p(x)∣X∣)=log⁡∣X∣−H⁡(p)≥0\KL(p\,\|\,u) = \sum_x p(x)\log\big(p(x)\abs{\mathcal{X}}\big) = \log \abs{\mathcal{X}} - \Ent(p) \ge 0. The motivation was one case: log⁡24−1.75=0.25\log_2 4 - 1.75 = 0.25 bits excess. You have used the result without proof whenever saying “uniform distribution maximizes uncertainty”; its origin is that divergence to uniform cannot be negative.

The log-sum inequality

KL is a sum of terms alog⁡(a/b)a \log(a/b). Understanding what happens when grouping terms is key to its convexity.

The interpretation is simple: grouping bins cannot increase divergence. If ai=p(xi)a_i = p(x_i) and bi=q(xi)b_i = q(x_i) are masses pp and qq assign to a group of outcomes, the left side is those bins’ separate contribution to KL⁡(p ∥ q)\KL(p\,\|\,q), and the right their contribution merged into a single bin with masses AA and BB. This is the next lesson’s data processing inequality in miniature.

Proof

Trivial cases. If A=0A = 0 both sides are 0. If any ai>0a_i > 0 has bi=0b_i = 0, the left side is +∞+\infty. Assume A>0A > 0 and bi>0b_i > 0 whenever ai>0a_i > 0. Indices with ai=0a_i = 0 contribute nothing on the left and can only increase BB, lowering the right side (strictly if any has bi>0b_i > 0): it suffices to prove the inequality without them, with B′=∑ai>0bi≤BB' = \sum_{a_i > 0} b_i \le B, because Alog⁡AB′≥Alog⁡ABA \log\frac{A}{B'} \ge A \log \frac{A}{B}. Thus assume all ai,bi>0a_i, b_i > 0.

Function f(t)=tlog⁡tf(t) = t \log t is strictly convex on (0,∞)(0, \infty) (f′′(t)=1/(tln⁡2)>0f''(t) = 1/(t \ln 2) > 0). With weights bi/Bb_i / B summing to 1 and points ti=ai/bit_i = a_i / b_i, Jensen’s inequality gives

∑iailog⁡aibi=∑ibif(ti)=B∑ibiBf(ti)≥B f(∑ibiB ti)=Bf(AB)=Alog⁡AB.\sum_i a_i \log \frac{a_i}{b_i} = \sum_i b_i f(t_i) = B \sum_i \frac{b_i}{B} f(t_i) \ge B\, f\Big(\sum_i \frac{b_i}{B}\, t_i\Big) = B f\Big(\frac{A}{B}\Big) = A \log \frac{A}{B}.

Convexity is strict, so Jensen equality holds only if all tit_i agree. Returning to the general case, equality also requires B′=BB' = B, i.e. no indices with ai=0<bia_i = 0 < b_i: this gives stated condition ai=c bia_i = c\,b_i for every ii.

∎

Consider the most important consequence.

Proof

Fix xx and apply the two-term log-sum inequality: a1=λp1(x)a_1 = \lambda p_1(x), a2=(1−λ)p2(x)a_2 = (1 - \lambda) p_2(x), b1=λq1(x)b_1 = \lambda q_1(x), b2=(1−λ)q2(x)b_2 = (1 - \lambda) q_2(x). Then A=λp1(x)+(1−λ)p2(x)A = \lambda p_1(x) + (1 - \lambda) p_2(x) and B=λq1(x)+(1−λ)q2(x)B = \lambda q_1(x) + (1 - \lambda) q_2(x) are mixture masses, and factors λ\lambda and 1−λ1 - \lambda cancel inside ratios,

λp1(x)log⁡p1(x)q1(x)+(1−λ)p2(x)log⁡p2(x)q2(x)  ≥  pλ(x)log⁡pλ(x)qλ(x).\lambda p_1(x) \log \frac{p_1(x)}{q_1(x)} + (1 - \lambda) p_2(x) \log \frac{p_2(x)}{q_2(x)} \;\ge\; p_\lambda(x) \log \frac{p_\lambda(x)}{q_\lambda(x)} .

Summing over x∈Xx \in \mathcal{X} gives the desired inequality. (If λ∈{0,1}\lambda \in \{0, 1\} equality holds.)

∎

Mixing is generally beneficial. With p1=(1,0)p_1 = (1, 0), p2=(0,1)p_2 = (0, 1) and q1=q2=(12,12)q_1 = q_2 = (\tfrac12, \tfrac12), each pair has KL⁡=1\KL = 1 bit; their equal mixture is (12,12)(\tfrac12, \tfrac12) versus (12,12)(\tfrac12, \tfrac12), with zero divergence. The inequality can be very loose: here the left side is 00 and right 11 bit. In the 10⁵ Dirichlet pairs tested in implementation the inequality always holds and mean gap is one bit.

Consequences you will use: KL is convex in pp with fixed qq (strictly), and convex in qq with fixed pp, so minimizing over a convex set (an “information projection”, lesson 13) is convex optimization without misleading local minima. But it is not generally jointly strictly convex (if p=qp = q for both pairs, their mixture remains on diagonal p=qp = q where KL is 0, so strictness fails).

The chain rule

Entropy decomposes as H(X,Y)=H(X)+H(Y∣X)H(X, Y) = H(X) + H(Y \mid X). Divergence has the same structure, making it manageable for sequences and multivariable models.

Proof

If p(x,y)>0p(x, y) > 0 and q(x,y)>0q(x, y) > 0, then p(x),q(x)>0p(x), q(x) > 0 and p(x,y)q(x,y)=p(x)q(x)⋅p(y∣x)q(y∣x)\dfrac{p(x, y)}{q(x, y)} = \dfrac{p(x)}{q(x)}\cdot\dfrac{p(y \mid x)}{q(y \mid x)}. Taking logarithms and expectation under p(x,y)p(x, y),

KL⁡(pXY ∥ qXY)=∑x,yp(x,y)log⁡p(x)q(x)+∑x,yp(x,y)log⁡p(y∣x)q(y∣x).\KL(p_{XY}\,\|\,q_{XY}) = \sum_{x, y} p(x, y) \log \frac{p(x)}{q(x)} + \sum_{x, y} p(x, y) \log \frac{p(y \mid x)}{q(y \mid x)}.

The first summand is ∑xp(x)log⁡p(x)q(x)\sum_x p(x) \log\frac{p(x)}{q(x)} after summing over yy. In the second, p(x,y)=p(x)p(y∣x)p(x, y) = p(x) p(y \mid x) leaving ∑xp(x)∑yp(y∣x)log⁡p(y∣x)q(y∣x)\sum_x p(x) \sum_y p(y \mid x) \log\frac{p(y \mid x)}{q(y \mid x)}. Infinite cases are consistent: if p(x,y)>0=q(x,y)p(x, y) > 0 = q(x, y), either q(x)=0q(x) = 0 (and marginal divergence is ∞\infty) or q(y∣x)=0<p(y∣x)q(y \mid x) = 0 < p(y \mid x) (and the conditional for that xx is ∞\infty weighted by p(x)>0p(x) > 0). Both sides equal ∞\infty.

∎
InteractiveTotal divergence splits up
p(x, y)0.480.120.120.28y=1y=2x=1x=2q(x, y)0.240.160.300.30y=1y=2x=1x=2Chain rule0.1170.0790.047Cell-by-cell sum, Σ p(x, y) log₂ p(x, y)/q(x, y)0.244X marginalconditional, x = 1conditional, x = 2
The bars match: the difference is only floating-point rounding (less than 10−910^{-9} bits).
Distribution p
0.60
0.80
0.30
Distribution q
0.40
0.60
0.50
KL⁡(pXY ∥ qXY)\KL(p_{XY}\,\|\,q_{XY})0.2437 bits
KL⁡(pX ∥ qX)\KL(p_X\,\|\,q_X)0.1170 bits
Conditional average0.1267 bits
KL⁡(pY ∥ qY)\KL(p_Y\,\|\,q_Y) (YY marginal)0.0105 bits
Marginalizing over YY loses divergence: KL⁡(pY ∥ qY)<KL⁡(pXY ∥ qXY)\KL(p_Y\,\|\,q_Y) < \KL(p_{XY}\,\|\,q_{XY}).
Two joint distributions on X,Y∈{1,2}X, Y \in \{1, 2\}, written as p(x) p(y∣x)p(x)\,p(y \mid x). The top bar stacks three chain-rule terms: divergence of the XX marginal and conditional divergences, each weighted by p(x)p(x). The bottom bar sums p(x,y)log⁡2p(x,y)q(x,y)p(x, y)\log_2\frac{p(x,y)}{q(x,y)} cell by cell across four cells. Both measure the same thing. Try ‘Only the X marginal differs’: which terms vanish? With ‘Both independent’, what happens to total divergence? Also see how the YY marginal divergence stays below.

At initial values, p(x,y)=[0.480.120.120.28]p(x, y) = \begin{bmatrix} 0.48 & 0.12 \\ 0.12 & 0.28 \end{bmatrix} and q(x,y)=[0.240.160.300.30]q(x, y) = \begin{bmatrix} 0.24 & 0.16 \\ 0.30 & 0.30 \end{bmatrix}. Total divergence is 0.24370.2437 bits. The XX marginal contributes 0.11700.1170 (with pX=(0.6,0.4)p_X = (0.6, 0.4) and qX=(0.4,0.6)q_X = (0.4, 0.6)) and conditionals, weighted by p(x)p(x), contribute 0.6 KL⁡(Bern(0.8) ∥ Bern(0.6))+0.4 KL⁡(Bern(0.3) ∥ Bern(0.5))=0.0792+0.0475=0.12670.6\,\KL(\mathrm{Bern}(0.8)\,\|\,\mathrm{Bern}(0.6)) + 0.4\,\KL(\mathrm{Bern}(0.3)\,\|\,\mathrm{Bern}(0.5)) = 0.0792 + 0.0475 = 0.1267. Total 0.1170+0.1267=0.24370.1170 + 0.1267 = 0.2437: the same number as cellwise summation.

Three consequences of the rule:

  • Forgetting variables cannot increase divergence. The conditional term is nonnegative by Gibbs, so KL⁡(pXY ∥ qXY)≥KL⁡(pX ∥ qX)\KL(p_{XY}\,\|\,q_{XY}) \ge \KL(p_X\,\|\,q_X), with equality if and only if p(y∣x)=q(y∣x)p(y \mid x) = q(y \mid x) for every xx with p(x)>0p(x) > 0: ignored information cannot distinguish. With initial tables, the YY marginal gives only 0.01050.0105 bits versus 0.24370.2437 jointly. This is data processing for marginalization, generalized to any transformation in lesson 3.
  • It is additive on products. If p=p1×p2p = p_1 \times p_2 and q=q1×q2q = q_1 \times q_2 are product distributions, conditionals do not depend on xx and KL⁡(p ∥ q)=KL⁡(p1 ∥ q1)+KL⁡(p2 ∥ q2)\KL(p\,\|\,q) = \KL(p_1\,\|\,q_1) + \KL(p_2\,\|\,q_2). For nn iid samples, KL⁡(p⊗n ∥ q⊗n)=n KL⁡(p ∥ q)\KL(p^{\otimes n}\,\|\,q^{\otimes n}) = n\,\KL(p\,\|\,q): divergence is extensive, like entropy. This explains E[Sn]=n KL⁡(p ∥ q)\E[S_n] = n\,\KL(p\,\|\,q) in the evidence figure.
  • It decomposes token by token. For autoregressive models p(x1:T)=∏tp(xt∣x<t)p(x_{1:T}) = \prod_t p(x_t \mid x_{<t}), applying the rule TT times gives KL⁡(p1:T ∥ q1:T)=∑t=1TEx<t∼p[KL⁡(p(⋅∣x<t) ∥ q(⋅∣x<t))].\KL(p_{1:T}\,\|\,q_{1:T}) = \sum_{t=1}^{T} \E_{x_{<t} \sim p}\Big[\KL\big(p(\cdot \mid x_{<t})\,\|\,q(\cdot \mid x_{<t})\big)\Big]. Divergence between two language models over full sequences is the sum of per-token divergences averaged over prefixes generated by pp. This is penalized token by token in RLHF.

Asymmetry, supports and the triangle inequality

All the above applies separately in each direction. What fails is swapping pp and qq.

This is not an extreme-point accident. For nearby distributions KL resembles a squared distance, and squared distances do not satisfy the triangle inequality: (2d)2=4d2>2d2(2d)^2 = 4d^2 > 2d^2.

Proof

Let u=δ/qu = \delta/q, so ∑xqu=0\sum_x q u = 0. With ln⁡(1+u)=u−u2/2+u3/3−…\ln(1 + u) = u - u^2/2 + u^3/3 - \dots, the first case is ∑xq(1+u)ln⁡(1+u)=∑xq (u+12u2−16u3+⋯ )\sum_x q(1 + u)\ln(1 + u) = \sum_x q\,(u + \tfrac12 u^2 - \tfrac16 u^3 + \cdots) and the second −∑xqln⁡(1+u)=∑xq (−u+12u2−13u3+⋯ )-\sum_x q \ln(1 + u) = \sum_x q\,(-u + \tfrac12 u^2 - \tfrac13 u^3 + \cdots). The linear term vanishes because ∑xqu=∑xδ=0\sum_x q u = \sum_x \delta = 0.

∎

Both directions share second-order term 12∑xδ2/q\frac12\sum_x \delta^2/q (half Pearson χ2\chi^2 divergence, χ2(p ∥ q)=∑x(p(x)−q(x))2/q(x)\chi^2(p\,\|\,q) = \sum_x (p(x) - q(x))^2/q(x)), a positive-definite quadratic form: locally KL is squared distance, the Fisher metric seen in lesson 16. They differ in the cubic term, so far from pp the two directions’ level curves separate.

InteractiveD(p‖q) versus D(q‖p) on the simplex
KL⁡(p ∥ q)\KL(p\,\|\,q) as a function of qq
KL⁡(q ∥ p)\KL(q\,\|\,p) as a function of qq
0.05 bits2.5 bits or more (includes ∞)level ccquadratic approximation
0.15
KL⁡(p ∥ q)\KL(p\,\|\,q)0.704 bits
KL⁡(q ∥ p)\KL(q\,\|\,p)0.728 bits
pp(0.50, 0.30, 0.20)
qq(0.15, 0.20, 0.65)
Near pp the divergences almost agree (the dashed ellipse approximates them). Move away and watch them separate.
The triangle is the set of distributions over 3 outcomes (each vertex is concentrated on one). Fix pp and drag qq: left colors q↦KL⁡(p ∥ q)q \mapsto \KL(p\,\|\,q), right q↦KL⁡(q ∥ p)q \mapsto \KL(q\,\|\,p), with level bands. Thick line is chosen level cc and dashed its quadratic approximation. Are they circles? Do they agree far from pp? Move qq toward an edge where pp has mass: one map explodes and the other does not. Then lower pp to an edge (last example) and inspect the right map.

What to take from the figure:

  • They are not circles. Level curves near pp are ellipses of quadratic form 12∑xδ2/p\frac12\sum_x \delta^2/p, narrower in directions moving a low-probability outcome (deviation 0.050.05 in an outcome of probability 0.050.05 weighs much more than in one of 0.50.5, so a shorter step reaches the same level). This is “information geometry”: distance between distributions is not Euclidean.
  • Both directions agree nearby and separate far away, as the cubic term predicts: almost identical bands inside the ellipse, different outside.
  • Edges explode in one direction only. With pp interior and q→q \to on the edge, KL⁡(p ∥ q)→∞\KL(p\,\|\,q) \to \infty, while KL⁡(q ∥ p)\KL(q\,\|\,p) remains bounded by log⁡(1/min⁡xp(x))\log(1/\min_x p(x)). With pp on the edge, KL⁡(q ∥ p)=∞\KL(q\,\|\,p) = \infty throughout the interior: the right map fills with the highest-level color. A model whose support exceeds the data’s is no problem for KL⁡(p ∥ q)\KL(p\,\|\,q) (it merely wastes mass), but smaller support is an irreparable problem.

The consequence for model training is serious. Maximum likelihood minimizes KL⁡(p^ ∥ qθ)\KL(\hat p\,\|\,q_\theta): if data contain a symbol assigned zero probability by the model, loss is infinite. Hence outputs are parametrized with softmax, never giving exact zeros, yet near-zero probability where data exist produces huge losses and gradients. The other direction KL⁡(qθ ∥ p)\KL(q_\theta\,\|\,p) (minimized by variational inference and many penalties) punishes the reverse: model mass where data have none. Each prefers a type of error. Study this as forward and reverse KL in lesson 15.

What can be saved from the idea of distance? A metric requires symmetrization: square root of Jensen–Shannon divergence KL⁡(p ∥ m)/2+KL⁡(q ∥ m)/2\KL(p\,\|\,m)/2 + \KL(q\,\|\,m)/2 with m=(p+q)/2m = (p + q)/2 does satisfy the triangle inequality (lesson 12). KL is instead a divergence in information geometry: nonnegative, zero only on the diagonal and smooth, but neither symmetric nor triangular.

Implementation from scratch

First divergence with all conventions and checks from earlier sections: motivation, asymmetry, triangle inequality, supports and Gibbs on 10510^5 Dirichlet pairs. Function kl_lote computes 10510^5 divergences at once without loops.

[ ]KL from scratch and its propertiesBrowser
import numpy as np

def kl(p, q, base=2.0):
    """D(p||q) con las convenciones 0 log(0/q) = 0 y p log(p/0) = inf (bits por defecto)."""
    p = np.asarray(p, dtype=float)
    q = np.asarray(q, dtype=float)
    if p.shape != q.shape:
        raise ValueError("p y q deben tener la misma forma")
    if np.any(p < 0) or np.any(q < 0) or not np.isclose(p.sum(), 1) or not np.isclose(q.sum(), 1):
        raise ValueError("p y q deben ser distribuciones de probabilidad")
    soporte = p > 0                      # solo cuentan los x con p(x) > 0
    if np.any(q[soporte] == 0):
        return np.inf                    # p no es absolutamente continua respecto a q
    return float(np.sum(p[soporte] * np.log(p[soporte] / q[soporte])) / np.log(base))

def entropia(p, base=2.0):
    p = np.asarray(p, dtype=float)
    p = p[p > 0]
    return float(-np.sum(p * np.log(p)) / np.log(base))

# la motivación: describir p con un código pensado para la uniforme
p = np.array([1/2, 1/4, 1/8, 1/8])
u = np.full(4, 1/4)
print("H(p) =", entropia(p), "  coste con el código uniforme =", -np.sum(p * np.log2(u)), "  D(p||u) =", round(kl(p, u), 6))

# asimetría, soportes y desigualdad triangular
b = lambda a: [1 - a, a]
print("D(B(.1)||B(.5)) =", round(kl(b(.1), b(.5)), 4), "  D(B(.5)||B(.1)) =", round(kl(b(.5), b(.1)), 4))
print("D(B(.1)||B(.9)) =", round(kl(b(.1), b(.9)), 4), " > ", round(kl(b(.1), b(.5)) + kl(b(.5), b(.9)), 4), "= D(.1||.5) + D(.5||.9)")
print("soportes: D(p||q) =", kl([1/2, 1/2, 0], [1/2, 1/4, 1/4]), "  D(q||p) =", kl([1/2, 1/4, 1/4], [1/2, 1/2, 0]))

# Gibbs en 10^5 pares de Dirichlet, sin bucles
rng = np.random.default_rng(0)
N, K = 100_000, 5

def kl_lote(P, Q):
    """D(P_i || Q_i) en bits para cada fila de dos arrays de forma (N, K)."""
    with np.errstate(divide="ignore", invalid="ignore"):
        T = np.where(P > 0, P * np.log2(P / Q), 0.0)
    return T.sum(axis=1)

P, Q = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
D = kl_lote(P, Q)
neg = np.mean((P * np.log2(P / Q) < 0).any(axis=1))
print(f"Gibbs: mín D = {D.min():.2e}; D < 0 en {np.sum(D < -1e-12)} de {N} pares")
print(f"pares con alguna contribución negativa: {100 * neg:.1f} %   (y aun así, ninguno con total negativo)")

Minimum divergence across 10510^5 pairs is positive, although all have at least one category with negative contribution: as the first figure showed. Now joint convexity, chain rule and Pinsker’s inequality from the note above, using the same samples.

[ ]Joint convexity, chain rule and PinskerBrowser
import numpy as np

rng = np.random.default_rng(1)
N, K = 100_000, 5

def kl_lote(P, Q):
    with np.errstate(divide="ignore", invalid="ignore"):
        T = np.where(P > 0, P * np.log2(P / Q), 0.0)
    return T.sum(axis=1)

P1, Q1 = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
P2, Q2 = rng.dirichlet(np.ones(K) * 0.5, N), rng.dirichlet(np.ones(K) * 0.5, N)
lam = rng.uniform(size=(N, 1))

# convexidad conjunta: KL de la mezcla <= mezcla de KLs
izq = kl_lote(lam * P1 + (1 - lam) * P2, lam * Q1 + (1 - lam) * Q2)
der = lam[:, 0] * kl_lote(P1, Q1) + (1 - lam[:, 0]) * kl_lote(P2, Q2)
print(f"convexidad: violaciones {np.sum(izq > der + 1e-12)} de {N}; mayor (izq - der) = {np.max(izq - der):.2e}; hueco medio = {np.mean(der - izq):.3f} bits")

# Pinsker: KL >= ||p - q||_1^2 / (2 ln 2)
l1 = np.abs(P1 - Q1).sum(axis=1)
cociente = kl_lote(P1, Q1) / (l1**2 / (2 * np.log(2)))
print(f"Pinsker: cociente mínimo KL / (||p-q||_1^2 / 2 ln 2) = {cociente.min():.4f} (>= 1)")

# regla de la cadena en tablas conjuntas 4 x 3, sin ceros (con ceros hay que tener cuidado: es un ejercicio)
def kl(p, q):
    return float(np.sum(p * np.log2(p / q)))

def cadena(Pxy, Qxy):
    px, qx = Pxy.sum(axis=1), Qxy.sum(axis=1)
    condicional = sum(px[i] * kl(Pxy[i] / px[i], Qxy[i] / qx[i]) for i in range(len(px)))
    return kl(Pxy.ravel(), Qxy.ravel()), kl(px, qx) + condicional

error = 0.0
for _ in range(2000):
    A, B = rng.dirichlet(np.ones(12)).reshape(4, 3), rng.dirichlet(np.ones(12)).reshape(4, 3)
    izq, der = cadena(A, B)
    error = max(error, abs(izq - der))
print(f"regla de la cadena: error máximo en 2000 tablas aleatorias = {error:.1e}")

# la divergencia es extensiva: n muestras iid dan n veces la KL de una
p, q = np.array([0.6, 0.4]), np.array([0.5, 0.5])
p2, q2 = np.outer(p, p).ravel(), np.outer(q, q).ravel()
print("KL de un lanzamiento:", round(kl(p, q), 5), "  de dos:", round(kl(p2, q2), 5))

Convexity holds in every case, Pinsker ratio is always at least 1, and the chain rule is verified up to floating-point rounding. But that cadena implementation fails whenever a cell is zero (0 * log(0) gives nan) or an entire row has zero mass (division by zero): the final coding exercise asks you to fix it.

The library version

SciPy offers three related functions, and they are not equivalent.

FunctionComputesNotes
scipy.special.rel_entr(x, y)xln⁡(x/y)x \ln(x/y) term by termnats; 00 if x=0x = 0, ∞\infty if x>0=yx > 0 = y; preserves sign
scipy.stats.entropy(p, q, base=2)KL⁡(p ∥ q)\KL(p\,\|\,q)renormalizes pp and qq to sum 1 silently
scipy.special.kl_div(x, y)xln⁡(x/y)−x+yx \ln(x/y) - x + y term by termnonnegative per term; equals KL only if xx and yy sum equally
[ ]rel_entr, entropy, kl_div and the epsilon trapBrowser
import numpy as np
from scipy.special import rel_entr, kl_div
from scipy.stats import entropy

def kl(p, q, base=2.0):
    p = np.asarray(p, dtype=float); q = np.asarray(q, dtype=float)
    s = p > 0
    if np.any(q[s] == 0):
        return np.inf
    return float(np.sum(p[s] * np.log(p[s] / q[s])) / np.log(base))

p = np.array([0.5, 0.25, 0.25])
q = np.array([0.4, 0.4, 0.2])
print("a mano (nats):        ", kl(p, q, base=np.e))
print("rel_entr(p, q).sum(): ", rel_entr(p, q).sum())
print("entropy(p, q):        ", entropy(p, q), "  en bits:", entropy(p, q, base=2))
print("kl_div(p, q).sum():   ", kl_div(p, q).sum())
print("términos rel_entr:", np.round(rel_entr(p, q), 4), "  (uno es negativo)")
print("términos kl_div:  ", np.round(kl_div(p, q), 4), "  (todos positivos)")

# entropy normaliza sin avisar; rel_entr no
print("\nentropy(2 * p, q)        =", entropy(2 * p, q), "  (renormaliza: igual que con p)")
print("rel_entr(2 * p, q).sum() =", rel_entr(2 * p, q).sum(), "  (sin renormalizar: otra cosa)")

# soportes distintos
p3, q3 = np.array([0.5, 0.25, 0.25]), np.array([0.5, 0.5, 0.0])
print("\nsoportes: entropy(p3, q3) =", entropy(p3, q3), "  entropy(q3, p3) =", round(entropy(q3, p3), 4))

# la trampa del epsilon: el valor depende de la constante que elijas
dato = np.array([0.5, 0.5, 0.0])
modelo = np.array([0.5, 0.25, 0.25])
for eps in [1e-3, 1e-6, 1e-12]:
    suave = (dato + eps) / (dato + eps).sum()
    print(f"eps = {eps:.0e}:  D(modelo || dato + eps) = {kl(modelo, suave):6.3f} bits")

All three agree with hand calculation for properly normalized distributions, but diverge when something is unusual. The final loop shows why “smoothing with small ε\varepsilon” does not solve infinite support: divergence grows as 0.25log⁡2(1/ε)0.25\log_2(1/\varepsilon) because the model puts mass 0.250.25 outside data support, and each ε\varepsilon yields a different number (1.71.7, 4.24.2 and 9.29.2 bits). If your loss depends on ε\varepsilon, you are not measuring KL: you are measuring your ε\varepsilon.

PyTorch: the kl_div convention

torch.nn.functional.kl_div(input, target) causes more silent KL mistakes because it does not receive pp and qq: it receives input =log⁡q= \log q (model probability logarithms) and target =p= p (data probabilities), and calculates p (log⁡p−log⁡q)p\,(\log p - \log q) elementwise in nats, with 0log⁡0=00 \log 0 = 0. Then it reduces. reduction='batchmean' divides the sum by batch size (mathematical mean KL per example); default 'mean' divides by total element count B⋅KB \cdot K.

import torch
import torch.nn.functional as F

# logits del modelo -> log q, nunca q; p son las probabilidades objetivo (datos, profesor...)
log_q = F.log_softmax(logits, dim=-1)
kl_medio = F.kl_div(log_q, p, reduction="batchmean")     # KL(p || q) media por ejemplo, en nats

# trampas: F.kl_div(q, p) con probabilidades en vez de log-probabilidades; reduction="mean"
# (por defecto) que divide además entre K; y F.kl_div(log_p, q) que calcula KL(q || p).

For concrete numbers this cell reproduces kl_div in NumPy (without PyTorch) and shows three common mistakes:

[ ]The F.kl_div convention replicated in NumPyBrowser
import numpy as np

def kl_div_torch(entrada, objetivo, reduction="batchmean"):
    """Réplica de F.kl_div(entrada, objetivo, reduction=...): entrada = log q, objetivo = p."""
    seguro = np.where(objetivo > 0, objetivo, 1.0)
    puntual = np.where(objetivo > 0, objetivo * (np.log(seguro) - entrada), 0.0)
    if reduction == "sum":
        return puntual.sum()
    if reduction == "batchmean":
        return puntual.sum() / entrada.shape[0]
    return puntual.mean()                 # 'mean': divide entre TODOS los elementos

P = np.array([[0.5, 0.25, 0.25], [0.1, 0.8, 0.1]])     # datos
Q = np.array([[0.4, 0.4, 0.2], [0.2, 0.6, 0.2]])       # modelo

def kl_fila(p, q):
    return float(np.sum(p * np.log(p / q)))

exacto = np.mean([kl_fila(a, b) for a, b in zip(P, Q)])
print("KL(p||q) media por fila (nats):  ", round(exacto, 6))
print("kl_div(log q, p, 'batchmean'):   ", round(kl_div_torch(np.log(Q), P), 6))
print("kl_div(log q, p, 'mean'):        ", round(kl_div_torch(np.log(Q), P, "mean"), 6), "  <- dividida entre B*K = 6")
print("argumentos cambiados (log p, q): ", round(kl_div_torch(np.log(P), Q), 6), "  = KL(q||p), otra cantidad")

The numbers match PyTorch (checked on CPU with the same tensors). PyTorch documentation warns of this and announces that 'mean' will behave like 'batchmean' in a major release, so always state the reduction.

Common mistakes

Exercises

NumericThe first divergence
Calculate KL⁡(p ∥ q)\KL(p\,\|\,q) in bits for p=(12,12)p = (\tfrac12, \tfrac12) and q=(34,14)q = (\tfrac34, \tfrac14).
NumericDistance to uniform
A source over 8 symbols has entropy H⁡(p)=2.3\Ent(p) = 2.3 bits. What is KL⁡(p ∥ u)\KL(p\,\|\,u) in bits, with uu uniform?
NumericDivergence of a sample
A coin lands heads with probability 0.60.6 (pp), and model qq assumes a fair coin. What is KL⁡(p⊗n ∥ q⊗n)\KL(p^{\otimes n}\,\|\,q^{\otimes n}) in bits for n=100n = 100 independent tosses?
NumericHow many samples are needed
Data come from p=Bern(0.5)p = \mathrm{Bern}(0.5) and are tested against q=Bern(0.9)q = \mathrm{Bern}(0.9). On average how many observations accumulate about 1010 bits of evidence for pp? (Use approximation n≈A/KL⁡n \approx A/\KL.)
QuizA zero probability
Let p,qp, q be distributions on a finite alphabet and x0x_0 an outcome with p(x0)>0p(x_0) > 0 and q(x0)=0q(x_0) = 0. What can be asserted with certainty?
QuizThe broken triangle inequality
For three Bernoulli distributions a,b,ca, b, c (parameters a,b,ca, b, c), which triples (a,b,c)(a, b, c) violate KL⁡(a ∥ c)≤KL⁡(a ∥ b)+KL⁡(b ∥ c)\KL(a\,\|\,c) \le \KL(a\,\|\,b) + \KL(b\,\|\,c)?

More than one answer may be correct.

QuizThe correct call
q is a tensor B×KB \times K with model probabilities (sum 1 per row) and p of the same shape has target probabilities. Which call computes mean divergence KL⁡(p ∥ q)\KL(p\,\|\,q) per example in nats?
ProofGibbs via Jensen
Prove: For distributions p,qp, q on a finite alphabet, KL⁡(p ∥ q)≥0\KL(p\,\|\,q) \ge 0, with equality if and only if p=qp = q.
0
Let S=supp⁡(p)S = \operatorname{supp}(p). We may assume q(x)>0q(x) > 0 throughout SS: otherwise KL⁡(p ∥ q)=∞\KL(p\,\|\,q) = \infty and nothing remains to prove.

Step 1 of 4. How do you rewrite −KL⁡(p ∥ q)-\KL(p\,\|\,q) to apply Jensen?

ProofFrom log-sum to joint convexity
Prove: If ai,bi>0a_i, b_i > 0 with A=∑iaiA = \sum_i a_i and B=∑ibiB = \sum_i b_i, then ∑iailog⁡aibi≥Alog⁡AB\sum_i a_i \log\frac{a_i}{b_i} \ge A \log\frac{A}{B}. Consequently KL⁡\KL is jointly convex in (p,q)(p, q).
0
Use function f(t)=tlog⁡tf(t) = t\log t, strictly convex on (0,∞)(0, \infty).

Step 1 of 4. How do you write the left side to apply Jensen to ff?

CodeThe chain rule with zero cells
Implement cadena(P, Q), where P and Q are joint tables (rows xx, columns yy) summing to 1. Return (izq, der) with izq =KL⁡(P ∥ Q)= \KL(P\,\|\,Q) and der =KL⁡(PX ∥ QX)+∑xPX(x) KL⁡(P(⋅∣x) ∥ Q(⋅∣x))= \KL(P_X\,\|\,Q_X) + \sum_x P_X(x)\,\KL(P(\cdot\mid x)\,\|\,Q(\cdot\mid x)), in bits, with usual conventions: 0log⁡0q=00\log\frac0q = 0, plog⁡p0=∞p\log\frac p0 = \infty. Rows with PX(x)=0P_X(x) = 0 do not count (their conditional is undefined and weight 0), and if PP has mass where QQ is zero both outputs must be inf. No nan may appear.
import numpy as np

def kl(p, q):
  """KL en bits entre dos vectores (ya con las convenciones de soporte)."""
  p = np.asarray(p, dtype=float)
  q = np.asarray(q, dtype=float)
  s = p > 0
  if np.any(q[s] == 0):
      return np.inf
  return float(np.sum(p[s] * np.log2(p[s] / q[s])))

def cadena(P, Q):
  """Devuelve (izq, der): KL conjunta y suma marginal + condicional, en bits."""
  P = np.asarray(P, dtype=float)
  Q = np.asarray(Q, dtype=float)
  # tu código: izquierda con las tablas aplanadas; derecha con las marginales de X y los condicionales
  return 0.0, 0.0
Shift+Enter to run

Summary

Key idea
Divergence KL⁡(p ∥ q)\KL(p\,\|\,q) is expected excess surprise when describing pp data with model qq, and mean evidence per observation for pp against qq. It is never negative (Gibbs), jointly convex, decomposes into marginal plus conditional (chain rule), and is additive on products; but it is asymmetric, fails the triangle inequality, and is infinite if qq forbids something pp produces.
  • Definition. KL⁡(p ∥ q)=∑xp(x)log⁡p(x)q(x)\KL(p\,\|\,q) = \sum_x p(x)\log\frac{p(x)}{q(x)}, with 0log⁡0q=00\log\frac0q = 0 and plog⁡p0=∞p\log\frac p0 = \infty. It is finite if and only if p≪qp \ll q. pp samples; qq describes.
  • Two interpretations. H(p,q)=H⁡(p)+KL⁡(p ∥ q)H(p, q) = \Ent(p) + \KL(p\,\|\,q) (excess bits and training loss) and Ep[log⁡p/q]=KL⁡\E_p[\log p/q] = \KL (mean evidence per sample; AA bits require about A/KL⁡A/\KL observations).
  • Gibbs. KL⁡≥0\KL \ge 0, with equality if and only if p=qp = q: by Jensen, by ln⁡t≤t−1\ln t \le t - 1, or as the negative-entropy tangent. Corollary: H⁡(p)≤log⁡∣X∣\Ent(p) \le \log\abs{\mathcal{X}}.
  • Log-sum and convexity. ∑ailog⁡aibi≥Alog⁡AB\sum a_i\log\frac{a_i}{b_i} \ge A\log\frac AB, hence KL⁡\KL is jointly convex in (p,q)(p, q).
  • Chain rule. KL⁡(pXY ∥ qXY)=KL⁡(pX ∥ qX)+EpXKL⁡(pY∣X ∥ qY∣X)\KL(p_{XY}\,\|\,q_{XY}) = \KL(p_X\,\|\,q_X) + \E_{p_X}\KL(p_{Y\mid X}\,\|\,q_{Y\mid X}): forgetting variables cannot increase KL, KL⁡(p⊗n ∥ q⊗n)=n KL⁡(p ∥ q)\KL(p^{\otimes n}\,\|\,q^{\otimes n}) = n\,\KL(p\,\|\,q) and KL between autoregressive models is the sum of per-token KLs.
  • Geometry. Near qq, KL⁡≈12∑δ2/q\KL \approx \frac12\sum\delta^2/q: squared distance, symmetric to second order. Thus it fails the triangle inequality ((2d)2>2d2(2d)^2 > 2d^2) and directions separate far from qq.
  • Practice. PyTorch kl_div receives log⁡q\log q and pp (in that order), with correct batchmean reduction; scipy.stats.entropy renormalizes; ε\varepsilon to avoid log⁡0\log 0 gives divergence depending on ε\varepsilon.