Skip to content
Mathematical foundations Core 25 min read

Entropy, cross-entropy and KL divergence

Information theory measures surprise. Entropy is the average surprise of a source, cross-entropy is the average surprise when you predict that source with a model, and KL divergence is the gap between the two. The loss every language model is trained on is cross-entropy, so a good LLM is, quite literally, a good compressor of text.

10,000 ft

Claude Shannon built information theory in 1948 to answer an engineering question: how few bits can a message be squeezed into, and how fast can it be sent over a noisy line? The answers turned out to be the vocabulary of machine learning. Cross-entropy is the standard classification and language-modelling loss, and perplexity is its exponential. KL divergence keeps a fine-tuned model close to its reference in RLHF, defines the VAE objective, drives knowledge distillation, and appears inside DPO's derivation. Mutual information underlies contrastive learning (CLIP, InfoNCE). And the equivalence between prediction and compression is a working lens on what LLMs do. This page derives all of it from one definition, using probability, distributions and the MLE view of training.

2,000 ft

Everything is built from the surprisal of an outcome, \(-\log p(x)\): rare outcomes are surprising, certain ones are not. Average it in different ways and you get the whole family:

One definition, five quantities
One definition, five quantities. Surprisal −log p(x), Entropy H(p) average surprisal under p, Cross-entropy H(p, q) surprisal of model q on data from p, KL(p ‖ q) = H(p, q) − H(p) extra bits from using q, Mutual information I(X; Y) KL from joint to product of marginals, Training loss minimise H(p_data, q_θ) = minimise KL = MLEOne definition, five quantities. Surprisal −log p(x), Entropy H(p) average surprisal under p, Cross-entropy H(p, q) surprisal of model q on data from p, KL(p ‖ q) = H(p, q) − H(p) extra bits from using q, Mutual information I(X; Y) KL from joint to product of marginals, Training loss minimise H(p_data, q_θ) = minimise KL = MLE

Entropy is fixed by the data; only the KL term depends on the model. So minimising cross-entropy over the model is minimising the KL divergence from the data distribution, which is maximum likelihood. Three names, one objective.

Ground level

Surprise, and why it is a logarithm

How much information do you get from learning that an event of probability \(p\) happened? We want a measure \(I(p)\) that is zero for a certain event, larger for rarer events, and additive for independent events: learning two independent facts should give the sum of their information. Since independent probabilities multiply, \(I(p_1 p_2) = I(p_1) + I(p_2)\), and the only continuous functions with that property are logarithms. So

\[ I(x) = -\log p(x). \]

With \(\log_2\) the unit is the bit; with the natural log it is the nat (1 nat = 1.443 bits). Frameworks compute losses in nats. A fair coin flip is 1 bit; one of 8 equally likely outcomes is 3 bits; an event with probability 0.001 is about 10 bits; a certain event is 0 bits.

Entropy: the average surprise

The entropy of a distribution is its expected surprisal:

\[ H(p) = -\sum_x p(x) \log p(x) . \]

It measures how unpredictable the source is. A coin with \(p(\text{heads}) = 0.5\) has 1 bit of entropy; at \(p = 0.11\) it has 0.5 bits; at \(p = 0\) or \(1\) it has none.

p = 0.11: 0.50 bitsp = 0.5: 1.00 bits0p(heads)11 bit0
Entropy of a coin. A fair coin carries 1 bit per flip; a coin that lands heads 11% of the time carries only 0.5 bits, so a long sequence of its flips can be compressed to half the length. A certain outcome carries nothing.

Among distributions over \(K\) outcomes, the uniform one has the maximum entropy, \(\log K\); a one-hot distribution has the minimum, zero. Entropy is the right measure of uncertainty for LLM outputs too: the entropy of the next-token distribution is low after "The capital of France is" and high at the start of a story, and entropy-based signals are used for detecting uncertain generations and for deciding where to spend extra compute.

