AI from scratch · Probability 5 · Stage 3: classic ML and judging models

Information: entropy, cross-entropy and KL divergence

Chapter 5 measured a wrong belief by its surprise, \(-\log p\), and called the average the cross-entropy loss. This lesson asks what that number really is. It turns out to be a count of bits: how many yes/no answers it takes to pin down what happened. That one idea explains how far a file can be compressed, why the training loss can never reach zero on real data, what "extra bits" a wrong model costs, how a decision tree picks its question, and why fine-tuning keeps a leash on a chatbot.

1. Entropy: the average surprise

An outcome with probability \(p\) carries \(-\log_2 p\) bits of surprise (chapter 5): a coin flip 1 bit, one of 4 equal outcomes 2 bits, a 1-in-1,000 event about 10. Entropy is the surprise you should expect on average, before you know what will happen: each outcome's surprise weighted by how often it occurs.

\[ H(p) = -\sum_i p_i \log_2 p_i \quad \text{bits} \]

Predict first: tomorrow is sun, clouds, rain or storm, all four equally likely. How many bits is the entropy?

Each outcome has \(p = 1/4\) and surprise \(\log_2 4 = 2\) bits, so the average is 2. That's the same as two yes/no questions: "sun or clouds?", then one more.

Now drag the bars: they are your forecast for tomorrow, always adding up to 1. Watch the entropy. Try making one outcome certain, then all four equal.

The last line of the readout, \(2^H\), turns entropy back into a count: the forecast is as uncertain as a choice among that many equally likely outcomes. For a language model the same number is called perplexity: "perplexity 20" means it's as unsure about the next word as if it were choosing among 20 equally likely words.

Entropy is how uncertain a distribution is, measured as the average number of yes/no answers needed to learn what happened: 0 when you're sure, largest when everything is equally likely.

Why a logarithm, and why a minus sign?
  1. Surprise should depend only on how likely something was, so it's some function \(s(p)\).
  2. A certain event isn't surprising, \(s(1) = 0\), and rarer events are more surprising: \(s\) grows as \(p\) shrinks.
  3. Two independent events, say a coin and a die, happen together with probability \(p \cdot q\). Their surprise should simply add: \(s(p\,q) = s(p) + s(q)\).
  4. The function that turns products into sums is the logarithm (chapter 5 used exactly this to stop probabilities underflowing). So \(s(p) = -\log p\): the minus sign makes it positive, since \(\log p < 0\) for \(p < 1\).
  5. The base only picks the unit: \(\log_2\) gives bits, \(\ln\) gives "nats" (PyTorch's loss is in nats; divide by \(\ln 2 \approx 0.693\) for bits).
Where it breaks: what entropy can't see

2. The limit of compression

Play twenty questions with the "½ ¼ ⅛ ⅛" forecast. Ask "sun?" first: half the time you're done after one question. If not, "clouds?": done after two. Otherwise "rain?" settles it after three. On average that's \(\tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75\) questions, and the widget says the entropy is exactly 1.75 bits. A good strategy asks about likely outcomes first, so they get short answers. That's a code: sun = 1, clouds = 01, rain = 001, storm = 000. Shannon proved that no code can average fewer bits than the entropy, and good ones come within a bit of it (more on why in section 3).

So how many bits does a subway station name need? Count characters in the 379 NYC station names:

Every bit of context lowers the entropy: after a "q" the next letter is almost surely "u", and after " s" a "t" is likely ("St"). zlib finds repeated chunks like " St\n" and lands between the two. A language model is this idea taken all the way: it predicts each character or word from everything before it, and its cross-entropy in bits is the size it could compress the text to. Better prediction and better compression are the same thing.

Entropy is the floor for compression: no code can average fewer bits per symbol, and more context lowers the floor. Predicting well and compressing well are one skill.

3. Cross-entropy and KL: the price of a wrong belief

Suppose the truth is \(p\), but you believe \(q\) and build your code (or your predictions) from \(q\). Each outcome costs you \(-\log_2 q_i\) bits, and it happens with frequency \(p_i\), so on average you pay the cross-entropy. The part above the unavoidable \(H(p)\) is the KL divergence, the extra bits your wrong belief costs:

\[ H(p, q) = -\sum_i p_i \log_2 q_i \qquad D_{\mathrm{KL}}(p \,\Vert\, q) = H(p, q) - H(p) = \sum_i p_i \log_2 \frac{p_i}{q_i} \]

The double bar here isn't a length (chapter 1's \(\lVert v \rVert\)): it only separates the two distributions. Read \(D_{\mathrm{KL}}(p \Vert q)\) as "the KL divergence of \(q\) from \(p\)"; the order matters (section 4).

