Information theory for ML: entropy, cross-entropy, KL, mutual information

What a log-loss number means: entropy, codes, cross-entropy and KL, temperature, perplexity and bits per byte, compression, mutual information, InfoNCE, KL penalties and estimators. Child of Topic: math. Reading: 38 min, plus 8 in closed details. Data as of October 2026.

The idea in one screen

Every log-loss is a code length: the cross-entropy a model pays is the data's own entropy, which no model can remove, plus a KL divergence, which is the part training removes.

H(p,q)⏟the loss=H(p)⏟floor+DKL(p‖q)⏟removable\underbrace{H(p, q)}_{\text{the loss}} \;=\; \underbrace{H(p)}_{\text{floor}} \;+\; \underbrace{D_{\mathrm{KL}}(p \,\Vert\, q)}_{\text{removable}}

Fig. 1 draws that line over every bet a model could make on the root page's three words. The target pp is a soft one, sat 0.8 and dog 0.2 illustrative (section 3).

  1. Every bet is a point. Each point of the triangle is one distribution over cat, dog and sat; at a corner one word is certain. The target sits on the dog-sat edge; the tiny model's bet (0.665,0.245,0.090)(0.665, 0.245, 0.090) sits near cat.
  2. Height is the loss. Over every bet qq stands its cross-entropy against the target, H(p,q)H(p, q) in nats. The tiny model's bet pays 2.208 nats. Towards the edges where a bet gives sat or dog nothing, the loss runs to infinity (the surface is cut off at 4.5 nats).
  3. The floor is the target's own entropy. The glass plane is H(p)=0.500H(p) = 0.500 nats. The surface touches it at one point, q=pq = p, and lies above it everywhere else: no bet pays less than the entropy of what it predicts.
  4. The gap is the KL. Above the tiny model's bet the column splits into the floor, 0.500 nats, and DKL(p‖q)=1.707D_{\mathrm{KL}}(p \Vert q) = 1.707 nats, the part a better bet removes.
  5. Training removes the KL, never the floor. Gradient descent on the scores (step size 1, 40 steps, illustrative) walks the bet downhill towards pp: the KL falls from 1.707 to 0.017 nats and the 0.500 floor stays.

The same split holds for real models. GPT-2 and Qwen2.5-0.5B read the same 10,376-byte Darwin passage at 1.003 and 0.850 bits per byte (measured, section 6). Nobody knows the passage's floor, but it is the same for both models, so the whole 0.153 bits per byte between them is a difference in KL.

This one line (derived in section 3) is why minimising cross-entropy is maximum likelihood, why a language model's loss levels off above zero, and why the answer to "is 2.0 a good loss?" is "compared with what entropy?". The same few quantities explain why perplexity cannot be compared across tokenizers while bits per byte can, why maximum likelihood spreads probability while an RLHF-style KL penalty narrows it, and why contrastive losses such as CLIP's want huge batches.

You need: distributions, expectations and likelihood (Probability for ML); the tiny next-token model of the Topic: math root (scores z=(2,1,0)z = (2, 1, 0) for cat, dog, sat; softmax bet (0.665,0.245,0.090)(0.665, 0.245, 0.090); true word sat; loss −ln⁡0.090=2.408-\ln 0.090 = 2.408 nats).

Which letter is the data
This page uses the textbook convention of Cover and Thomas and of MacKay, which most papers follow: pp is the truth, qq is the model, so the loss is H(p,q)H(p, q) and the KL it reduces is DKL(p‖q)D_{\mathrm{KL}}(p \Vert q). The Topic: math root page writes the model's softmax as pp and the target as qq, so its H(q,p)H(q, p) is this page's H(p,q)H(p, q). When reading a paper, find which letter is the data before reading anything else.

New terms, each with this page's number

termformulawhat it isexample
surprise−log⁡p(x)-\log p(x)bits to name one outcome you gave probability p(x)p(x)sat at 0.090: 3.473 bits
entropy−∑plog⁡p-\sum p \log pexpected surprise; the shortest average codethe bet: 1.201 bits; weather: 1.5
cross-entropy−∑plog⁡q-\sum p \log qcode built for qq, data from pp; the training lossweather, wrong forecast: 1.75 bits
KL divergence∑plog⁡(p/q)\sum p \log(p/q)the extra bits; ≥0\ge 0; not symmetric1.75−1.5=0.251.75 - 1.5 = 0.25 bits
conditional entropyH(X,Y)−H(Y)H(X, Y) - H(Y)what is left once YY is known; the loss floor0.722 bits
mutual informationH(X)−H(X|Y)H(X) - H(X \mid Y)bits shared; KL from independencesignals agreeing 80%: 0.278 bits
perplexityeCEe^{\text{CE}}the loss as a number of equally likely choices; tokenizer-dependentGPT-2 on Darwin: 30.2
bits per bytetotal bits / bytesthe loss as a compression rate; tokenizer-freeGPT-2 on Darwin: 1.003
InfoNCENN-way softmax cross-entropyI≥ln⁡N−LI \ge \ln N - L, never above ln⁡N\ln NCLIP's ceiling: 10.4 nats

Running examples: the tiny model's bet; the weather (sun 1/2, cloud 1/4, rain 1/4, and a forecaster who swaps sun and cloud); a four-letter source A, B, C, D with probabilities 1/2, 1/4, 1/8, 1/8; real text, a 10,376-byte passage of Darwin's Origin of Species (chapter III, public domain) scored by four small open models and five compressors (Real text, measured). log2⁡\log_2 gives bits, ln⁡\ln gives nats, and 1 nat =1/ln⁡2=1.443= 1/\ln 2 = 1.443 bits; 𝔼p[⋅]\mathbb{E}_p[\cdot] is the average weighting each outcome by pp; 0log⁡0=00 \log 0 = 0. Every number is recomputed by src/recompute.py.

1. Surprise and entropy

The tiny model gave the true word "sat" probability 0.090, and the loss came out as 2.408. That number is a surprise (also called self-information): −ln⁡0.090=2.408-\ln 0.090 = 2.408 nats, or −log2⁡0.090=3.473-\log_2 0.090 = 3.473 bits, as surprised as you would be by three and a half fair coins all landing heads.

s(x)=−log⁡p(x)s(x) = -\log p(x)

A certain outcome surprises you not at all; and for two independent outcomes the probability multiplies, p(x)p(y)p(x)p(y), while the surprise should add. Only −log⁡-\log turns products into sums (details below), and the base only sets the unit: base 2 gives bits, base ee gives nats, and 1 nat =1.443= 1.443 bits, 1 bit =ln⁡2=0.693= \ln 2 = 0.693 nats. PyTorch, JAX and NumPy use ln⁡\ln, so a loss printed during training is in nats: 2.0 nats is 2.885 bits, and its perplexity is e2.0e^{2.0}, not 22.02^{2.0}. Per-token surprise is also the first thing to read in a loss spike: a token with loss 10 nats is one the model gave about e−10=4.5×10−5e^{-10} = 4.5 \times 10^{-5}, and a few of those can dominate a batch's average.

Why the logarithm, as Shannon proved it (with his own example checked)

Shannon put the additivity requirement on the average (his third axiom: "if a choice be broken down into two successive choices, the original HH should be the weighted sum of the individual values of HH") and proved that −K∑ipilog⁡pi-K\sum_i p_i \log p_i is the only form satisfying it, the constant KK "merely" choosing the unit (Shannon 1948, Theorem 2 and Appendix 2).

His example: choose among 12,13,16\tfrac12, \tfrac13, \tfrac16 at once, or first between two halves and then, half the time, between 23\tfrac23 and 13\tfrac13. The final probabilities agree (12×23=13\tfrac12 \times \tfrac23 = \tfrac13), so H(12,13,16)=H(12,12)+12H(23,13)H(\tfrac12, \tfrac13, \tfrac16) = H(\tfrac12, \tfrac12) + \tfrac12 H(\tfrac23, \tfrac13). In bits: left 12×1+13×1.585+16×2.585=1.459\tfrac12 \times 1 + \tfrac13 \times 1.585 + \tfrac16 \times 2.585 = 1.459; right 1+12×0.918=1.4591 + \tfrac12 \times 0.918 = 1.459. The 12\tfrac12 is there because the second choice happens only half the time.

Each halving of the probability adds exactly one bit