The operational meaning is Shannon's source coding theorem: you cannot losslessly encode symbols from \(p\) using fewer than \(H(p)\) bits per symbol on average, and you can get as close to it as you like. For \(p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18)\) over four symbols, \(H(p) = 1.75\) bits. A code giving the symbols lengths 1, 2, 3 and 3 bits (for example 0, 10, 110, 111, a Huffman code) averages exactly 1.75 bits, beating the naive 2 bits per symbol. The ideal code length for a symbol is its surprisal, \(-\log_2 p(x)\).

Entropy is a number of yes/no questions

\(H(p)\) is the average number of well-chosen yes/no questions needed to identify a draw from \(p\). For the distribution above: "Is it A?" (half the time, done in one question); "Is it B?"; "Is it C?". Average: 1.75 questions. The 3Blue1Brown Wordle video (Go deeper) builds a whole solver on choosing the guess with the most expected information.

Cross-entropy: the cost of using the wrong code

Suppose the data come from \(p\) but you encode them with a code designed for a model \(q\), so symbol \(x\) costs \(-\log q(x)\) bits. Your average cost is the cross-entropy:

\[ H(p, q) = -\sum_x p(x) \log q(x) . \]

For the source above and a model that assumes all four symbols are equally likely, \(H(p, q) = 2\) bits: you pay 0.25 bits per symbol for the model's ignorance.

This is exactly the classification loss, computed on top of a softmax. For one example with true class \(y\), the "true distribution" is one-hot on \(y\), so \(H(p, q) = -\log q(y)\): the negative log-probability the model gave the right answer. With logits \((2.0, 1.0, 0.1)\) and true class 0, softmax gives \(q(y) = 0.659\) and the loss is \(-\ln 0.659 = 0.417\) nats. Averaged over a dataset, this is the negative log-likelihood of the MLE page, and its gradient with respect to the logits is the beautifully simple \(\mathbf{q} - \mathbf{y}\): here \((-0.341, 0.242, 0.099)\), which the code checks by finite differences.

Why not train on accuracy, or MSE on probabilities? Accuracy is piecewise constant, so its gradient is zero almost everywhere. MSE on a sigmoid output has a gradient that vanishes when the model is confidently wrong (the sigmoid is flat there), so the worst mistakes learn slowest. Cross-entropy's gradient is largest exactly when the model is confidently wrong. It is also a strictly proper scoring rule: the expected score is optimised only by reporting your true belief, so it rewards calibrated probabilities, not just correct rankings (Gneiting and Raftery, 2007).

Perplexity, bits per token and bits per byte

Language-model losses are reported in several equivalent units:

  • Cross-entropy per token, in nats (what PyTorch prints).
  • Bits per token: divide by \(\ln 2\).
  • Perplexity: \(\exp(\text{loss in nats})\), the effective number of equally likely choices the model is hesitating between. A loss of 2.0 nats per token is 2.885 bits per token and a perplexity of 7.39: on average the model is as uncertain as if choosing uniformly among about 7 tokens, and it gives the true token a geometric-mean probability of 0.135.
  • Bits per byte (or per character): total bits divided by the number of bytes of raw text.

Per-token numbers are only comparable between models with the same tokeniser: a tokeniser with bigger tokens has fewer, harder predictions per sentence. Bits per byte normalises by the text itself, which is why it is used to compare models across tokenisers (see tokenisation and the language-modelling objective).

KL divergence: how different are two distributions?

The excess cost of coding \(p\) with \(q\)'s code is the Kullback–Leibler divergence:

\[ \operatorname{KL}(p \,\|\, q) = H(p, q) - H(p) = \sum_x p(x) \log \frac{p(x)}{q(x)} . \]