Gray bars are the truth (the city's real odds); drag the blue bars, the forecaster's belief. Try to bring the extra bits to zero. Then try the forecaster who's sure a storm can't happen.

truth \(p\) belief \(q\) (drag)

Two things to notice. The extra bits never go below zero: no belief beats the truth. And look at the storm days under "storms never happen": that forecaster saves a little on ordinary days but pays almost 10 bits each time a storm comes, against 4.3 for the truth. Drag the storm bar toward zero and that cost grows without limit: calling something nearly impossible is the most expensive mistake there is.

KL divergence is the extra bits you pay for believing \(q\) when the truth is \(p\). It's never negative, and it's zero only when \(q = p\). Training a classifier with cross-entropy is shrinking exactly this gap.

Why can't the extra bits go below zero?
  1. Work in natural logs (it only rescales). The curve \(\ln x\) bends down, so it lies below its tangent line at \(x = 1\), which is \(x - 1\) (calculus 1: slope \(1/x = 1\) there). So \(\ln x \le x - 1\), with equality only at \(x = 1\).
  2. Flip the KL around: \(-D_{\mathrm{KL}} = \sum_i p_i \ln \frac{q_i}{p_i}\).
  3. Use step 1 on each term: \(\sum_i p_i \ln \frac{q_i}{p_i} \le \sum_i p_i \left(\frac{q_i}{p_i} - 1\right) = \sum_i q_i - \sum_i p_i = 1 - 1 = 0\).
  4. So \(D_{\mathrm{KL}} \ge 0\), with equality only when every \(q_i / p_i = 1\), that is \(q = p\).

Two results fall out. With \(q\) uniform over \(n\) outcomes, \(D_{\mathrm{KL}} = \log_2 n - H(p) \ge 0\): no distribution has more entropy than the uniform one. And compression: a code with lengths \(\ell_i\) behaves like a belief \(q_i = 2^{-\ell_i}\), so its average length is a cross-entropy, at least \(H(p)\). That's Shannon's floor from section 2.

Back to the station names, with a model that learned how common each character is from the second half of the alphabetical list (from about "E 149 St" to "Zerega Av") and is used on the first half:

Where it breaks: zeros, and the wrong direction

Estimate: an untrained language model spreads its belief evenly over a vocabulary of 50,000 tokens. How many bits is its cross-entropy per token, whatever the text? (One decimal.)

Every token gets \(q = 1/50{,}000\), so each costs \(\log_2 50{,}000 \approx 15.6\) bits (\(2^{15.6} \approx 50{,}000\)), its perplexity is 50,000, and its loss in PyTorch's nats is \(\ln 50{,}000 \approx 10.8\). A training run that starts far above 10.8 has a bug; the loss should start right there and fall.

4. Two directions: covering or choosing

Fit one bell curve \(q\) to a truth \(p\) with two humps. There's no perfect fit, so the direction of the KL decides which mistake you prefer. Forward \(D_{\mathrm{KL}}(p \Vert q)\) weighs by the truth: wherever the data is, \(q\) must not be near zero, so it stretches to cover both humps. Reverse \(D_{\mathrm{KL}}(q \Vert p)\) weighs by the model: wherever \(q\) puts weight, the data had better be there, so it chooses one hump and fits it snugly.

Maximum likelihood (probability 3) is the forward direction: it makes models that hedge and cover everything the data does, which is why a model trained only that way can produce blurry averages when the answer has two distinct options. The reverse direction appears when a model's own outputs are being judged, as in fine-tuning a chatbot with a KL leash (section 6) and in variational autoencoders.

Forward KL makes a model cover everything the data does (and blur between options); reverse KL makes it commit to what it does well (and ignore the rest).

Why does the forward-KL fit sit in the empty middle, where the truth has almost no weight?

Each term is \(p_i \log(p_i/q_i)\): when \(p_i\) is near 0, the term is near 0 whatever \(q\) does there. The only expensive mistake is a small \(q\) where \(p\) is big, so the bell stretches over both humps and wastes weight in the middle.

5. Information gain: which question tells you most?

A question is worth the entropy it removes. Before asking, the answer you care about \(Y\) has entropy \(H(Y)\); after learning \(X\) it has \(H(Y \mid X)\), the average entropy left in each group. The difference is the information gain (also called mutual information):

\[ I(X; Y) = H(Y) - H(Y \mid X) \]

A decision tree (chapter 13, coming up next) grows by asking, at each step, the yes/no question with the biggest information gain. Here's that search on the wine data (3 kinds of wine, 13 measurements):

A good question is one whose answer removes the most entropy. Trees choose their splits this way, and "how many bits does feature X tell me about Y?" is a way to rank features.

Where it breaks: questions that are too good

A column with a different value in every row (a customer ID, a timestamp) splits the data into groups of one, each with entropy 0, so its information gain is the maximum possible, and it predicts nothing on new rows. Information gain rewards questions with many answers. Trees guard against it by limiting depth and leaf size, or by dividing the gain by the entropy of the question itself (the "gain ratio"). It's also the information-theory face of leakage (stage 3): a feature that tells you too much is a warning sign, not a gift.

6. Where AI uses it

WhereWhat's being measured
Training lossCross-entropy between the data and the model. Since the data's own entropy is fixed, minimizing it is minimizing \(D_{\mathrm{KL}}(\text{data} \Vert \text{model})\), and that's maximum likelihood (probability 3) in other words. The loss can't go below the data's entropy: real labels have some noise, and text has real uncertainty.
Perplexity\(2^{\text{cross-entropy in bits}}\): how many equally likely choices the model is torn between, per token.
DistillationA small student model is trained to match a big teacher's whole probability distribution, softened with temperature (chapter 5), by minimizing the KL from teacher to student. "Fairly sure it's a 7, could be a 1" teaches more than the bare label "7".
Fine-tuning with a leashWhen a chatbot is tuned to maximize a reward (RLHF, stage 6), a penalty \(\beta\, D_{\mathrm{KL}}(\text{new} \Vert \text{original})\) keeps it from drifting into strange text that games the reward.
Trees and feature rankingInformation gain picks splits; mutual information ranks features.

A language model's cross-entropy on held-out text is 3 bits per token. What's its perplexity?

\(2^3 = 8\): on average it's as unsure as a choice among 8 equally likely tokens, down from 50,000 before training.

7. What to carry forward

All lessons: AI from scratch. Claude Shannon's 1948 paper "A Mathematical Theory of Communication" started all of this and is still readable; Chris Olah's "Visual Information Theory" is a gentle illustrated companion.

Last updated