Skip to content

Probability and Statistics

Information theory: entropy and cross-entropy

Measuring surprise and the loss that trains LLMs

When a friend says "the sun rose this morning," you learn nothing - you already knew it. When they say "it snowed in the desert," you sit up. Information theory turns that gut feeling into arithmetic: the surprise of an event is , measured in bits. Average that surprise over a whole distribution and you get entropy. Average it while using the wrong probabilities and you get cross-entropy - which, it turns out, is the exact number an LLM is trained to push down, token after token.

The core idea

A rare event carries a lot of information; a certain event carries none. The one function that maps "probability" to "surprise" while making independent surprises simply add up is the logarithm. Pick base 2 and the unit is the bit: a fair coin flip () is exactly bit of surprise. Everything else in this lesson is just averaging that one quantity.

Surprise, measured in bits

The information content (or "surprise") of an outcome with probability is

The minus sign is only there because probabilities are , so their logs are negative - surprise should be a positive number. Two properties make this the only sensible choice. First, it is monotone: smaller means larger surprise, and a sure thing () has surprise . Second, it is additive for independent events - the surprise of two coin flips is bits, not because we multiplied but because turns the product of probabilities into a sum of surprises.

Now average that surprise over the whole distribution, weighting each outcome by how often it actually happens. That average is Shannon entropy:

Entropy is the irreducible uncertainty of a source: the average number of yes/no questions you must ask to pin down its outcome, and - by Shannon's coding theorem - the shortest average code length in bits that any scheme can achieve. A predictable source (one likely outcome) has low entropy; a uniform source has the most, bits for equally likely options.

Cross-entropy and KL: paying for a wrong map

Here is the twist that matters for machine learning. Suppose reality follows a distribution , but you build your code - your model - as if the distribution were . You still get charged the real surprise every time occurs, but occurs at the true rate . Your average bill is cross-entropy:

It is the average surprise of the truth, scored with the model's probabilities. Cross-entropy is never smaller than the true entropy, and the gap between them has a name - the Kullback-Leibler divergence, the number of extra bits you waste by using instead of :

Why the floor is H(p), and why it is a floor

Because (Gibbs' inequality), cross-entropy decomposes as . The floor is fixed by reality and cannot be removed by any model. The penalty is entirely the model's fault, and it hits - meaning - only when exactly. So minimizing cross-entropy is the same as minimizing KL: driving the model's guess toward the truth.

Drag the model's guesses

Below is a miniature language model. The prompt is "The cat sat on the ___" and the vocabulary has four tokens. The dashed ticks are the true next-token distribution (what the corpus actually does); the solid bars are the model's guess , which you can drag up and down. As you make resemble , the cross-entropy loss slides toward its floor . Starve the true winner of probability - make the model confident and wrong - and watch the loss bolt toward infinity. Hit "Draw the actual token" to sample from reality and see the surprise you paid on that one draw.

Next-token predictor drag the bars - watch the loss react
q - model's guess (drag me)p - the true distribution (dashed)

Bars start uniform (1/4 each). Drag one up - the others shrink to keep the guess a valid distribution summing to 1.

Cross-entropy loss - 0.46 extra bits above the floor
floor H(p)
Entropy H(p) - floor1.54 bits
Cross-entropy H(p,q) - loss2.00 bits
KL(p||q) - wasted bits0.46 bits
Perplexity 2^H(p,q)4.00 choices

Why this is the language-model loss

During training the "true distribution" for a single position is dead simple: it's a one-hot spike on the token that actually came next - on the real word, on everything else. Plug that into cross-entropy and every term vanishes except one: . The loss for one token is the surprise of the correct token. Sum it over the corpus and you have the objective GPT minimizes. Its exponential, , converts the bits back into an intuitive "the model is as unsure as if it were guessing uniformly among this many words."

Cross-entropy, and the one-hot special case, in a few lines:

# p: the true distribution, q: the model's guess (both sum to 1)
import numpy as np

def cross_entropy(p, q):
    return -np.sum(p * np.log2(q))     # bits; use np.log for nats (frameworks' default)

# The LM case: the target is one-hot on the real next token.
loss = -np.log2(q[true_token])         # surprise of the actual token, in bits
ppl  = 2 ** loss                       # perplexity: the "effective number of choices"
Cross-entropy in NumPy; the LM case reduces to one term.

PyTorch's cross_entropy uses the natural log, so its numbers are in nats rather than bits - but the story is identical, and perplexity is just instead of . Base changes the unit, not the meaning.

Check yourself

Cross-entropy H(p,q) reaches its minimum value exactly when:

A model that is confident and wrong - near-zero q on the true token - makes the loss:

What extra quantity does cross-entropy add on top of entropy, and when does it vanish?

The decomposition is the single most important identity in this lesson. Try to state it, then check.

Lock it in

  • Surprise of an event is bits - rare events carry more information.
  • Entropy is the average surprise - the irreducible uncertainty of a source.
  • Cross-entropy is the average surprise when you score the truth with the wrong model.
  • KL divergence is the gap: the extra bits you waste. Minimizing cross-entropy is the same as minimizing KL.
  • The LLM training loss is cross-entropy over the vocabulary - surprise of the correct token, summed across the corpus.

Primary source

For the geometric intuition behind information, entropy, cross-entropy and KL divergence, read Christopher Olah's "Visual Information Theory" - it builds every formula here from pictures. For how cross-entropy sits inside a trained network, see 3Blue1Brown's Neural Networks series.

Closing the loop

This lesson closes a loop that has been open since the middle of the course. The cost function, language modeling, and the LLM training objective are all the same instruction: minimize cross-entropy - minimize the surprise, in bits, of the next token. And it ties straight back to maximum likelihood: minimizing cross-entropy against the data is maximizing the likelihood of that data.