Its three key properties:

  1. \(\operatorname{KL}(p \,\|\, q) \ge 0\), with equality only when \(p = q\) (Gibbs' inequality, derived below). You can never beat the true distribution's code.
  2. It is not symmetric and not a distance. For \(p = (0.5, 0.25, 0.125, 0.125)\) and an overconfident model \(r = (0.8, 0.1, 0.05, 0.05)\): \(\operatorname{KL}(p \,\|\, r) = 0.322\) bits but \(\operatorname{KL}(r \,\|\, p) = 0.278\) bits.
  3. It is infinite if \(q(x) = 0\) anywhere \(p(x) > 0\). A model that rules out something that happens pays an infinite price, which is why models must never assign exactly zero probability (and why the smoothing of estimation matters).

Forward or reverse: which way round matters

Because KL is asymmetric, fitting a simple \(q\) to a complicated \(p\) gives different answers depending on direction, and different parts of AI use different directions.

  • Forward KL, \(\operatorname{KL}(p \,\|\, q)\), averages over \(p\). It is huge wherever \(p\) has mass and \(q\) does not, so the best \(q\) covers all of \(p\)'s modes, even at the cost of putting mass between them. Maximum likelihood minimises this direction (with \(p\) = data).
  • Reverse KL, \(\operatorname{KL}(q \,\|\, p)\), averages over \(q\). It is huge wherever \(q\) has mass and \(p\) does not, so the best \(q\) seeks one mode and stays inside it. Variational inference minimises this direction (with \(p\) = the posterior), and so does the KL penalty in RLHF.

Fitting one Gaussian to an even mixture of \(\mathcal{N}(-2.5, 0.7^2)\) and \(\mathcal{N}(2.5, 0.7^2)\) by grid search: forward KL picks \(\mathcal{N}(0, 2.6^2)\), matching the mixture's mean and variance and centred where the mixture has almost no mass; reverse KL picks \(\mathcal{N}(-2.5, 0.7^2)\), one component exactly, at a cost of \(\ln 2 = 0.693\) nats (it ignores half the mass).

p: two modes (shaded)forward KL(p‖q): N(0, 2.6²)reverse KL(q‖p): N(−2.5, 0.7²)0−2.52.5
Fitting one Gaussian q to a two-mode p. Forward KL (what maximum likelihood minimises) punishes q for missing any of p's mass, so q stretches to cover both modes and puts its peak where p has almost nothing. Reverse KL (what variational inference minimises) punishes q for putting mass where p has none, so q locks onto one mode (drawn at half height to fit). Numbers from the grid search in Build it.

This explains real behaviour. A language model trained by MLE (forward KL) spreads probability over every continuation seen in the data, including bad ones, so unfiltered sampling wanders into the low-quality tail and decoding methods cut it off (Holtzman et al., 2019). Huszár (2015) discusses how the choice of divergence shapes generative models more generally.

Where KL divergence appears in modern AI

Where Which KL What it does
Pre-training / supervised learning \(\operatorname{KL}(p_\text{data} \,\|\, q_\theta)\) Cross-entropy minus a constant: MLE
Label smoothing (Szegedy et al.) CE against a target mixed with uniform Adds a pull towards uniform; discourages over-confident logits
Knowledge distillation (Hinton et al.) \(\operatorname{KL}(p_\text{teacher}^{T} \,\|\, q_\text{student}^{T})\) at temperature \(T\) Transfers the teacher's "dark knowledge" about wrong classes
VAEs (Kingma and Welling) \(\operatorname{KL}(q(\mathbf{z} \mid \mathbf{x}) \,\|\, \mathcal{N}(\mathbf{0}, I))\) Keeps the latent code close to the prior; part of the ELBO
RLHF (Stiennon et al.) \(\operatorname{KL}(\pi_\theta \,\|\, \pi_\text{ref})\) penalty Stops the policy drifting from the SFT model to exploit the reward model
DPO (Rafailov et al.) Same KL-regularised objective, solved in closed form Turns the optimal policy into a classification loss on preference pairs
PPO / TRPO (Schulman et al.) KL between old and new policy (clipped surrogate in PPO) A trust region: small, safe policy updates

The RLHF objective deserves a line of maths, because DPO is built on it. Maximise \(\mathbb{E}_{y \sim \pi}[r(x, y)] - \beta\,\operatorname{KL}(\pi \,\|\, \pi_\text{ref})\) over policies \(\pi\). The maximiser is \(\pi^*(y \mid x) \propto \pi_\text{ref}(y \mid x)\,\exp(r(x, y)/\beta)\): the reference policy, reweighted by exponentiated reward. Rearranged, the reward is \(\beta \log \frac{\pi^*}{\pi_\text{ref}}\) plus a term that cancels in pairwise comparisons, which is the substitution DPO makes (see DPO and friends).

Mutual information: what one variable tells you about another

The mutual information between \(X\) and \(Y\) is how much knowing one reduces uncertainty about the other:

\[ I(X; Y) = H(X) - H(X \mid Y) = \operatorname{KL}\big(p(x, y) \,\|\, p(x)\,p(y)\big). \]

It is symmetric, non-negative, and zero exactly when \(X\) and \(Y\) are independent, so unlike correlation it detects any kind of dependence. Two results make it useful.

  • Data processing inequality. If \(X \to Y \to Z\) is a chain (Z computed from Y only), then \(I(X; Z) \le I(X; Y)\): no processing of \(Y\) can create information about \(X\). A deep network's layers can only lose information about the input; the information bottleneck view asks which information they should lose (everything irrelevant to the label).
  • Contrastive bounds. Mutual information is hard to estimate in high dimensions, but the InfoNCE loss of van den Oord et al. (2018), a softmax cross-entropy that picks the true pair out of \(N\) candidates, gives the lower bound \(I(X; Y) \ge \log N - \mathcal{L}_\text{InfoNCE}\). CLIP, SimCLR and most embedding models are trained with losses of this form (see vision transformers and CLIP and embeddings). Note the bound can never exceed \(\log N\), one reason contrastive learning wants large batches.

Compression is prediction

An arithmetic coder driven by a model \(q\) encodes a sequence \(x_{1:n}\) in about \(-\log_2 q(x_{1:n}) = \sum_t -\log_2 q(x_t \mid x_{<t})\) bits, within a couple of bits of that total. That sum is the model's cross-entropy loss on the sequence, in bits. So a better language model is a better compressor, exactly, and a training loss curve is a compression ratio curve. Delétang et al. (2023) made this concrete: Chinchilla 70B, trained mostly on text, compressed ImageNet patches to 43.4% and LibriSpeech audio to 16.4% of their raw size, beating PNG (58.5%) and FLAC (30.3%) at their own domains (ignoring the size of the model itself, which is the catch).

Typicality: why the most likely sequence looks wrong

For \(n\) i.i.d. draws from \(p\), almost all the probability sits on a "typical set" of about \(2^{nH(p)}\) sequences, each with probability close to \(2^{-nH(p)}\) (the asymptotic equipartition property). The single most likely sequence is usually not typical. For a coin with \(p(\text{heads}) = 0.6\), the most likely sequence of 100 flips is all heads, yet you will essentially never see it; typical sequences have about 60 heads. The same happens in language: greedy and beam search chase the most probable continuation and produce repetitive, atypical text, while sampling produces text whose per-token surprisal matches the data's entropy (Dieleman's essay on typicality and decoding).

