Information theory, entropy, and cross-entropy
I am thinking of a number from 1 to 8, and you may ask yes-or-no questions. Halving the range each time ("is it 4 or less?"), you need exactly 3 questions, and . Now suppose you know I pick 1 half the time. Asking "is it 1?" first wins immediately half the time, and on average you need fewer questions. The more predictable the source, the fewer questions it takes.
That observation, made precise by Claude Shannon in 1948, is information theory. It is exactly the right language for machine learning. The cross-entropy loss that trains every classifier and every language model is an average number of questions. The KL divergence that keeps an RLHF policy close to its starting point is the extra questions you pay for using the wrong distribution. Perplexity, the headline number of language modeling, is the effective number of choices the model is torn between. This section builds all of them from one idea, surprise.
Surprise and entropy
How surprised should you be when an event of probability happens? Three properties pin down the answer. A certain event () should carry no surprise. Rarer events should be more surprising. And the surprises of two independent events should add, so that seeing two unrelated things together is exactly as surprising as seeing each in turn. The only functions with these properties are multiples of , so we define the surprise (or information content) of an outcome as
With the unit is the bit, and with the natural log it is the nat ( bits). Machine learning code uses nats, since np.log is natural, while papers about compression and tokenizers often report bits.
The entropy of a distribution is its average surprise,
with the convention (impossible outcomes contribute nothing). In plain words, entropy measures how unpredictable a source is, the average number of yes-or-no questions (in bits) needed to pin down one draw.
A few values to anchor intuition. A fair coin has bit. A coin that lands heads 90% of the time has bits, less than half as unpredictable. A fair six-sided die has bits. And in general a uniform distribution over outcomes has , which is the largest entropy any distribution on outcomes can have (we prove it below). For continuous variables with a given mean and variance, the maximum-entropy distribution is the Gaussian, one reason it is the default assumption in §0.4.
Entropy is the best possible average code length
Shannon's source coding theorem makes the "questions" picture exact. Any lossless code for draws from needs at least bits per draw on average, and there are codes that come within 1 bit of it (within a vanishing fraction per symbol, if you encode long blocks). The ideal code gives outcome a codeword of length , short codes for common outcomes.
Take four outcomes with probabilities . Their surprises are 1, 2, 3, and 3 bits, and the prefix code 0, 10, 110, 111 uses exactly those lengths. The average length is bits, which equals the entropy. A naive fixed-length code would use 2 bits for everything.
This link between probability and compression is not a curiosity. A language model is a compressor. Pair it with an arithmetic coder and it can encode text in about as many bits as its loss, which is why bits per byte (below) is a meaningful way to compare models.
Cross-entropy, the loss behind every classifier
Now suppose the data come from , but you build your code (or your predictions) from a different distribution . Each outcome costs you , and the average cost is the cross-entropy
In plain words, cross-entropy is the average surprise of a model at data that actually come from . In the example above, using the fixed-length 2-bit code amounts to uniform, and bits, a quarter of a bit more than the 1.75 of the ideal code.
In classification the "data distribution" for one example is the one-hot target , so the cross-entropy collapses to , the negative log-probability of the true class. That is the softmax cross-entropy loss of §0.2. A language model's loss is the same thing averaged over tokens,
where is the token at position and are the tokens before it. This is a sample estimate of the cross-entropy between the true distribution of text and the model. When papers report a loss of 2.0 for a language model, they mean the model is, on average, nats ( bits) surprised by each token.
KL divergence, the price of the wrong model
How much worse than ideal is a model ? Subtract the best possible cost, , from what you actually pay, . That difference is the Kullback-Leibler divergence,
In plain words, KL divergence is the extra surprise, per draw, that you suffer by believing when the truth is .
The most important fact about it is that it is never negative, and it is zero only when . This is Gibbs' inequality, and the proof takes one line. Using (the log lies below its tangent line at 1),
with equality exactly when everywhere. Two corollaries follow at once. Cross-entropy is never below entropy, , so a model's loss is bounded below by the entropy of the data. And with the uniform distribution over outcomes, , which proves that the uniform distribution has the most entropy.
Now the punchline for machine learning. When we train a model by minimizing cross-entropy on data from ,
the entropy term does not depend on , so minimizing cross-entropy is minimizing , the extra surprise the model suffers on real data, which is also maximum likelihood (§0.4). The leftover is a floor no model can beat, the inherent unpredictability of the data. The "irreducible loss" term in neural scaling laws (§9.3) is an estimate of it.
Play with two distributions below. Make put almost no mass where has some, and watch explode while stays moderate.
Entropy, cross-entropy, and KL, with the edge cases right
Implement entropy(p, base=np.e), cross_entropy(p, q, base=np.e), and kl(p, q, base=np.e) for discrete distributions given as 1-D arrays. Treat as 0. Where but , cross-entropy and KL are inf. Return plain floats, with no NaN and no warnings.
Forward and reverse KL
KL divergence is not symmetric, and the direction you choose changes what you get. This is one of the most important practical ideas in this section, so let's go slowly.
Suppose the truth is complicated (here, two separated bumps) and you must approximate it with something simple, a single Gaussian . Which Gaussian is "closest" depends on which KL you minimize.
Forward KL, , averages over where has mass. If is tiny where has mass, is hugely negative there and the penalty is enormous, infinite if . So the best covers every region of , even if that means putting mass in the gap between the bumps. It is called mass-covering or mean-seeking. For a Gaussian the answer is exact. Since , and , setting derivatives to zero gives and . Forward KL matches the moments, and with two bumps the mean sits in the valley between them.
Reverse KL, , averages over where has mass. Now the big penalty is for putting mass where is tiny, and there is no penalty for ignoring parts of , since regions where contribute nothing to the average. So the best squeezes into one bump and fits it well. It is called mode-seeking or zero-forcing.
The forward fit is centered at 0 with a standard deviation of about 2.1, matching the mixture's moments and putting a large share of its mass, its peak included, in the valley where has almost none. The reverse fit locks onto one bump (the grid happens to pick the right-hand bump at , and the left-hand one ties by symmetry) with exactly that bump's width. Its divergence is , because inside its bump , so everywhere has mass.
These two behaviors show up across the book.
| forward | reverse | |
|---|---|---|
| averages over | the target | the model |
| behavior | covers all modes, may blur | picks modes, may drop some |
| needs | samples from | samples from and the value of |
| where you meet it | maximum likelihood, pretraining, distillation from a teacher | variational inference, the KL penalty in RLHF and GRPO |
The last row is worth spelling out. Pretraining minimizes the forward KL , because we have samples of text but no formula for its probability. RLHF penalizes the reverse KL between the policy being trained and the reference model it started from (§16.4), because the samples come from the policy and both log-probabilities are available. That choice is also what gives the best policy its explicit form, the reference tilted by , on which DPO is built (§17.1). The mode-seeking nature of reverse KL is one commonly offered explanation for why RLHF-tuned models produce less diverse outputs than their base models.
Estimating KL from samples
In RLHF and GRPO you cannot sum over every possible sequence. You estimate from samples , using the ratio . The obvious estimator is , which is unbiased (its mean is exactly the KL) but very noisy, and it is negative for many samples even though KL never is. John Schulman's note on the topic (linked below) popularized a better one,
It is unbiased, because , so the term has mean zero and . It is never negative, because . And when and are close it has much lower variance, because the added term is negatively correlated with and cancels much of its noise. A third choice, , has low variance but is biased. GRPO's KL penalty (§18.4) is exactly with and . (It is unbiased only when the samples really come from . GRPO samples from a slightly older copy of the policy, so in practice it is a close approximation.)
Three Monte Carlo estimators of KL
Given log-probabilities of samples drawn from , logq and logp (arrays of shape (n,), where logp[i] and logq[i] for ), implement kl_estimators(logq, logp) returning a dict with keys "k1", "k2", "k3", each the per-sample array of that estimator (not its mean), estimating . Work from the log-ratio, never from probabilities, because sequence probabilities underflow.
Mutual information
How much does knowing one variable tell you about another? Start with conditional entropy, the uncertainty left in once you know ,
The mutual information is how much knowing reduces the uncertainty about ,
In plain words, mutual information is how far the joint distribution is from what it would be if the variables were independent. It is symmetric, never negative, and zero exactly when and are independent.
Notice the term inside the sum. is the pointwise mutual information (PMI), how much more often and occur together than independence predicts, so mutual information is the average PMI over the joint distribution. PMI between words and their contexts is what classical word vectors are built from (§1.4). A small example makes it concrete. Take the rain and wet-grass table of §0.4, with whether it rained and whether the grass is wet, and joint probabilities , , , and . Rain has entropy bits. Looking at the grass removes more than half of it, bits, leaving bits.
Mutual information is the quantity contrastive learning secretly maximizes. The InfoNCE loss used to train CLIP and modern embedding models satisfies for a batch of candidates (van den Oord et al., 2018), so driving the loss down pushes up a lower bound on the information shared by the two views. You'll derive this in §7.2.
Mutual information from a joint table
Implement mutual_information(P, base=2) for a joint distribution table P of shape (m, n) (nonnegative, summing to 1). Cells with probability 0 contribute 0. Also implement conditional_entropy(P, base=2) returning , where rows index and columns index .
Perplexity, and bits per byte
A language model's loss is an average cross-entropy in nats per token, which is hard to feel. Perplexity turns it into a count,
In plain words, perplexity is one over the geometric mean of the probabilities the model gave to the tokens that actually occurred, which makes it the number of equally likely choices that would leave you as uncertain as the model is, on average. That is why it is often called the effective branching factor.
Work one by hand. A model assigns probabilities 0.5, 0.1, 0.9, and 0.25 to the four tokens of a short text. Their logs are , , , and , so the mean loss is nats per token, and the perplexity is . The geometric mean probability is . Notice what perplexity is not. The average of the inverse probabilities, , is a different and meaningless number, and so is the average of per-token perplexities.
Three anchor values follow from the definition.
- A uniform model has perplexity . If for every token, and . This is also where a freshly initialized model starts, so a GPT-2 model with its vocabulary of 50,257 tokens should begin training near a loss of nats. Checking that number is the first step of the debugging recipe in §0.7.
- A perfect model has perplexity 1. It puts probability 1 on every token that occurs. No real model gets there, because text has entropy of its own, the floor from the KL section above.
- One zero sends perplexity to infinity. If any , then and . Short of zero, one confident mistake still costs a lot. A token given probability adds nats to the total, as much as 20 ordinary tokens at a loss near 1. Perplexity punishes overconfidence far more than it rewards confidence, which is the cross-entropy's character showing through.
The same quantity has three common units, and you should convert between them without thinking. The loss is in nats per token. Dividing by gives bits per token. And perplexity is both and 2 raised to the bits per token. A loss of 2.0 nats per token is bits per token and a perplexity of , as unsure as choosing among 7 or 8 equally likely tokens at every step.
At real scale, the OpenAI GPT-2 checkpoints, evaluated on the OpenWebText validation set, reach a loss of 3.12 nats per token for the 124M-parameter model and 2.54 for the 1.5B-parameter one (Karpathy's nanoGPT reports these baselines). Those are perplexities of and . Going from 10.82 at initialization to 3.12 shrinks the effective number of choices per token from 50,257 to about 23.
Computing it over a corpus
Perplexity is a statement about a whole evaluation set, and the most common mistakes are in how the per-token numbers are combined.
- Pool the tokens, then exponentiate. The perplexity of a corpus is . Averaging per-document perplexities gives too much weight to short documents, and even with equal-length documents it comes out too large, because is convex, so the average of the exponentials exceeds the exponential of the average whenever the documents' losses differ (Jensen's inequality). Averaging per-batch mean losses is wrong for the same reason whenever batches hold different numbers of counted tokens, the bug that gradient accumulation also has to avoid (§0.9).
- Count only real predictions. Padding positions, and the first token of a sequence (which nothing predicts), must be excluded from both the total loss and the token count. Whether the end-of-sequence token counts is a convention that has to be stated, because it changes the number (§3.1).
- Context changes the number. The same model scores lower perplexity when each token sees more context. Cutting a long text into non-overlapping chunks leaves the first tokens of every chunk with almost no context and inflates perplexity. Evaluating with an overlapping sliding window fixes this at extra cost (§6.6 builds it).
Comparing across tokenizers with bits per byte
Perplexity per token depends on the tokenizer. A tokenizer with longer tokens has fewer, harder predictions per document, so two models with different tokenizers cannot be compared by per-token loss (§2.1). What does not depend on the tokenizer is the total probability the model assigns to the text, so the fix is to normalize the total by something every tokenizer shares, the raw bytes of text. If a document of bytes is split into tokens and the model's total loss is nats, then
In plain words, convert the document's total surprise to bits and divide by its length in bytes. For example, a loss of 2.0 nats per token with an average of 4 bytes per token is bits per byte. Bits per byte is also directly a compression rate. A model at 0.72 bits per byte, driving an arithmetic coder, would compress text to 9% of its original size (0.72 out of 8 bits). For GPT-2 small, using the common rule of thumb of about 4 bytes of English per token, 3.12 nats per token is bits per token and about bits per byte. Bytes are not characters. Most non-English scripts take 2 to 4 bytes per character in UTF-8, so bits per character and bits per byte differ there, and papers should say which they report. You'll use these conversions in §6.6.
Perplexity and bits per byte from token log-probabilities
Implement perplexity(token_logprobs) for an array of natural-log probabilities the model assigned to each actual token, and bits_per_byte(token_logprobs, n_bytes) for a text of n_bytes bytes.
Corpus perplexity from a padded batch
An evaluation harness hands you logprobs, an array of shape (B, T) holding the natural-log probability the model gave to each target token, and a boolean mask of the same shape that is True on the positions that count. Padding positions hold garbage, which may include -inf or NaN. Implement corpus_perplexity(logprobs, mask) returning the perplexity of all counted tokens pooled together, and doc_perplexities(logprobs, mask) returning the perplexity of each row, shape (B,). Every row has at least one counted token. No loops, and no floating-point warnings.
Label smoothing
Cross-entropy with one-hot targets has a strange optimum. Once a training example is classified correctly, the loss keeps decreasing as , which requires the logit gap between the true class and the others to grow without bound. On data the model can fit perfectly, the logits drift toward infinity, and the model becomes overconfident.
Label smoothing (Szegedy et al., 2016) replaces the one-hot target with a softened one. With smoothing and classes,
In plain words, mix a little of the uniform distribution into every target, which adds a penalty for putting very low probability on any class.
Three consequences follow from what we already know. The gradient is still "predicted minus target", (the derivation in §0.2 holds for any target distribution). The loss is minimized when , by Gibbs' inequality, so the optimal logit gap between the true class and any other is finite, , which is about 9.1 for and . And the minimum loss is no longer 0 but the entropy , so do not be alarmed when a smoothed model's training loss plateaus above zero.
Without smoothing the gap keeps growing, roughly logarithmically in the number of steps, forever. With smoothing it settles quickly at the predicted value, for these 10 classes. Label smoothing became standard in image classification and machine translation, and the original Transformer used . It has a known cost. Müller, Kornblith & Hinton (2019) showed that it tends to erase the information in a network's logits about which wrong classes are similar to the right one, which makes smoothed networks worse teachers for knowledge distillation. Most large language model pretraining does not use it.
Label-smoothed cross-entropy, forward and backward
Implement smoothed_cross_entropy(logits, y, eps) for logits of shape (N, K) and integer labels y of shape (N,), returning (mean loss, dlogits), where dlogits is the gradient of the mean loss (so it includes the factor ), with the smoothed target . It must be numerically stable. With eps=0 it must reduce to ordinary cross-entropy.
In PyTorch
Read more
- Shannon (1948). A Mathematical Theory of Communication. The founding paper, still remarkably readable.
- MacKay (2003). Information Theory, Inference, and Learning Algorithms. Free, and the best book connecting information theory to learning.
- Christopher Olah (2015). Visual Information Theory. Entropy, cross-entropy, and KL as pictures of code lengths.
- John Schulman (2020). Approximating KL Divergence. The , , estimators and their bias and variance.
- Karpathy. nanoGPT. Its README lists the OpenWebText losses of the GPT-2 checkpoints quoted in this section.
- Szegedy et al. (2016). Rethinking the Inception Architecture for Computer Vision. Introduces label smoothing (Section 7).
- Müller, Kornblith & Hinton (2019). When Does Label Smoothing Help? Calibration benefits, and why smoothed teachers distill poorly.
- van den Oord, Li & Vinyals (2018). Representation Learning with Contrastive Predictive Coding. InfoNCE and its mutual-information bound.