p = 10 bits
p = 1/2 (a coin)1 bit
p = 1/83 bits
p = 0.090 (sat)3.473 bits
p = 1/102410 bits
wordqq (model's bet)nats −ln⁡q-\ln qbits −log2⁡q-\log_2 q
cat0.6650.4080.588
dog0.2451.4082.031
sat (the truth)0.0902.4083.473

Surprise −log2⁡p-\log_2 p to scale (10 bits is the full width), and the tiny model's three surprises. The nats column goes up by exactly 1 per row because the scores z=(2,1,0)z = (2, 1, 0) drop by 1 each and −ln⁡softmax(z)i=ln⁡∑jezj−zi-\ln \mathrm{softmax}(z)_i = \ln \sum_j e^{z_j} - z_i.

Entropy: the surprise you expect before you look

Weather that is sun half the time and cloud or rain a quarter each surprises you by 1, 2 and 2 bits, so on average by 12×1+14×2+14×2=1.5\tfrac12 \times 1 + \tfrac14 \times 2 + \tfrac14 \times 2 = 1.5 bits. The tiny model's bet: 0.665×0.588+0.245×2.031+0.090×3.473=1.2010.665 \times 0.588 + 0.245 \times 2.031 + 0.090 \times 3.473 = 1.201 bits (0.832 nats), below the 1.585 bits (log2⁡3\log_2 3) of a uniform bet over three words. A coin that lands heads 90% of the time: 0.137+0.332=0.4690.137 + 0.332 = 0.469 bits; the rare tail is very surprising (3.32 bits) but rare.

Entropy is steep near certainty and flat near a fair coin

The binary entropy H(θ)=−θlog2⁡θ−(1−θ)log2⁡(1−θ)H(\theta) = -\theta \log_2 \theta - (1-\theta)\log_2(1-\theta) of a coin with heads probability θ\theta: 0 at the ends, 1 bit at θ=1/2\theta = 1/2. Going from 99% to 95% certain adds more (0.081 to 0.286 bits) than going from 70% to 60% (0.881 to 0.971).

Fig. 2 lifts every bet over three words to its entropy.

H(p)=𝔼x∼p[−log⁡p(x)]=−∑xp(x)log⁡p(x)H(p) = \mathbb{E}_{x \sim p}\big[-\log p(x)\big] = -\sum_{x} p(x) \log p(x)
  1. Every bet is a point. The triangle holds every distribution over cat, dog and sat. At a corner one word is certain; the centre is the uniform bet, a third each.
  2. Height is entropy. Over each bet stands its entropy in bits: 0 at the corners, rising to log2⁡3=1.585\log_2 3 = 1.585 bits at the centre, the most uncertain bet there is over three words.
  3. The tiny model's bet: 1.201 bits. (0.665,0.245,0.090)(0.665, 0.245, 0.090) sits between the cat corner and the centre, below the 1.585 ceiling.
  4. Each edge is a coin. Along an edge one word has probability 0, so the edge is the binary entropy curve of the chart above: 1 bit in the middle, 0.469 bits at the 0.9 coin.
  5. Temperature walks one path. Dividing the scores by TT moves the bet along a single curve: towards the cat corner as T→0T \to 0 (greedy), through T=0.5T = 0.5 (0.636 bits), T=1T = 1 (1.201) and T=2T = 2 (1.472), towards the centre as TT grows. It never heads for another word's corner, because dividing keeps the order of the scores (section 5).

Three readings of one number: the average surprise; the shortest possible average length of a message saying which outcome happened (section 2); and the spread of the distribution. 0≤H(p)≤log⁡K0 \le H(p) \le \log K for KK outcomes, 0 exactly when one outcome is certain and log⁡K\log K exactly when all are equally likely (because DKL(p‖u)=log⁡K−H(p)≥0D_{\mathrm{KL}}(p \Vert u) = \log K - H(p) \ge 0 for the uniform uu, section 3). It depends only on the probabilities, not on the names or values of the outcomes, which is why it measures uncertainty and not the size of an error. Choosing a Gaussian or a softmax is choosing the maximum-entropy, least committal distribution that matches what you know (details below).

Where entropy shows up in ML
Exploration in RL: an entropy bonus +αH(π(⋅|s))+\alpha H(\pi(\cdot \mid s)) keeps a policy from collapsing too early (SAC maximises reward plus entropy; Policy gradients and actor-critic). Confidence: the entropy of a predicted distribution is a cheap uncertainty signal, 0 for a certain prediction and log⁡K\log K for a uniform one. Decision trees: the information gain of a split is the parent's label entropy minus the children's weighted entropy; ten examples, 5 yes and 5 no (1 bit), split into 4 yes / 1 no and 1 yes / 4 no gives children of H(0.8)=0.722H(0.8) = 0.722 bits, a gain of 0.278 bits, exactly the mutual information between split and label (section 8). Sampling: temperature moves the entropy of the next-token distribution (section 5).
Maximum entropy, and why the entropy of a continuous variable is different

Among distributions on the real line with variance σ2\sigma^2, the Gaussian has the largest (differential) entropy, 12ln⁡(2πeσ2)\tfrac12 \ln(2\pi e \sigma^2), 1.419 nats at σ=1\sigma = 1; among distributions over KK classes with a given expected score, the softmax qi∝eziq_i \propto e^{z_i} has the largest (Cover and Thomas, ch. 12).

For a density f(x)f(x), the differential entropy is h(f)=−∫f(x)ln⁡f(x)dxh(f) = -\int f(x) \ln f(x)\, dx. It is not the limit of the discrete entropy (that limit is infinite: pinning a real number down exactly takes infinitely many bits), it can be negative (a Gaussian with σ=0.1\sigma = 0.1 has h=1.419+ln⁡0.1=−0.884h = 1.419 + \ln 0.1 = -0.884 nats), and it changes if you rescale xx. Differences of differential entropies, such as KL divergences and mutual information, are finite, non-negative and unchanged by rescaling, which is why ML on continuous data works with them rather than with hh.

Huffman pays 0.134 bits per word for rounding to whole bits

2. Codes: entropy is the shortest average message

Tell a friend the weather each day in 0s and 1s with sun = 0, cloud = 10, rain = 11. No codeword is the start of another (a prefix code), so 0100110 splits one way only: sun, cloud, sun, rain, sun. The average length is 12×1+14×2+14×2=1.5\tfrac12 \times 1 + \tfrac14 \times 2 + \tfrac14 \times 2 = 1.5 bits per day, exactly the entropy, because each codeword is exactly −log2⁡p-\log_2 p bits long.

Lengths are a budget. A codeword of length ℓ\ell uses up a fraction 2−ℓ2^{-\ell} of all bit strings, and a prefix code with lengths ℓ1,…,ℓK\ell_1, \dots, \ell_K exists if and only if

∑i=1K2−ℓi≤1\sum_{i=1}^{K} 2^{-\ell_i} \le 1

(the Kraft inequality, MacKay, ITILA, §5.2). A 1-bit word spends half the budget, so short words can go to only a few outcomes, and they should go to the frequent ones. Read qi=2−ℓiq_i = 2^{-\ell_i} as the probability the code assumes: a code is a probability distribution in disguise, and a distribution is a code. The average length is then L=∑ipiℓi=−∑ipilog2⁡qiL = \sum_i p_i \ell_i = -\sum_i p_i \log_2 q_i, the cross-entropy H(p,q)H(p, q), and section 3 proves H(p,q)≥H(p)H(p, q) \ge H(p). So no prefix code beats the entropy on average, and it meets it exactly when ℓi=−log2⁡pi\ell_i = -\log_2 p_i. MacKay's equation 5.23: "the average length is L=H(X)+∑ipilog⁡pi/qiL = H(X) + \sum_i p_i \log p_i/q_i", which "exceeds the entropy by the relative entropy DKL(p‖q)D_{\mathrm{KL}}(p \Vert q)". That equation is the bridge from codes to losses.

Whole numbers of bits: Huffman's code on the tiny model's bet

The ideal lengths for the bet are 0.588, 2.031 and 3.473 bits. Huffman's algorithm finds the best whole-number lengths: merge the two least likely items, repeat, then read the codewords off the branches.

  1. Three leaves. The tiny model's bet: cat 0.665, dog 0.245, sat 0.090. The ideal code lengths, −log2⁡q-\log_2 q, are 0.588, 2.031 and 3.473 bits, not whole numbers.
  2. Merge the two least likely. Dog (0.245) and sat (0.090) are the two smallest; join them under one node of weight 0.335.
  3. Merge again. Two items are left, cat (0.665) and the dog-sat node (0.335); joining them makes the root, weight 1.
  4. Read the codewords. Label every left branch 0 and every right branch 1 and read from the root down: cat 0, dog 10, sat 11. No codeword starts another, and the Kraft sum 2−1+2−2+2−2=12^{-1} + 2^{-2} + 2^{-2} = 1 wastes no budget.
  5. The cost. Average length 0.665×1+0.245×2+0.090×2=1.3350.665 \times 1 + 0.245 \times 2 + 0.090 \times 2 = 1.335 bits per word, against the entropy 1.201. The 0.134 bits are the price of whole bits: cat deserves 0.588 bits and gets 1.

Huffman's guarantee is H(p)≤LHuffman<H(p)+1H(p) \le L_{\text{Huffman}} \lt H(p) + 1 (MacKay, Theorem 5.1, eq. 5.19). Coding longer blocks shrinks the "+1", and arithmetic coding removes it: it codes a whole message as one number and spends, in total, within two bits of the message's surprise ∑t−log2⁡q(xt|x<t)\sum_t -\log_2 q(x_t \mid x_{\lt t}) (MacKay §6.2). So the length of a compressed file is the model's total surprise, to within two bits; section 7 animates it.

On real text: the Darwin passage uses 58 distinct byte values with an entropy, ignoring all context, of 4.269 bits per byte; a Huffman code on those counts spends 4.295, against 8 raw. Going lower needs context, which is a language model (section 7). The code-length reading is also why tokenizers are compressors (a BPE merge table shortens frequent strings, Tokenizers), and why minimum-description-length arguments treat a model plus its residual code as one message.

The Shannon code, block coding, and the source coding theorem as stated

The cruder rule "round each ideal length up" (a Shannon code, lengths 1, 3, 4) gives 1.760 bits on the bet. Huffman on pairs of words (9 outcomes) costs 1.2145 bits per word, on triples 1.2107, on blocks of four 1.2094, closing in on 1.2009.

The theorem, in MacKay's words (§4.4): "N i.i.d. random variables each with entropy H(X) can be compressed into more than N H(X) bits with negligible risk of information loss, as N → ∞; conversely if they are compressed into fewer than N H(X) bits it is virtually certain that information will be lost." Shannon's original is Theorem 9 of the 1948 paper, stated for transmitting over a channel. Entropy limits the average, not every message, and reaching it needs long blocks or a method such as arithmetic coding that does not spend whole bits per symbol.

3. Cross-entropy and KL: the wrong code, and the bits it wastes

Sixteen symbols drawn from pp = (A 1/2, B 1/4, C 1/8, D 1/8), in exactly those proportions, go through two codes: the code built for pp (A 0, B 10, C 110, D 111) and a code built for a wrong guess qq = (A 1/8, B 1/2, C 1/4, D 1/8) (A 110, B 0, C 10, D 111). Predict before Fig. 3 plays: the wrong code is shorter on B, so does it lose overall, and by how much per symbol?

  1. Sixteen symbols in p's proportions. 8 A, 4 B, 2 C and 2 D: exactly pp = (1/2, 1/4, 1/8, 1/8).
  2. The code built for p: 28 bits. 8×1+4×2+2×3+2×3=288 \times 1 + 4 \times 2 + 2 \times 3 + 2 \times 3 = 28 bits, 1.75 per symbol =H(p)= H(p): each codeword is exactly −log2⁡p-\log_2 p bits long.
  3. The code built for q: 38 bits. 8×3+4×1+2×2+2×3=388 \times 3 + 4 \times 1 + 2 \times 2 + 2 \times 3 = 38 bits, 2.375 per symbol. The wrong code is shorter on B and C, but A, half the stream, now costs 3 bits instead of 1.
  4. The extra bits, outcome by outcome. Per symbol, A costs 1 bit more, B saves 0.25 and C 0.125, and D is unchanged: the terms p(x)log2⁡p(x)q(x)p(x)\log_2 \frac{p(x)}{q(x)}. They add to 0.625 bits, 2.375−1.752.375 - 1.75. Single terms can be negative; the sum never is.
  5. The other direction is another number. Swap the roles (a stream from qq through the code for pp) and the terms become q(x)log2⁡q(x)p(x)q(x)\log_2 \frac{q(x)}{p(x)}: −0.25,+0.5,+0.25,0-0.25, +0.5, +0.25, 0, adding to 0.5 bits. KL is not symmetric.

Frequencies from one distribution and code lengths from the other give the cross-entropy H(p,q)H(p, q), 2.375 bits here. The difference from the entropy, 0.625 bits per symbol, is the Kullback-Leibler divergence (or relative entropy) DKL(p‖q)D_{\mathrm{KL}}(p \Vert q). Every probability here is a power of one half, so the equality is exact.

H(p,q)=−∑xp(x)log⁡q(x),DKL(p‖q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p)H(p, q) = -\sum_x p(x) \log q(x), \qquad D_{\mathrm{KL}}(p \,\Vert\, q) = \sum_x p(x) \log \frac{p(x)}{q(x)} = H(p, q) - H(p)

The identity is one line: split log⁡pq=−log⁡q+log⁡p\log \frac{p}{q} = -\log q + \log p and average under pp. The weather agrees: a forecaster who swaps sun and cloud builds cloud 0, sun 10, rain 11, and the real weather costs 1.75 bits a day, =1.5+0.25= 1.5 + 0.25. The ratio p(x)/q(x)p(x)/q(x) is the likelihood ratio; the sum runs over outcomes with p(x)>0p(x) \gt 0, and if q(x)=0q(x) = 0 for any of them the divergence is infinite.

The training loss is a cross-entropy, so training minimises a KL

With nn examples (xi,yi)(x_i, y_i), use the empirical distribution (each example gets 1/n1/n) as pp and the model qθ(y|x)q_\theta(y \mid x) as qq. A one-hot target multiplies every term of −∑yp(y)log⁡q(y)-\sum_y p(y) \log q(y) by 0 except the true label, leaving the negative log-likelihood

ℒ(θ)=−1n∑i=1nlog⁡qθ(yi|xi)=H(pˆ)+DKL(pˆ‖qθ)\mathcal{L}(\theta) = -\frac{1}{n}\sum_{i=1}^{n} \log q_\theta(y_i \mid x_i) = H(\hat p) + D_{\mathrm{KL}}(\hat p \,\Vert\, q_\theta)

Minimising it maximises ∏iqθ(yi|xi)\prod_i q_\theta(y_i \mid x_i): cross-entropy minimisation is maximum-likelihood estimation (the Probability page arrives at the same loss from the likelihood side), and because H(pˆ)H(\hat p) does not depend on θ\theta, it is exactly minimising DKL(data‖model)D_{\mathrm{KL}}(\text{data} \Vert \text{model}); the loss can never go below the data's own entropy. For the tiny model with the one-hot target sat, H(p)=0H(p) = 0 and all 2.408 nats are KL. In nats, a correct-class probability of 0.7 costs 0.357 (0.515 bits), 0.99 costs 0.010, and 0.01 costs 4.61: the loss grows without bound, so a few confidently wrong examples can dominate a batch.

Soft targets (a teacher's probabilities, label smoothing) keep the full sum, and its minimum is H(p)H(p), not 0. Say the data after "the cat" were sat 0.8, dog 0.2 illustrative: against the tiny model H(p,q)=2.208H(p, q) = 2.208 nats, of which H(p)=0.500H(p) = 0.500 is the target's own entropy and 1.707 is removable. Cross-entropy and KL have the same gradient in the model (they differ by H(p)H(p)), "prediction minus target" q−pq - p on the scores (derived on the Calculus and optimisation for ML, section 2), but not the same value: report KL for "distance from the target", cross-entropy for "compressed length".

Binary cross-entropy, logits, and why cross-entropy rewards calibration
Binary cross-entropy, −yln⁡yˆ−(1−y)ln⁡(1−yˆ)-y \ln \hat y - (1 - y)\ln(1 - \hat y), is the two-outcome case; PyTorch's BCEWithLogitsLoss and CrossEntropyLoss take logits so they can compute the log of a softmax stably. Cross-entropy is also a proper scoring rule: its expected value is minimised only by reporting the true probabilities, which pushes a model towards calibration, not just correct rankings (Evaluation metrics). Cross-entropy among the other losses, with label smoothing and focal loss, is on Loss functions.

Never negative, and not a distance

DKL(p‖q)≥0D_{\mathrm{KL}}(p \Vert q) \ge 0, with equality only when q=pq = p (Gibbs' inequality): on average you cannot beat the truth's own code. MacKay calls it "probably the most important inequality in this book" (§2.6, eq. 2.46); every "≥\ge" on this page (entropy below log⁡K\log K, conditioning reduces entropy, mutual information is non-negative, data processing, the ELBO) comes from it. It is not symmetric: a fair coin p=(0.5,0.5)p = (0.5, 0.5) against a model q=(0.9,0.1)q = (0.9, 0.1) gives DKL(p‖q)=0.737D_{\mathrm{KL}}(p \Vert q) = 0.737 bits but DKL(q‖p)=0.531D_{\mathrm{KL}}(q \Vert p) = 0.531; the stream above gives 0.625 one way and 0.5 the other; the weather gives 0.25 both ways only because qq is pp with two outcomes swapped. With no symmetry and no triangle inequality it is not a metric, despite the name "KL distance" (MacKay: it "is not strictly a distance"). Section 4 shows the direction changes the answer. Try your own pairs in the Entropy and KL lab.

Zero probability means infinite cost
A model that gives probability exactly 0 to something that happens has −log⁡0=∞-\log 0 = \infty: infinite cross-entropy and infinite forward KL. A softmax never outputs an exact 0 in exact arithmetic, but log⁡(softmax(z))\log(\mathrm{softmax}(z)) in floating point can underflow to log⁡0\log 0, which is why frameworks compute log_softmax directly as zi−log⁡∑jezjz_i - \log \sum_j e^{z_j} with the maximum subtracted (Numerical computing).
Proof that KL is never negative (Jensen's inequality)

Jensen: for a convex function ff (curving upwards, like −log⁡u-\log u), 𝔼[f(U)]≥f(𝔼[U])\mathbb{E}[f(U)] \ge f(\mathbb{E}[U]); the chord between two points of a bowl lies above the curve, and equality needs UU constant. The same proof as MacKay's solution to exercise 2.26:

  1. Let U=q(x)/p(x)U = q(x)/p(x) with x∼px \sim p, and f(u)=−log⁡uf(u) = -\log u. Then DKL(p‖q)=𝔼[f(U)]D_{\mathrm{KL}}(p \Vert q) = \mathbb{E}[f(U)].
  2. Jensen: 𝔼[f(U)]≥−log⁡𝔼p[q(x)p(x)]\mathbb{E}[f(U)] \ge -\log \mathbb{E}_p\big[\tfrac{q(x)}{p(x)}\big].
  3. 𝔼p[q(x)p(x)]=∑x:p(x)>0q(x)≤1\mathbb{E}_p\big[\tfrac{q(x)}{p(x)}\big] = \sum_{x: p(x) \gt 0} q(x) \le 1, so DKL≥−log⁡(something≤1)≥0D_{\mathrm{KL}} \ge -\log(\text{something} \le 1) \ge 0.
  4. Equality needs q/pq/p constant and ∑q=1\sum q = 1 on the support of pp: q=pq = p.
Where KL shows up in ML
The removable part of every log-loss; KL penalties that keep a fine-tuned model near its reference (section 10); the ELBO of VAEs and diffusion models (section 10 and Variational inference and generative-model maths); trust regions in RL (TRPO constrains a KL between old and new policies); knowledge distillation (section 5).

Forward KL spreads over both humps; reverse KL picks one

A grid of 801 points from −8-8 to 8; gradients by central differences on (μ,ln⁡σ)(\mu, \ln\sigma), step size 0.1, 200 steps; src/recompute.py gives the same end points.

4. Forward against reverse KL: covering every mode or choosing one

The truth pp has two humps, 12𝒩(−2,0.62)+12𝒩(2,0.62)\tfrac12 \mathcal{N}(-2, 0.6^2) + \tfrac12 \mathcal{N}(2, 0.6^2); the model qq is one Gaussian with mean μ\mu and standard deviation σ\sigma. Both fits start at μ=1,σ=1\mu = 1, \sigma = 1 and run gradient descent, the top on the forward KL DKL(p‖q)D_{\mathrm{KL}}(p \Vert q), the bottom on the reverse KL DKL(q‖p)D_{\mathrm{KL}}(q \Vert p). Predict before it plays: which one ends up sitting in the valley between the humps?

  1. The same start. Both fits start at μ=1,σ=1\mu = 1, \sigma = 1, a narrow bell near the right hump. Blue is the truth pp; the shaded band is the valley |x|<0.5|x| \lt 0.5, where pp has only 0.6% of its mass.
  2. Steps 1 to 10: the objectives pull apart. Forward KL pays for every point of the left hump that qq misses, so it widens at once (σ=2.15\sigma = 2.15 after ten steps) and starts sliding left. Reverse KL pays only where qq itself has mass, so it moves right, onto the hump (μ=1.47\mu = 1.47).
  3. Steps 10 to 40: reverse has found its hump. The reverse fit is already at about μ=2.0,σ=0.61\mu = 2.0, \sigma = 0.61 and stays there; the forward fit keeps sliding towards the middle of the two humps.
  4. Steps 40 to 200: converged. Forward ends at the mean and spread of the whole of pp; reverse sits on one hump, fitted tightly, and ignores the other. The numbers are in the two paragraphs below.

Forward, 𝔼x∼p[log⁡p(x)q(x)]\mathbb{E}_{x \sim p}\big[\log \frac{p(x)}{q(x)}\big], averages over the truth: wherever the data has mass and the model has almost none, log⁡pq\log \frac{p}{q} is huge, so the model must put some probability everywhere the data goes, mode-covering (mean-seeking, zero-avoiding). The fit converges to μ=0.009,σ=2.088\mu = 0.009, \sigma = 2.088, which is moment matching: the mean and variance of pp, σ=0.62+22=2.088\sigma = \sqrt{0.6^2 + 2^2} = 2.088. The price is 18.6% of its mass in the valley |x|<0.5|x| \lt 0.5, where the truth has 0.6%; forward KL 0.555 nats, reverse 1.267.

Reverse, 𝔼x∼q[log⁡q(x)p(x)]\mathbb{E}_{x \sim q}\big[\log \frac{q(x)}{p(x)}\big], averages over the model: mass the model puts where the truth has none is punished, and truth the model ignores costs nothing because it is never averaged over. So it picks one hump, mode-seeking (zero-forcing): μ=1.997,σ=0.605\mu = 1.997, \sigma = 0.605, reverse KL 0.692 nats, almost exactly ln⁡2=0.693\ln 2 = 0.693 because on its hump q≈2pq \approx 2p (the hump holds half of pp). Its forward KL is 10.23 nats: it ignores half the data. Started at μ=−1\mu = -1 it lands on the left hump; the reverse objective has a local minimum at each.

Why the forward fit matches moments (for a Gaussian model)
  1. DKL(p‖q)=−H(p)−𝔼p[ln⁡q(x)]D_{\mathrm{KL}}(p \Vert q) = -H(p) - \mathbb{E}_p[\ln q(x)], and H(p)H(p) does not depend on μ,σ\mu, \sigma.
  2. −𝔼p[ln⁡q]=12ln⁡(2πσ2)+𝔼p[(x−μ)2]2σ2-\mathbb{E}_p[\ln q] = \tfrac12 \ln(2\pi\sigma^2) + \frac{\mathbb{E}_p[(x-\mu)^2]}{2\sigma^2}.
  3. In μ\mu: −𝔼p[x−μ]/σ2=0-\mathbb{E}_p[x - \mu]/\sigma^2 = 0, so μ=𝔼p[x]\mu = \mathbb{E}_p[x]. In σ\sigma: 1σ−𝔼p[(x−μ)2]σ3=0\frac{1}{\sigma} - \frac{\mathbb{E}_p[(x-\mu)^2]}{\sigma^3} = 0, so σ2=Varp(x)\sigma^2 = \mathrm{Var}_p(x).
This is maximum likelihood for a Gaussian: the fitted mean and variance are the data's, whatever shape the data has.

Where each direction shows up

  • Maximum likelihood is forward KL. A language model trained on cross-entropy minimises DKL(data‖model)D_{\mathrm{KL}}(\text{data} \Vert \text{model}), so it learns to put some probability on everything the data does. That is good for coverage; it is also the usual explanation (an argument, not a measurement) for why pure sampling from a pretrained model wanders into low-probability text, and why decoding tricks such as top-p cut the tail (Sampling and Decoding).
  • Variational inference is reverse KL. Raising the ELBO lowers DKL(q(z)‖p(z|x))D_{\mathrm{KL}}(q(z) \Vert p(z \mid x)) (section 10), so the approximate posterior hugs one mode and underestimates uncertainty; MacKay's Figure 33.6 shows a reverse-KL fit to a correlated two-dimensional Gaussian coming out too narrow (ITILA ch. 33).
  • RLHF's KL penalty is reverse KL, DKL(π‖πref)D_{\mathrm{KL}}(\pi \Vert \pi_{\text{ref}}), averaged over the policy's own samples: it punishes saying what the reference finds unlikely and does not punish dropping what the reference would say, one mechanism behind the narrower, less diverse outputs of aligned models (section 10).
  • Distillation uses both: forward KL on the teacher's distribution, reverse KL on the student's own samples (section 5).
Choosing a direction
Forward KL when missing a mode is the worse failure (a density model, a speech recogniser that must not rule out a word). Reverse KL when putting mass where the truth has none is the worse failure (a policy that must not say unacceptable things), or when you can sample from your approximation and evaluate the target only up to a constant (variational inference, where p(z|x)p(z \mid x) is known only up to p(x)p(x)).

5. Temperature: one dial on the entropy of a distribution

Sampling at temperature TT divides the scores by TT before the softmax, qT=softmax(z/T)q_T = \mathrm{softmax}(z / T). On the tiny model, T=1T = 1 is the bet itself, 1.201 bits; T=0.5T = 0.5 sharpens it to (0.867, 0.117, 0.016), 0.636 bits; T=2T = 2 flattens it to (0.506, 0.307, 0.186), 1.472 bits. Predict before you drag: can any temperature push the entropy above 1.585 bits, or reorder the three words?

No: dividing by TT keeps the order of the scores, so the most likely word stays the most likely, and the entropy rises monotonically from 0 (as T→0T \to 0, all mass on the top score: greedy decoding) to log⁡K\log K (as T→∞T \to \infty, uniform). The rate has a closed form derived:

dH(qT)dT=VarqT(z)T3≥0(nats)\frac{dH(q_T)}{dT} = \frac{\mathrm{Var}_{q_T}(z)}{T^3} \;\ge\; 0 \quad \text{(nats)}

(write H=ln⁡Z−𝔼qT[z]/TH = \ln Z - \mathbb{E}_{q_T}[z]/T with Z=∑jezj/TZ = \sum_j e^{z_j/T} and differentiate). At T=1T = 1 the variance of the scores under the bet is 0.424, so the entropy climbs 0.424 nats per unit of temperature there. Temperature is the one dial that sets how uncertain the sampler is without changing what it prefers; truncation samplers (top-k, top-p, min-p) change the support instead, and their effects on real next-token distributions are on Sampling and Decoding. In RL fine-tuning, the entropy of the policy's own next-token distribution is the quantity watched for entropy collapse (RL for LLMs).

Temperature only moves the entropy, between 0 (greedy) and log K (uniform), never the order

1.00

Scores z=(2,1,0)z = (2, 1, 0); the slider is logarithmic from T=0.1T = 0.1 to 10. The curve is the entropy of qTq_T in bits against TT (log axis), with the dashed ceiling log2⁡3=1.585\log_2 3 = 1.585. "Effective choices" is 2H2^{H}, the perplexity of the sampling distribution itself: 2.30 words at T=1T = 1.

Distillation read as information theory

A teacher's soft probabilities carry more bits than a one-hot label: the relative sizes of the wrong answers. Distillation trains the student on cross-entropy against the teacher's distribution at a raised temperature, which is the teacher's entropy (fixed) plus the forward KL from teacher to student (removable), exactly the split of section 3. Raising TT raises the teacher's entropy and so how much of that wrong-answer structure the target exposes. The gradient on the student's logits is (qT−pT)/T(q_{T} - p_{T})/T, and at high temperature the difference itself shrinks like 1/T1/T, so the soft term's gradients scale as 1/T21/T^2 and are multiplied back by T2T^2 (Hinton, Vinyals and Dean 2015, §2). On-policy distillation instead scores the student's own samples: MiniLLM minimises the reverse KL from student to teacher, with the mode-seeking behaviour of section 4, and GKD allows a family of divergences between the two. The recipes, the measured teacher-student runs and when each direction wins are on Distillation and Small Language Models.

6. Perplexity and bits per byte

GPT-2 (124M) read the 10,376-byte Darwin passage and paid a total of 7,212.5 nats (10,405 bits). That total is the size of the file it would compress the passage to (section 2). Divide the same total by different units:

PPL=exp⁡(CE in nats per token),BPB=ntokens⋅CEnats/tokennbytes⋅ln⁡2\mathrm{PPL} = \exp\big(\text{CE in nats per token}\big), \qquad \mathrm{BPB} = \frac{n_{\text{tokens}} \cdot \mathrm{CE}_{\text{nats/token}}}{n_{\text{bytes}} \cdot \ln 2}

Perplexity is the number of equally likely options that would be as confusing as the model: 1 is perfect, a uniform guess over KK tokens is KK, and the tiny model on sat is e2.408=11.1e^{2.408} = 11.1, worse than a uniform guess over its 3 words. But it divides the total surprise by the number of tokens before exponentiating, so a tokenizer with fewer, longer tokens raises it without the model knowing anything less. Bits per byte (BPB) divides by something no tokenizer can change: GPT-2 cuts the passage into 2,117 tokens, 4.901 bytes per token; 3.407 nats per token is 4.915 bits per token; so 3.407/(0.6931×4.901)=1.0033.407 / (0.6931 \times 4.901) = 1.003 bits per byte, an eighth of the raw size.

One model, one text, one compressed length: "perplexity" from 2 to 907

unitcountnats per unit"perplexity"
GPT-2 tokens2,1173.40730.2
whitespace words1,7774.05957.9
pairs of tokens (a coarser tokenizer, built exactly by the chain rule)1,0596.811907.5
bytes10,3760.6952.00

Measured (src/data/score.py). The pair row is exact, not hypothetical: a tokenizer whose tokens are pairs of GPT-2 tokens gives each pair the product of the two conditional probabilities, so the total is unchanged and the count halves.

Different tokenizers on the same texts (real)

Three things the table shows. Across texts, perplexity misleads: GPT-2's perplexity on the C code is far lower than on Darwin, yet it compresses the code worse, because 979 of its 3,331 tokens there are pure whitespace at 1.14 nats each against 2.51 for the rest (Qwen2.5's tokenizer needs only 284 such tokens); cheap tokens dilute the per-token loss without shortening the file. Across tokenizers, perplexity understates or overstates: on the French passage Qwen2.5 uses 1,670 tokens where SmolLM2 uses 2,131, so its perplexity advantage (13.3 against 16.6, a ratio of 1.24) is smaller than its compression advantage (1.048 against 1.450 bits per byte, a ratio of 1.38). Within one tokenizer, perplexity is fine: GPT-2 against OPT-125m ranks the same way under both measures on all three texts, and the remaining differences between models are model differences (Qwen2.5 is 0.5B parameters, the others 124M to 135M), which bits per byte measures cleanly. The rule: perplexity only within one tokenizer and one evaluation set; bits per byte or per character, saying which, across tokenizers. Pretraining reports and scaling laws use bits per byte or nats per token within one tokenizer; per-token perplexity under three tokenizers, token by token, is drawn on Evaluation metrics.

Four models, three texts: perplexity against bits per byte

Four small open models on three public-domain texts, float32 on CPU, sliding window (src/data/score.py). GPT-2 and OPT-125m share one tokenizer (OPT's paper, §2.3: "the GPT-2 byte level BPE tokenizer"), so only their perplexities compare. On C code GPT-2 scores perplexity 8.2 yet 1.51 bits per byte, against 30.2 and 1.00 on Darwin. Token by token in Real text, measured.

Bits per character, and two more conversions checked

Bits per character (BPC) divides by characters instead of bytes; it is the traditional unit on character-level benchmarks such as enwik8, the first 10810^8 bytes of the 3 March 2006 English Wikipedia dump (Large Text Compression Benchmark). For plain English the two nearly coincide: the Darwin passage has 10,371 characters and 10,376 bytes (an "æ" takes 2 bytes in UTF-8 and a curly apostrophe 3), so GPT-2's 1.0028 bits per byte is 1.0033 bits per character. In accented French they part: the Hugo passage is 5,773 characters but 5,953 bytes, and Qwen2.5's 1.048 bits per byte is 1.048×5,953/5,773=1.0811.048 \times 5{,}953 / 5{,}773 = 1.081 bits per character.

Illustrative (from the old page): one 4,000-byte text; tokenizer A gives 1,000 tokens at 2.0 nats each, tokenizer B 1,250 tokens at 1.6 nats. Both total 2,000 nats. Perplexity: A e2.0=7.39e^{2.0} = 7.39, B e1.6=4.95e^{1.6} = 4.95, so B looks much better; bits per byte: both 2,000/(4,000ln⁡2)=0.7212{,}000 / (4{,}000 \ln 2) = 0.721. Real ratio: the Pile paper prefers bits per byte "due to its invariance to different tokenization schemes" and measures 0.29335 GPT-2 tokens per byte over the Pile, so 2.0 nats per token there is 0.29335×2.0/ln⁡2=0.8460.29335 \times 2.0 / \ln 2 = 0.846 bits per byte (Gao et al. 2020).

7. The loss floor, and compression as prediction

A language model predicts each token given the ones before it, and the chain rule of entropy (section 8) says the uncertainty of a whole text is exactly the sum of those conditional uncertainties:

H(X1,…,Xn)=∑t=1nH(Xt|X1,…,Xt−1)H(X_1, \dots, X_n) = \sum_{t=1}^{n} H(X_t \mid X_1, \dots, X_{t-1})

That is the shape of the loss: the model pays −log⁡q(xt|x<t)-\log q(x_t \mid x_{\lt t}) at each position, and the per-token average over a long text estimates the entropy rate, the uncertainty per symbol once all the past is known. That rate is the floor H(p)H(p) of section 3; a loss that levels off is the KL shrinking towards a floor that is not zero. Context is worth a lot: Shannon measured, for a 26-letter alphabet, F0=log2⁡26=4.70F_0 = \log_2 26 = 4.70 bits per letter with no context, F1=4.14F_1 = 4.14 with letter frequencies and F2=3.56F_2 = 3.56 with pairs, and from people guessing the next letter with 100 letters of context (27 symbols, counting the space) bounded the entropy between about 0.6 and 1.3 bits per letter, "of the order of one bit per letter" ("Prediction and Entropy of Printed English", 1951). Longer context lowers loss because it lowers the conditional entropy a model can reach.

Chinchilla's fit puts a number on the floor: in Lˆ(N,D)=E+A/Nα+B/Dβ\hat L(N, D) = E + A/N^{\alpha} + B/D^{\beta}, the constant EE, which the paper calls "the entropy of natural text" (Hoffmann et al. 2022, §D.2), is fitted as 1.69 nats per token (2.44 bits; perplexity 5.4) on its own data and tokenizer; a refit of the same form by Besiroglu et al. (2024) gives 1.82 (2.63 bits). Both are extrapolations of a fitted curve to infinite model and data, not measurements, and both are per token under one tokenizer (Chinchilla page). Read the terms as this page's split: A/NαA/N^\alpha and B/DβB/D^\beta are the KL that more parameters and more data remove; EE is the entropy, which nothing removes. The floor of a classifier is the same idea, H(Y|X)H(Y \mid X): zero only when every input has exactly one correct label.

The final interval's width is the product of the probabilities, so its bits are the total surprise

Compression is prediction: arithmetic coding

Start with [0,1)[0, 1). For each symbol, split the current interval in proportion to the model's probabilities and keep the slice of the symbol that occurred; at the end, send just enough bits to name a number inside the final slice. Here the tiny model's bet, used as a fixed predictor, encodes "sat cat cat":

  1. Start: the whole interval [0, 1). Split it in proportion to the bet: cat takes the first 0.665, dog the next 0.245, sat the last 0.090. The message is "sat cat cat".
  2. Symbol 1: sat. Keep sat's slice, [0.910, 1.000), width 0.090, and split it again in the same proportions (each row is zoomed to fill the width).
  3. Symbol 2: cat. Keep cat's part of that slice: width 0.090×0.665=0.05990.090 \times 0.665 = 0.0599.
  4. Symbol 3: cat. Width 0.0599×0.665=0.03980.0599 \times 0.665 = 0.0398. Any number inside the final interval identifies the whole message, and naming one to that precision takes about −log2⁡0.0398=4.65-\log_2 0.0398 = 4.65 bits.

The 4.65 bits are 3.473+0.588+0.5883.473 + 0.588 + 0.588, the three surprises added up; a real coder adds at most about two bits for the whole message (MacKay §6.2). A language model plugs in q(xt|x<t)q(x_t \mid x_{\lt t}) at each step instead of a fixed bet, and the decoder runs the same model to rebuild the same intervals. So a model's total loss on a text, in bits, is the size of the file it would compress that text to.

The models reach about 1 bit per byte or less; the best general-purpose compressor, brotli, needs 2.57, and brotli already ships a built-in dictionary of 122,784 bytes of common words and phrases (RFC 7932, Appendix A), a tiny frozen prior, the same idea as a pretrained model. Classical compressors learn only from the text in front of them, so they improve with length: on the whole 953,697-byte book bzip2 reaches 1.92 bits per byte and xz 2.09, still about twice what the models achieve on a 10 KB excerpt (Real text, measured plots it against length).

"Language Modeling Is Compression" (Delétang et al., ICLR 2024) feeds models' predictions to an arithmetic coder on 1 GB of text (enwik9), image patches (ImageNet) and audio (LibriSpeech), each in 2,048-byte chunks. Table 1, raw rates (compressed over raw size): Chinchilla 70B compresses enwik9 to 8.3% (0.66 bits per byte), against 32.3% for gzip on the whole file (2.58 bits per byte); on images and audio, which it was not trained on, it reaches 48.0% and 21.0%, against PNG's 58.5% (whole file) and FLAC's 30.3% (in chunks).

Four small language models need about 1 bit per byte or less; the best general compressor needs 2.57

Bits per byte on the 10,376-byte Darwin passage (lower is better). Compressors are real runs (src/data/comp.py: Apple gzip 487.0.1, bzip2 1.0.8, xz 5.8.2, zstd 1.5.7, brotli 1.1.0, each at its strongest setting); models are total loss in bits over bytes. Order-0 Huffman codes each byte on its own, with no context.

Correction: the headline numbers are not in the paper's table
The abstract and introduction say Chinchilla 70B "compresses ImageNet patches to 43.4% and LibriSpeech samples to 16.4% of their raw size". Table 1 of the same paper, in both arXiv versions (v1 of 19 September 2023 and v2 of 18 March 2024), gives 48.0% and 21.0% for Chinchilla 70B; we found 43.4% nowhere else in the paper, and 16.4% only as an unrelated cell of Table 2 (a 6.4M-parameter model with a 20K BPE vocabulary on enwik9). The abstract also sets the model's chunked rate against PNG's whole-file rate (58.5%; PNG in chunks is 61.7%) and FLAC's chunked rate (30.3%; whole-file 30.9%). The conclusion survives either way: the model beats both domain compressors. Quote the table, and say whether the rate counts the model's size. The old version of this page quoted the abstract's numbers.

Counting the model. The decoder needs the model too. Delétang et al.'s "adjusted" rate adds the parameters to the compressed size: Chinchilla 70B's enwik9 rate becomes 14,008.3%, and their Figure 2 shows an optimal model size for each dataset size, past which a bigger model compresses worse once its own size is counted. Here, GPT-2's about 124 million parameters are roughly 250 MB in 16-bit floats, some 24,000 times the 10 KB passage it compresses so well derived. Prediction and compression are the same thing; whether a model is a practical compressor depends on how much data it is amortised over (see also Pretraining for loss curves against data).

Tokenization is compression too (Delétang et al., Table 2)
The paper trains small Transformers on enwik8 with different tokenizers and measures raw rates on enwik9. The best choice depends on model size: at 200K parameters a 20K-token BPE vocabulary wins (19.3% against 22.9% with plain ASCII bytes), at 38M parameters ASCII wins (6.4% against 9.0%). The paper's reading: a bigger vocabulary packs more text into the context but makes each prediction harder.

8. Conditional entropy and mutual information: what knowing one thing tells you about another

Two fair binary signals XX and YY agree 80% of the time: p(0,0)=p(1,1)=0.4p(0,0) = p(1,1) = 0.4, p(0,1)=p(1,0)=0.1p(0,1) = p(1,0) = 0.1. Each alone has 1 bit. The pair has the joint entropy H(X,Y)=2×0.4×1.322+2×0.1×3.322=1.722H(X, Y) = 2 \times 0.4 \times 1.322 + 2 \times 0.1 \times 3.322 = 1.722 bits. Once YY is known, XX is 0.8 likely to match it, so what is left is the conditional entropy H(X|Y)=H(0.8,0.2)=0.722H(X \mid Y) = H(0.8, 0.2) = 0.722 bits. The 0.278 bits that knowing YY saves is the mutual information.

I(X;Y)=H(X)−H(X|Y)=DKL(p(x,y)‖p(x)p(y))I(X; Y) = H(X) - H(X \mid Y) = D_{\mathrm{KL}}\big(p(x, y) \,\Vert\, p(x)\,p(y)\big)

The chain rule H(X,Y)=H(Y)+H(X|Y)H(X, Y) = H(Y) + H(X \mid Y) says the uncertainty of the pair is the uncertainty of one plus what is left of the other (section 7 applies it to a whole text), so also I=H(X)+H(Y)−H(X,Y)I = H(X) + H(Y) - H(X, Y).

The shared 0.278 bits is counted once in the joint

H(X)H(X)
H(X|Y) 0.722I 0.278
H(Y)H(Y)
I 0.278H(Y|X) 0.722
H(X,Y)H(X,Y)
0.7220.2780.722

The bits of the two signals to scale (the top two bars are 1 bit each on their own width; the bottom bar's full width is 1.722 bits).

Fig. 4 builds the same number from the table of the two signals.

  1. The joint: four cells. The bars are p(x,y)p(x, y): 0.4 where the signals agree, 0.1 where they differ. Their entropy is H(X,Y)=1.722H(X, Y) = 1.722 bits.
  2. The marginals on the edges. Adding each row and each column gives p(x)p(x) and p(y)p(y), 0.5 each: each signal alone is a fair bit, H(X)=H(Y)=1H(X) = H(Y) = 1.
  3. Independence would be the product. If the signals were unrelated, each cell would hold p(x)p(y)=0.25p(x)\,p(y) = 0.25, the glass lids. The agreeing cells stand above their lids and the disagreeing ones fall short.
  4. The gap, cell by cell, is the mutual information. Each cell adds p(x,y)log2⁡p(x,y)p(x)p(y)p(x, y) \log_2 \frac{p(x, y)}{p(x)\,p(y)}: +0.271 bits for each agreeing cell, −0.132-0.132 for each disagreeing one, 0.278 bits in all.
  5. Zero correlation, plenty of information. XX is −1-1, 0 or 1 with equal probability and Y=X2Y = X^2. Three cells are filled, a third each, and every one stands above its lid: I=0.918I = 0.918 bits, although the correlation is 0 (the box below).

The KL form says mutual information is how far the joint is from independence, p(x)p(y)p(x)p(y), which is what Fig. 4 adds up cell by cell. Because it is a KL, I≥0I \ge 0, so conditioning never increases entropy on average, H(X|Y)≤H(X)H(X \mid Y) \le H(X), with equality exactly at independence. A single value can still raise it (a usually reliable test coming back strange can make you less sure); only the average must fall. Mutual information is symmetric, I(X;X)=H(X)I(X; X) = H(X), and, unlike correlation, unchanged by any invertible transform of either variable.

Zero correlation, plenty of information
Let XX be −1-1, 0 or 1 with equal probability and Y=X2Y = X^2. The correlation is 0 (𝔼[XY]=𝔼[X3]=0\mathbb{E}[XY] = \mathbb{E}[X^3] = 0 and 𝔼[X]=0\mathbb{E}[X] = 0), yet YY is a function of XX: H(Y)=0.918H(Y) = 0.918 bits (YY is 1 with probability 2/3), H(Y|X)=0H(Y \mid X) = 0, so I(X;Y)=0.918I(X; Y) = 0.918 bits. Only zero mutual information means independence.
The chain rule and the KL form, derived
  1. p(x,y)=p(y)p(x|y)p(x, y) = p(y)\, p(x \mid y); take −log⁡-\log: −log⁡p(x,y)=−log⁡p(y)−log⁡p(x|y)-\log p(x, y) = -\log p(y) - \log p(x \mid y).
  2. Average over (x,y)∼p(x, y) \sim p: the left is H(X,Y)H(X, Y), the first right term only depends on yy and averages to H(Y)H(Y), the second is H(X|Y)H(X \mid Y), which is −∑x,yp(x,y)log⁡p(x|y)-\sum_{x, y} p(x, y) \log p(x \mid y), the same as ∑yp(y)H(X|Y=y)\sum_y p(y) H(X \mid Y = y). So H(X,Y)=H(Y)+H(X|Y)=H(X)+H(Y|X)H(X, Y) = H(Y) + H(X \mid Y) = H(X) + H(Y \mid X).
  3. Subtract H(X|Y)H(X \mid Y) from H(X)=−∑x,yp(x,y)log⁡p(x)H(X) = -\sum_{x,y} p(x, y) \log p(x): I=∑x,yp(x,y)log⁡p(x|y)p(x)I = \sum_{x,y} p(x, y) \log \frac{p(x \mid y)}{p(x)}, and p(x|y)p(x)=p(x,y)p(x)p(y)\frac{p(x \mid y)}{p(x)} = \frac{p(x, y)}{p(x)\,p(y)}, which is the KL form.

The data processing inequality

A message XX (a fair bit) is copied with a 10% chance of a flip to give YY, and YY copied again the same way to give ZZ. I(X;Y)=1−H(0.1)=1−0.469=0.531I(X; Y) = 1 - H(0.1) = 1 - 0.469 = 0.531 bits; ZZ differs from XX when exactly one flip happens, 2×0.1×0.9=0.182 \times 0.1 \times 0.9 = 0.18, so I(X;Z)=1−H(0.18)=0.320I(X; Z) = 1 - H(0.18) = 0.320 bits. Each copy loses information and none gains it. In general, for a Markov chain X→Y→ZX \to Y \to Z (ZZ computed from YY alone, p(x,y,z)=p(x)p(y|x)p(z|y)p(x, y, z) = p(x)\,p(y \mid x)\,p(z \mid y)):

I(X;Z)≤I(X;Y)I(X; Z) \le I(X; Y)

MacKay: "data processing can only destroy information" (§8.3, exercise 8.9). The layers of a network form such a chain, so a hidden layer cannot carry more information about the label than the input does. Training does not add information; it makes the useful information easier to extract by a simple final layer, which Shannon information does not measure. The same quantity ranks features (information gain in trees is exactly mutual information, section 1), and the information bottleneck asks for a representation that keeps as little as possible about the input while keeping as much as possible about the label (Tishby, Pereira and Bialek 1999).

Proof of the data processing inequality
The chain rule for mutual information, I(X;Y,Z)=I(X;Z)+I(X;Y|Z)I(X; Y, Z) = I(X; Z) + I(X; Y \mid Z) =I(X;Y)+I(X;Z|Y)= I(X; Y) + I(X; Z \mid Y), follows from the entropy chain rule applied to H(X)−H(X|⋅)H(X) - H(X \mid \cdot). The conditional mutual information I(X;Z|Y)I(X; Z \mid Y), what ZZ tells about XX once YY is known, is 0 in a Markov chain, because ZZ depends on XX only through YY. So I(X;Y)=I(X;Z)+I(X;Y|Z)I(X; Y) = I(X; Z) + I(X; Y \mid Z), and I(X;Y|Z)≥0I(X; Y \mid Z) \ge 0 (an average of KL divergences) gives I(X;Y)≥I(X;Z)I(X; Y) \ge I(X; Z).

9. InfoNCE: a classification loss that bounds mutual information, up to ln⁡N\ln N

Read the tiny model as a contrastive scorer: cat is the positive (the candidate that truly goes with the anchor), dog and sat the negatives, scores 2, 1, 0. Picking the positive with a softmax costs −ln⁡0.665=0.408-\ln 0.665 = 0.408 nats, and that loss certifies I≥ln⁡3−0.408=0.691I \ge \ln 3 - 0.408 = 0.691 nats of mutual information between anchor and positive. With sat as the positive the loss is 2.408 and the bound is negative: it certifies nothing.

LNCE=−𝔼[log⁡ef(x,y+)∑j=1Nef(x,yj)],I(X;Y)≥ln⁡N−LNCEL_{\text{NCE}} = -\,\mathbb{E}\left[\log \frac{e^{f(x, y^+)}}{\sum_{j=1}^{N} e^{f(x, y_j)}}\right], \qquad I(X; Y) \ge \ln N - L_{\text{NCE}}

The InfoNCE loss is an NN-way classification whose classes are the candidates in the batch (one positive, N−1N - 1 negatives, usually the other batch items), scored by a learned critic f(x,y)f(x, y), often a scaled cosine similarity (van den Oord et al. 2018, §2.3; proved exactly by Poole et al. 2019, details below). A loss is never negative, so the bound can never exceed ln⁡N\ln N: with 4 candidates even a perfect critic certifies at most ln⁡4=1.386\ln 4 = 1.386 nats. Poole et al. (§2.3, with KK for NN): "INCEI_{\text{NCE}} is upper bounded by log⁡K\log K, meaning that this bound will be loose when I(X;Y)>log⁡KI(X; Y) > \log K". Predict before you choose a correlation: with a perfect critic and 16 candidates, what does InfoNCE report for a true 5.41 nats?

With weak dependence (ρ=0.5\rho = 0.5) every batch size gets close to the truth, from below. With strong dependence (5.41 nats) the estimate rides the ln⁡N\ln N ceiling until NN is in the hundreds: 2.73 nats at N=16N = 16, 5.20 at 1,024. The ceiling is not a quirk of InfoNCE: McAllester and Stratos (2020) prove that "any distribution-free high-confidence lower bound on mutual information estimated from N samples cannot be larger than O(ln N)". CLIP trains with 32,768 image-text pairs per batch, so each direction is a 32,768-way classification with a ceiling of ln⁡32,768=10.4\ln 32{,}768 = 10.4 nats (15 bits) (Radford et al. 2021). Reading any reported "mutual information" estimate: check the batch size first; a value near ln⁡N\ln N is the ceiling talking. InfoNCE as a training method (SimCLR, MoCo, SimCSE, temperature, collapse) is on Contrastive and self-supervised learning; the CLIP page trains a toy one.

A small batch does not just add noise; it caps what the loss can certify

estimate ln N − Lln N, the ceiling (dashed)true I

Two correlated Gaussians, x∼𝒩(0,1)x \sim \mathcal{N}(0,1), y=ρx+1−ρ2εy = \rho x + \sqrt{1-\rho^2}\,\varepsilon, whose mutual information is known, I=−12ln⁡(1−ρ2)I = -\tfrac12 \ln(1 - \rho^2). The optimal critic f=log⁡p(y|x)−log⁡p(y)f = \log p(y \mid x) - \log p(y); for each NN, 2,048 anchors in batches of NN (two batches at N=1,024N = 1{,}024); seeded random numbers (mulberry32, seed 7) identical here and in src/recompute.py.

The exact bound, the best critic, CLIP's temperature, and a worked batch of four

The CPC derivation used an approximation; Poole et al. 2019 (eq. 10 and footnote 2) prove the bound exactly and show the best critic is the log density ratio log⁡p(y|x)p(y)\log \frac{p(y \mid x)}{p(y)} plus any function of xx alone (it cancels inside the softmax). CLIP's loss is symmetric (image to text and text to image), and its temperature, which divides the similarities before the softmax, is learned as a log-parameterised scalar initialised to 0.07 and clipped so the logits are never scaled by more than 100 (Radford et al. 2021, §2.3 and §2.5).

N=4N = 4, positive scored 2.0, three negatives 0.0: the positive's probability is e2/(e2+3)=7.389/10.389=0.711e^2/(e^2 + 3) = 7.389 / 10.389 = 0.711, the loss −ln⁡0.711=0.341-\ln 0.711 = 0.341 nats, and I≥ln⁡4−0.341=1.386−0.341=1.046I \ge \ln 4 - 0.341 = 1.386 - 0.341 = 1.046 nats (1.51 bits).

10. KL penalties: RL fine-tuning, DPO and the ELBO

Take the tiny model as a policy: reference πref\pi_{\text{ref}} = (cat 0.665, dog 0.245, sat 0.090), reward 1 for sat and 0 otherwise illustrative. Fine-tuning with a reward model r(x,y)r(x, y) usually maximises reward minus a KL to the reference:

maxπ⁡𝔼x∼𝒟,y∼π(⋅|x)[r(x,y)]−βDKL(π(⋅|x)‖πref(⋅|x))⟹π∗(y)=1Zπref(y)er(y)/β\max_{\pi}\; \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi(\cdot \mid x)}\big[r(x, y)\big] \;-\; \beta\, D_{\mathrm{KL}}\big(\pi(\cdot \mid x) \,\Vert\, \pi_{\text{ref}}(\cdot \mid x)\big) \;\;\Longrightarrow\;\; \pi^*(y) = \frac{1}{Z}\, \pi_{\text{ref}}(y)\, e^{r(y)/\beta}

This is equation 3 of the DPO paper; InstructGPT puts the same term into the reward per sample as rθ(x,y)−βlog⁡πRL(y|x)πSFT(y|x)r_\theta(x, y) - \beta \log \frac{\pi^{\text{RL}}(y \mid x)}{\pi^{\text{SFT}}(y \mid x)} (Ouyang et al. 2022, eq. 2), whose average over y∼πy \sim \pi is exactly βDKL\beta D_{\mathrm{KL}}. The ideal fine-tuned model is the reference reweighted by ereward/βe^{\text{reward}/\beta}: small β\beta lets rewards dominate and concentrate the policy on the best response, large β\beta barely moves it, and nothing gets probability the reference does not give, because the KL is reverse (section 4). DPO runs the closed form backwards: solve it for the reward, r(x,y)=βlog⁡π∗(y|x)πref(y|x)+βlog⁡Z(x)r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x) (DPO eq. 5), substitute into a preference model where only reward differences matter, and Z(x)Z(x) cancels, leaving a loss on the policy alone (DPO page; the family is compared on Alignment: SFT, RLHF, DPO Family, RLVR and the RL algorithms on RL for LLMs).

What a KL budget guarantees: Pinsker's inequality, TV(π,πref)≤DKL/2\mathrm{TV}(\pi, \pi_{\text{ref}}) \le \sqrt{D_{\mathrm{KL}}/2} (KL in nats), bounds the total variation, the largest possible change in the probability of any event. So a KL penalty becomes a guarantee about behaviour: no event's probability can move by more than KL/2\sqrt{\mathrm{KL}/2}. On the tiny policy at β=1\beta = 1, sat moved by 0.122, within 0.068/2=0.18\sqrt{0.068/2} = 0.18.

The optimum reweights the reference by ereward/β; cat and dog keep their ratio at every β

Exact optimum on the tiny policy for each β\beta (src/recompute.py). At β=1\beta = 1: Z=0.665+0.245+0.090e=1.155Z = 0.665 + 0.245 + 0.090\,e = 1.155, π∗=(0.576,0.212,0.212)\pi^* = (0.576, 0.212, 0.212); expected reward rises from 0.090 to 0.212 at a KL of 0.068 nats, and the objective 0.212−0.068=0.1440.212 - 0.068 = 0.144 equals βln⁡Z=ln⁡1.155\beta \ln Z = \ln 1.155.

Deriving the closed-form optimum (DPO, Appendix A.1, one prompt)
  1. Write the objective as one average over y∼πy \sim \pi: 𝔼π[r(y)−βlog⁡π(y)πref(y)]\mathbb{E}_{\pi}\big[r(y) - \beta \log \frac{\pi(y)}{\pi_{\text{ref}}(y)}\big].
  2. Divide by −β-\beta to minimise: minπ⁡𝔼π[log⁡π(y)πref(y)er(y)/β]\min_\pi \mathbb{E}_\pi\big[\log \frac{\pi(y)}{\pi_{\text{ref}}(y)\, e^{r(y)/\beta}}\big].
  3. Normalise the denominator: Z=∑yπref(y)er(y)/βZ = \sum_y \pi_{\text{ref}}(y) e^{r(y)/\beta}, π∗(y)=πref(y)er(y)/β/Z\pi^*(y) = \pi_{\text{ref}}(y)\, e^{r(y)/\beta} / Z; the objective is DKL(π‖π∗)−log⁡ZD_{\mathrm{KL}}(\pi \Vert \pi^*) - \log Z.
  4. ZZ does not depend on π\pi, and the KL is 0 only at π=π∗\pi = \pi^* (Gibbs, section 3); the best achievable objective is βlog⁡Z\beta \log Z.

Estimating the KL from sampled tokens

The KL over all possible responses cannot be summed, so it is estimated from samples y∼πy \sim \pi with r=πref(y)/π(y)r = \pi_{\text{ref}}(y)/\pi(y). John Schulman's note ("Approximating KL Divergence", 7 March 2020) compares k1=−log⁡rk_1 = -\log r (unbiased, but negative for some samples, high variance), k2=12(log⁡r)2k_2 = \tfrac12 (\log r)^2 (always positive, low variance, biased) and k3=(r−1)−log⁡rk_3 = (r - 1) - \log r (unbiased and always positive, because log⁡r≤r−1\log r \le r - 1). GRPO uses k3k_3 (DeepSeekMath, eq. 4); the DeepSeekMath page explains why differentiating k3k_3 inside the loss does not give the gradient of the KL it estimates.

The three estimators on the tiny policy
At β=1\beta = 1, true DKL(π∗‖πref)=0.0681D_{\mathrm{KL}}(\pi^* \Vert \pi_{\text{ref}}) = 0.0681 nats. A cat or dog sample has r=1.155r = 1.155: k1=−0.144k_1 = -0.144 (negative), k2=0.010k_2 = 0.010, k3=0.011k_3 = 0.011. A sat sample has r=0.425r = 0.425: k1=0.856k_1 = 0.856, k2=0.367k_2 = 0.367, k3=0.281k_3 = 0.281. Averaged over π∗\pi^*: 𝔼[k1]=𝔼[k3]=0.0681\mathbb{E}[k_1] = \mathbb{E}[k_3] = 0.0681 exactly, 𝔼[k2]=0.0858\mathbb{E}[k_2] = 0.0858 (biased upwards here).

The ELBO is the same identity, with a reverse KL

log⁡p(x)=𝔼q[log⁡p(x,z)−log⁡q(z)]⏟ELBO+DKL(q(z)‖p(z|x))\log p(x) = \underbrace{\mathbb{E}_{q}[\log p(x, z) - \log q(z)]}_{\text{ELBO}} + D_{\mathrm{KL}}\big(q(z) \,\Vert\, p(z \mid x)\big)

For a latent-variable model with an encoder qϕ(z|x)q_\phi(z \mid x), the log-evidence splits into the evidence lower bound plus a reverse KL to the true posterior; since the KL is ≥0\ge 0 the first term is a lower bound, and raising it by changing qq lowers that KL by exactly the same amount (Kingma and Welling 2013, eq. 3, write it as a reconstruction term minus DKL(q(z|x)‖p(z))D_{\mathrm{KL}}(q(z \mid x) \Vert p(z))). The Gaussian KL term in closed form (0.818 nats for μ=1,σ=0.5\mu = 1, \sigma = 0.5), VAEs and diffusion as a chain of KL terms are derived on Variational inference and generative-model maths.

The ELBO identity in three lines
  1. For any zz: log⁡p(x)=log⁡p(x,z)−log⁡p(z|x)\log p(x) = \log p(x, z) - \log p(z \mid x); add and subtract log⁡q(z)\log q(z).
  2. Average over z∼qz \sim q; the left does not depend on zz, and the two brackets become the ELBO and DKL(q(z)‖p(z|x))D_{\mathrm{KL}}(q(z) \Vert p(z \mid x)).
  3. Splitting log⁡p(x,z)=log⁡p(z)+log⁡p(x|z)\log p(x, z) = \log p(z) + \log p(x \mid z) gives ELBO=−DKL(q(z|x)‖p(z))\mathrm{ELBO} = -D_{\mathrm{KL}}\big(q(z \mid x) \Vert p(z)\big) +𝔼q[log⁡p(x|z)]+\, \mathbb{E}_{q}\big[\log p(x \mid z)\big] (Kingma and Welling 2013, eq. 3); with q=𝒩(μ,σ2)q = \mathcal{N}(\mu, \sigma^2) and p(z)=𝒩(0,1)p(z) = \mathcal{N}(0, 1) the KL per dimension is 12(σ2+μ2−1−ln⁡σ2)\tfrac12(\sigma^2 + \mu^2 - 1 - \ln \sigma^2) (their Appendix B, which writes its negative).

11. Estimating entropy and mutual information from samples

Count which byte follows each context of N−1N - 1 bytes in the 10,376-byte Darwin passage, plug the frequencies into the formula, and the conditional entropy seems to fall to 0.18 bits per byte at N=8N = 8, far below the 0.85 that a 0.5B-parameter language model achieves. Predict before you look: have the counts learned English better than the model?

No. With about ten thousand positions, most 7-byte contexts occur once, so the "next byte" is always certain in the sample. On the whole book the same estimate falls more slowly (0.81 bits at N=8N = 8) and would keep falling with longer contexts. Shannon's 1951 lower bound of about 0.6 bits per letter is the sanity check: a count-based estimate below it on a short sample is the estimator, not the text. The obvious estimator, count, divide by NN and compute −∑pˆlog⁡pˆ-\sum \hat p \log \hat p (the plug-in or maximum-likelihood estimator), is biased downwards: outcomes not yet seen count as impossible, and the seen ones look more concentrated than they are. For mm possible outcomes and NN samples,

𝔼[Hˆplug-in]−H≈−m−12N nats\mathbb{E}\big[\hat H_{\text{plug-in}}\big] - H \approx -\frac{m - 1}{2N} \text{ nats}

(Paninski 2003, eq. 4.6, completing Miller's 1955 result; valid when NN is large compared with mm.) The Miller-Madow correction adds (mˆ−1)/(2N)(\hat m - 1)/(2N) back, with mˆ\hat m the number of outcomes actually seen; the same bias as a case of estimator bias and variance in general, with an exact table on the tiny model's three words, is section 2 of Statistics for ML.

Counting looks like it beats the models after a few bytes of context; it is memorising

whole book, 953,697 bytesthe passage, 10,376 bytesGPT-2 on the passage, 1.003Qwen2.5-0.5B on the passage, 0.850

Plug-in estimate of FNF_N, the entropy of the next byte given the previous N−1N-1, counted on all of Origin of Species and on the passage alone, against two real models on the passage. Bytes, not Shannon's 27 letters, so the levels are not comparable with his.

Mutual information inherits the bias, with a twist. In I=H(X)+H(Y)−H(X,Y)I = H(X) + H(Y) - H(X, Y) the joint has many more cells (mXmYm_X m_Y) than the marginals, so it is underestimated the most, and the plug-in mutual information comes out too high, by about (mX−1)(mY−1)2N\frac{(m_X - 1)(m_Y - 1)}{2N} nats (the Miller-Madow terms combined; derived here, not quoted). Independent variables look dependent:

Two independent variables, 10 values each (true I=0I = 0)
With 100 samples, two variables that have nothing to do with each other show 0.48 nats (0.69 bits) of "shared information": reading a plug-in mutual information without its bias is a classic way to find structure in noise.

High dimensions: bounds instead of counts. For images, sentences or embeddings every sample is unique, so methods switch to variational bounds learned by a network, InfoNCE (section 9) and others that trade bias against variance (Poole et al. 2019: "the existing variational lower bounds degrade when the MI is large, exhibiting either high bias or high variance"), all under the O(ln⁡N)O(\ln N) limit of section 9.

At N = m samples the plug-in entropy is half a nat low; the correction helps but cannot invent unseen outcomes

plug-inMiller-Madowtruth minus (m − 1)/(2N) (dashed)truth, ln 100

A uniform distribution over 100 outcomes (true entropy ln⁡100=4.605\ln 100 = 4.605 nats), sampled NN times, 200 repetitions per NN, seeded (mulberry32, seed 11) identically here and in src/recompute.py. At N=100N = 100 the plug-in averages 4.04 nats, 0.56 below the truth (the formula predicts 0.50); at N=25N = 25 it is 1.54 below.

A checklist for any reported entropy or mutual information
  1. How many samples per possible outcome (or per cell of the joint)? Below a few, plug-in numbers are mostly bias.
  2. Was a bias correction or a shuffled-data baseline used? Shuffle YY against XX and re-estimate: the shuffled value is the noise floor of "independent".
  3. For continuous data, how was it binned? The answer changes with the bins.
  4. For a variational bound: what was NN (the batch size)? Is the reported value near ln⁡N\ln N?
  5. In bits or nats?

12. More depth: KL's family, and which quantity to use when

f-divergences and Jensen-Shannon: GAN papers' Jensen-Shannon, chi-squared and total variation are one idea

Pick any convex ff with f(1)=0f(1) = 0. The f-divergence of pp from qq averages ff of the likelihood ratio under qq, Df(p‖q)=∑xq(x)f(p(x)q(x))D_f(p \Vert q) = \sum_x q(x)\, f\big(\frac{p(x)}{q(x)}\big), and Jensen gives Df≥f(∑xqpq)=f(1)=0D_f \ge f\big(\sum_x q \tfrac{p}{q}\big) = f(1) = 0 every time (Nowozin, Cseke and Tomioka 2016 (f-GAN), eq. 2 and Table 1).

namef(u)f(u)weather pp from qq, natsnotes
KL DKL(p‖q)D_{\mathrm{KL}}(p \Vert q)uln⁡uu \ln u0.1730.25 bits; section 3
reverse KL DKL(q‖p)D_{\mathrm{KL}}(q \Vert p)−ln⁡u-\ln u0.173equal here only because qq is pp with two outcomes swapped
Pearson χ2\chi^2(u−1)2(u-1)^20.375blows up where qq is small
squared Hellinger(u−1)2(\sqrt u - 1)^20.086symmetric; some books halve it
total variation12|u−1|\tfrac12 \lvert u - 1\rvert0.25012∑x|p−q|\tfrac12 \sum_x \lvert p - q\rvert; symmetric, a true metric, at most 1
Jensen-Shannon12[uln⁡2u1+u+ln⁡21+u]\tfrac12\big[u \ln \tfrac{2u}{1+u} + \ln \tfrac{2}{1+u}\big]0.042symmetric, at most ln⁡2=0.693\ln 2 = 0.693

Weather: pp = (0.5, 0.25, 0.25), qq = (0.25, 0.5, 0.25), recomputed in src/recompute.py from the generators. f-GAN's Table 1 defines Jensen-Shannon with the 12\tfrac12 but lists the generator uln⁡u−(u+1)ln⁡1+u2u \ln u - (u+1)\ln\tfrac{1+u}{2} without it, which gives twice the value (0.085 here); the generator above includes the 12\tfrac12.

Jensen-Shannon, JS(p,q)=12DKL(p‖m)+12DKL(q‖m)\mathrm{JS}(p, q) = \tfrac12 D_{\mathrm{KL}}(p \Vert m) + \tfrac12 D_{\mathrm{KL}}(q \Vert m) with m=12(p+q)m = \tfrac12(p + q), is how far each distribution is from their average. It is always finite, symmetric and at most ln⁡2\ln 2 nats (1 bit), reached when pp and qq do not overlap (p=(1,0)p = (1, 0), q=(0,1)q = (0, 1): 12ln⁡2+12ln⁡2=0.693\tfrac12 \ln 2 + \tfrac12 \ln 2 = 0.693). The cap is also a weakness: once two distributions stop overlapping, JS stays at ln⁡2\ln 2 however far apart they move, so it gives no gradient telling them to come closer.

GANs. The original GAN objective at the best discriminator equals 2JS(pdata,pmodel)−ln⁡42\,\mathrm{JS}(p_{\text{data}}, p_{\text{model}}) - \ln 4 (Goodfellow et al. 2014, as restated in f-GAN's Table 1), so the generator minimises JS; f-GAN minimises any f-divergence through its variational lower bound Df(p‖q)≥supT⁡(𝔼p[T(x)]−𝔼q[f∗(T(x))])D_f(p \Vert q) \ge \sup_T \big(\mathbb{E}_p[T(x)] - \mathbb{E}_q[f^*(T(x))]\big) (eq. 4), with f∗f^* the convex conjugate and the discriminator playing TT.

Near agreement they all look alike: Df(p0,pθ)≈f′′(1)2θ⊤FθD_f(p_0, p_\theta) \approx \tfrac{f''(1)}{2}\, \theta^\top F \theta, with FF the Fisher information (Schulman, "Approximating KL Divergence", 2020); for KL, f′′(1)=1f''(1) = 1. This is why trust regions measured in KL (TRPO, PPO's KL variants) behave like Fisher-weighted step limits, the connection the root's "Curvature is read three ways" box makes. Pinsker's inequality (section 10) on the weather: 0.25≤0.173/2=0.2940.25 \le \sqrt{0.173/2} = 0.294.

Which quantity to use when
  • Training a predictor of discrete outcomes (classes, tokens): minimise cross-entropy; it is the negative log-likelihood, and the only part you can change is the KL to the data.
  • Reporting a language model's quality: perplexity only within one tokenizer and one evaluation set; bits per byte (or per character, saying which) across tokenizers.
  • Keeping a fine-tuned model close to its starting point: a reverse KL penalty DKL(π‖πref)D_{\mathrm{KL}}(\pi \Vert \pi_{\text{ref}}); expect it to trade some diversity for staying on the reference's high-probability outputs.
  • Fitting an approximate distribution: forward KL when missing a mode is the worse failure; reverse KL when putting mass where the target has none is, or when only the approximation can be sampled.
  • Measuring dependence: mutual information when it may be nonlinear, with a bias check; correlation only for linear relationships; for high-dimensional variables a bound such as InfoNCE, remembering it cannot exceed ln⁡N\ln N.
  • How confident a prediction is: the entropy of the predicted distribution, 0 for certain and log⁡K\log K for uniform.
  • Comparing two distributions symmetrically, or with a bounded number: Jensen-Shannon (at most ln⁡2\ln 2) or total variation (at most 1).

Go deeper: the Further reading tab lists the root page's tabs, the sibling pages, and the textbooks chapter by chapter.