First principles

Why is entropy \(-\sum p \log p\) and nothing else? Shannon (1948, Theorem 2) asked for a measure \(H(p_1, \dots, p_n)\) of uncertainty with three properties: it is continuous in the \(p_i\); for uniform distributions it increases with \(n\) (more equally likely options, more uncertainty); and it is consistent under grouping: if a choice is broken into two successive choices, the total uncertainty is the first choice's uncertainty plus the weighted uncertainty of the second. He proved the only function satisfying all three is \(H = -K \sum_i p_i \log p_i\), with \(K\) fixing the unit. The grouping rule is the chain rule of entropy, \(H(X, Y) = H(X) + H(Y \mid X)\), the information-theoretic twin of the chain rule of probability.

Why is the log loss the right loss? Among scoring rules that depend only on the probability the forecaster gave the outcome that actually happened (local rules), the logarithmic score is the only strictly proper one when there are more than two outcomes. Every other "honest" scoring rule (Brier, spherical) looks at the probabilities of outcomes that did not happen. Log loss is also the only one with an additive decomposition over a sequence via the chain rule, which is what lets you train on tokens one at a time.

Why is KL non-negative, and what does that buy? Because \(-\log\) is convex, Jensen's inequality gives \(\mathbb{E}_p[-\log(q/p)] \ge -\log \mathbb{E}_p[q/p] = -\log 1 = 0\). This one inequality is behind the ELBO (the gap to \(\log p(D)\) is a KL, hence non-negative), the EM algorithm's monotone improvement, the data processing inequality, and the fact that no model can have lower cross-entropy than the data's own entropy. That last point sets a floor on LLM loss: scaling laws fit an irreducible term (see scaling laws) that is, roughly, the entropy of natural text under the tokenisation.

Maximum entropy, again. The distributions in the catalogue are the maximum-entropy distributions under simple constraints. "Assume nothing beyond what you know" and "use the exponential family" are the same instruction, and softmax classifiers are the maximum-entropy models whose expected features match the data.

History

From telegraph lines to language models

Ralph Hartley (1928) proposed measuring information by the logarithm of the number of possible messages. Claude Shannon's 1948 A Mathematical Theory of Communication defined entropy, proved the source and channel coding theorems, and generated English-like text from letter and word \(n\)-gram statistics. In 1951 he estimated the entropy of printed English by having people guess the next letter, a human language model. Solomon Kullback and Richard Leibler defined their divergence in 1951 as a measure of discrimination information. David Huffman found optimal prefix codes as a student in 1952; arithmetic coding was developed in the 1970s. Jaynes (1957) made maximum entropy a principle of inference. In machine learning, cross-entropy displaced squared error as the standard classification loss during the neural-network revival, and "perplexity", already standard in speech recognition from the late 1970s, became the headline metric of language modelling.

The maths

Definitions (discrete; replace sums by integrals for densities)

  • Entropy \(H(X) = -\sum_x p(x)\log p(x)\); joint entropy \(H(X, Y) = -\sum_{x,y} p(x,y)\log p(x,y)\).
  • Conditional entropy \(H(Y \mid X) = -\sum_{x,y} p(x,y)\log p(y \mid x)\).
  • Chain rule \(H(X, Y) = H(X) + H(Y \mid X)\); for sequences \(H(X_{1:n}) = \sum_t H(X_t \mid X_{<t})\).
  • Cross-entropy \(H(p, q) = -\sum_x p(x)\log q(x)\); KL \(\operatorname{KL}(p\,\|\,q) = \sum_x p(x)\log\frac{p(x)}{q(x)} = H(p,q) - H(p)\).
  • Mutual information \(I(X;Y) = H(X) - H(X\mid Y) = H(X) + H(Y) - H(X,Y) = \operatorname{KL}(p_{XY}\,\|\,p_X p_Y)\).
  • Bounds: \(0 \le H(X) \le \log K\) for \(K\) outcomes; \(H(X \mid Y) \le H(X)\) (conditioning never increases entropy on average).
Derivation: Gibbs' inequality, KL ≥ 0

Let \(S = \{x : p(x) > 0\}\). Using \(\log t \le t - 1\) (with equality only at \(t = 1\)):

\[ -\operatorname{KL}(p\,\|\,q) = \sum_{x \in S} p(x)\log\frac{q(x)}{p(x)} \le \sum_{x \in S} p(x)\Big(\frac{q(x)}{p(x)} - 1\Big) = \sum_{x \in S} q(x) - 1 \le 0 . \]

Equality requires \(q(x) = p(x)\) on \(S\) and \(q\) to put no mass outside \(S\), i.e. \(q = p\). Corollaries: \(H(p) \le H(p, q)\) for every \(q\); \(I(X;Y) \ge 0\); and \(H(p) \le \log K\) (take \(q\) uniform: \(H(p, q) = \log K\)).

Derivation: the softmax cross-entropy gradient

Logits \(\mathbf{z} \in \mathbb{R}^K\), \(q_k = e^{z_k}/\sum_j e^{z_j}\), true class \(y\).

\[ \mathcal{L} = -\log q_y = -z_y + \log\sum_j e^{z_j}, \qquad \frac{\partial \mathcal{L}}{\partial z_k} = -\mathbf{1}[k = y] + \frac{e^{z_k}}{\sum_j e^{z_j}} = q_k - y_k . \]

For a batch of \(B\) examples with logits \(Z \in \mathbb{R}^{B \times K}\) and one-hot labels \(Y\), the gradient of the mean loss is \((Q - Y)/B\). Every entry lies in \([-1, 1]\), so the loss never produces exploding gradients at the output layer, and the gradient is zero only when the prediction equals the label.

Continuous variables and Gaussians

Differential entropy \(h(p) = -\int p(x)\log p(x)\,dx\) can be negative (a narrow density has \(p > 1\)). For \(\mathcal{N}(\mu, \sigma^2)\), \(h = \tfrac12\log(2\pi e\sigma^2)\); for a \(d\)-dimensional Gaussian, \(h = \tfrac12\log\big((2\pi e)^d \lvert\Sigma\rvert\big)\). KL, unlike differential entropy, stays non-negative and invariant to reparameterisation. Between univariate Gaussians:

\[ \operatorname{KL}\big(\mathcal{N}(\mu_1, \sigma_1^2)\,\|\,\mathcal{N}(\mu_2, \sigma_2^2)\big) = \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac12 . \]

With \(\mu_2 = 0\), \(\sigma_2 = 1\) this is the VAE's KL term per latent dimension, \(\tfrac12(\mu^2 + \sigma^2 - 1 - \log\sigma^2)\).

Derivation: the KL-regularised policy objective (the basis of DPO)

For a fixed prompt, maximise over distributions \(\pi(y)\):

\[ J(\pi) = \sum_y \pi(y)\,r(y) - \beta \sum_y \pi(y)\log\frac{\pi(y)}{\pi_\text{ref}(y)} . \]

Define \(\pi^*(y) = \pi_\text{ref}(y)\,e^{r(y)/\beta} / Z\) with \(Z = \sum_y \pi_\text{ref}(y)\,e^{r(y)/\beta}\). Substituting \(r(y) = \beta\log\frac{\pi^*(y)}{\pi_\text{ref}(y)} + \beta\log Z\):

\[ J(\pi) = \beta\log Z - \beta\,\operatorname{KL}(\pi\,\|\,\pi^*) , \]

which is maximised, by Gibbs' inequality, at \(\pi = \pi^*\). The reward is recoverable from the optimal policy up to \(\beta\log Z\), which cancels when two responses to the same prompt are compared: that cancellation is DPO.

Build it

The basic quantities, the softmax cross-entropy gradient checked numerically, and the three ways of reading a language-model loss:

import numpy as np

H  = lambda p: -np.sum(p[p > 0] * np.log2(p[p > 0]))             # entropy, bits
CE = lambda p, q: -np.sum(p[p > 0] * np.log2(q[p > 0]))          # cross-entropy, bits
KL = lambda p, q: CE(p, q) - H(p)

p = np.array([0.5, 0.25, 0.125, 0.125])     # true source
q = np.array([0.25, 0.25, 0.25, 0.25])      # a model that assumes uniform
r = np.array([0.8, 0.1, 0.05, 0.05])        # an overconfident model
print(f"H(p) {H(p):.3f}  H(p,q) {CE(p, q):.3f}  KL(p||q) {KL(p, q):.3f}  KL(q||p) {KL(q, p):.3f} bits")
print(f"KL(p||r) {KL(p, r):.3f}  KL(r||p) {KL(r, p):.3f} bits  (not symmetric)")
print("optimal code lengths -log2 p:", -np.log2(p), " average:", (p * -np.log2(p)).sum())

# Softmax cross-entropy on logits, and its gradient (p - y) checked by finite differences
z = np.array([2.0, 1.0, 0.1]); y = 0
def loss(z):
    z = z - z.max()
    return -(z[y] - np.log(np.exp(z).sum()))                  # nats
probs = np.exp(z - z.max()); probs /= probs.sum()
grad = probs - np.eye(3)[y]
fd = np.array([(loss(z + 1e-6 * e) - loss(z - 1e-6 * e)) / 2e-6 for e in np.eye(3)])
print(f"loss {loss(z):.4f} nats = {loss(z) / np.log(2):.4f} bits;  perplexity {np.exp(loss(z)):.3f}")
print("analytic grad", grad.round(4), " finite diff", fd.round(4))

# A language model's loss, read three ways
L = 2.0                                                       # nats per token
print(f"loss {L} nats/token -> {L / np.log(2):.3f} bits/token, perplexity {np.exp(L):.2f}, "
      f"geometric-mean p(true token) {np.exp(-L):.3f}")
H(p) 1.750  H(p,q) 2.000  KL(p||q) 0.250  KL(q||p) 0.250 bits
KL(p||r) 0.322  KL(r||p) 0.278 bits  (not symmetric)
optimal code lengths -log2 p: [1. 2. 3. 3.]  average: 1.75
loss 0.4170 nats = 0.6016 bits;  perplexity 1.517
analytic grad [-0.341   0.2424  0.0986]  finite diff [-0.341   0.2424  0.0986]
loss 2.0 nats/token -> 2.885 bits/token, perplexity 7.39, geometric-mean p(true token) 0.135

(The first pair being equal is a coincidence of these particular numbers; the second pair shows the general, asymmetric case.)

Forward versus reverse KL, by brute-force search over one Gaussian:

import numpy as np
# Fit one Gaussian q to a bimodal mixture p by forward KL(p||q) and by reverse KL(q||p)
x = np.linspace(-8, 8, 4001); dx = x[1] - x[0]
gauss = lambda x, m, s: np.exp(-(x - m)**2 / (2 * s * s)) / (s * np.sqrt(2 * np.pi))
p = 0.5 * gauss(x, -2.5, 0.7) + 0.5 * gauss(x, 2.5, 0.7)
def kl(a, b):
    m = a > 1e-300
    return np.sum(a[m] * (np.log(a[m]) - np.log(b[m] + 1e-300))) * dx
best = {"forward": (np.inf,), "reverse": (np.inf,)}
for mu in np.linspace(-4, 4, 161):
    for sd in np.linspace(0.3, 4, 75):
        q = gauss(x, mu, sd)
        for name, val in (("forward", kl(p, q)), ("reverse", kl(q, p))):
            if val < best[name][0]:
                best[name] = (val, mu, sd)
for name, (val, mu, sd) in best.items():
    print(f"{name:>7} KL: best q = N({mu:+.2f}, {sd:.2f}^2), KL = {val:.3f} nats")
print(f"mixture mean 0, mixture sd {np.sqrt(np.sum(p * x * x) * dx):.2f}")
forward KL: best q = N(+0.00, 2.60^2), KL = 0.618 nats
reverse KL: best q = N(-2.50, 0.70^2), KL = 0.693 nats
mixture mean 0, mixture sd 2.60

Things to try

  • Compute the entropy of the next-token distribution of any open model over a paragraph (or of your bigram model). Where is it highest? Does high entropy predict where the model makes mistakes?
  • Move the two mixture components closer together (±1.0). At what separation does the reverse-KL fit jump from one mode to straddling both?
  • Implement label smoothing: replace the one-hot target by \((1 - \varepsilon)\mathbf{y} + \varepsilon/K\). Show that the loss equals \((1 - \varepsilon)\,\text{CE}(\mathbf{y}, \mathbf{q}) + \varepsilon\,\text{CE}(\text{uniform}, \mathbf{q})\) and that the optimal logits are now finite.
  • Compress a text file with gzip and compute its bits per byte. Then compute your bigram model's cross-entropy per byte on the same text. Which is the better compressor, and what would change with a real LLM?

Common misconceptions

  • "Cross-entropy and KL are different losses." For a fixed data distribution they differ by the constant \(H(p)\); their gradients with respect to the model are identical. They differ only when \(p\) also depends on parameters (as in distillation from a moving teacher, or the VAE's KL term).
  • "Lower perplexity always means a better model." Only on the same test set with the same tokeniser, and only as a language model. Perplexity says little about instruction following or truthfulness, and post-training deliberately moves a model's distribution away from raw web text, so web-text perplexity is a poor guide to a chat model's quality.
  • "KL is a distance." It is asymmetric and fails the triangle inequality. The Jensen–Shannon divergence (average KL to the midpoint) is symmetric and its square root is a metric; the Wasserstein distance is another alternative.
  • "Entropy measures meaning." Shannon was explicit that it does not: it measures unpredictability. A random string has maximal entropy and no meaning.

Check yourself

A model assigns probability 0.25 to the correct next token at every position. What are its loss in nats and bits, and its perplexity?

\(-\ln 0.25 = 1.386\) nats \(= 2\) bits per token; perplexity \(e^{1.386} = 4\). Perplexity equals the inverse of the (geometric-mean) probability of the correct token.

Why is the cross-entropy gradient with respect to the logits bounded, and why does that matter?

It is \(\mathbf{q} - \mathbf{y}\), whose entries lie in \([-1, 1]\). The output layer cannot produce an exploding gradient, however wrong the model is. (The loss itself can be huge, which is a numerical issue handled by computing it from logits with log-sum-exp; see numerical computing.)

Show that minimising expected cross-entropy H(p_data, q_θ) over θ is the same as maximum likelihood.

\(H(p_\text{data}, q_\theta) = -\mathbb{E}_{x \sim p_\text{data}}[\log q_\theta(x)]\). Replacing the expectation by the empirical average over a dataset gives \(-\frac1n\sum_i \log q_\theta(x_i)\), the negative average log-likelihood. Its minimiser is the MLE. Since \(H(p, q) = H(p) + \operatorname{KL}(p\,\|\,q)\) and \(H(p)\) does not depend on \(\theta\), this is also forward-KL minimisation.

In RLHF, why is the KL penalty taken as KL(π ‖ π_ref) and what goes wrong with β → 0?

Expectations over \(\pi\) can be estimated from the policy's own samples, which is what RL produces, so the reverse direction is the practical one; it also lets the policy concentrate on good responses inside the reference's support. With \(\beta \to 0\) nothing holds the policy near the reference, and it exploits imperfections of the reward model (reward hacking), producing text the reward model scores highly but humans do not.

Compute I(X; Y) for the joint table p(0,0) = 0.4, p(0,1) = 0.1, p(1,0) = 0.1, p(1,1) = 0.4, in bits.

Marginals are uniform, so \(H(X) = H(Y) = 1\) bit. \(H(X, Y) = -(2 \times 0.4\log_2 0.4 + 2 \times 0.1\log_2 0.1) = 1.722\) bits. \(I = 1 + 1 - 1.722 = 0.278\) bits. Knowing \(Y\) removes about 28% of the uncertainty about \(X\).

Hard: InfoNCE with batch size N can certify at most log N nats of mutual information. Why, and what does it imply for contrastive pre-training?

The InfoNCE loss is a cross-entropy over \(N\) candidates, so it is at least 0, and the bound \(I \ge \log N - \mathcal{L}\) is therefore at most \(\log N\). With \(N = 32{,}768\) (CLIP's batch size) the bound tops out at about 10.4 nats. Larger batches give a looser ceiling and more, harder negatives, one reason contrastive methods scale with batch size; the bound's tightness, not the true MI, is what training optimises.

Go deeper

Papers

Videos and lectures

Articles

  • Visual Information Theory — Chris Olah, 2015. The best visual explanation of entropy, cross-entropy and KL as code lengths.
  • Musings on typicality — Sander Dieleman, 2020. Why the mode is not typical, and what it means for decoding.

Books

Where this leads