Level 3 In-Depth AI · Math Foundations
Entropy, Cross-Entropy and KL Divergence
Information theory measures surprise in bits. Entropy is the average surprise of a distribution, cross-entropy is the surprise when your predictions don't match reality, and KL divergence is the gap between them. Cross-entropy is the loss that trains classifiers and every large language model, and perplexity is how their quality is reported.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 2 concepts →
- Quiz
- 5 questions ↓
Read first
Probability DistributionsThe full path from zero — 2 concepts before this one
- Probability Basics
- Probability Distributions
- Entropy, Cross-Entropy and KL Divergence
Read them roughly in this order. See it on the concept map →
Why it matters
Look inside the training code of almost any classifier or language model and you'll find the same line: a cross-entropy loss. When a lab reports how good a language model is at predicting text, it quotes a loss in nats or bits per token, or a perplexity. When RLHF fine-tunes a chatbot, it adds a KL divergence penalty to stop the model drifting too far from where it started. Variational autoencoders have a KL term in their loss, knowledge distillation minimises one, and Decision Trees choose their splits by entropy.
All of these come from information theory, founded by Claude Shannon in 1948 to answer an engineering question: how many bits do you need to send a message? His answer turned out to be a precise way of measuring uncertainty and surprise, which is exactly what a learning system needs to reduce.
The Maximum Likelihood Estimation chapter showed that cross-entropy is the negative log-likelihood. This chapter shows the same quantity from the other side, as wasted bits, and builds up the related ideas: entropy, KL divergence and perplexity.
The intuition
Information is surprise. If a friend tells you "the sun rose this morning", you learn nothing, because you were certain already. If they tell you "it snowed in the Sahara", you learn a lot, because it was very unlikely. The less probable an event, the more information its occurrence carries.
Shannon made this precise with a game of yes/no questions. To find out the result of a fair coin flip you need one yes/no question ("heads?"). That's 1 bit of information. To identify one of 8 equally likely options takes 3 questions (halve, halve, halve): 3 bits. To pin down one of 1,024 equally likely options takes 10. Each yes/no answer halves the possibilities, so an outcome with probability carries bits.
Now the three main ideas:
- Entropy is the average surprise of a source of outcomes, the uncertainty before you look. A fair coin has 1 bit of entropy. A coin that lands heads 99% of the time has very little: you're rarely surprised.
- Cross-entropy is your average surprise when reality follows one distribution, , but you expected another, . If your expectations are wrong, you are surprised more often than necessary.
- KL divergence is the extra surprise caused by having the wrong expectations: cross-entropy minus entropy.
Training a model to minimise cross-entropy means teaching it to be as little surprised by the real data as possible. That is the same as learning to predict it well.
Key idea Surprise . Entropy = average surprise of the truth. Cross-entropy = average surprise when you predict with but reality is . KL divergence = cross-entropy − entropy, the cost of being wrong. Training minimises cross-entropy, and perplexity .
How it works
Information content of one event
The information content (also called surprisal) of an outcome with probability is
| Event | Probability | Information |
|---|---|---|
| a certain event | 1 | 0 bits |
| a fair coin lands heads | 1/2 | 1 bit |
| a die shows six | 1/6 | 2.58 bits |
| one specific card from a deck | 1/52 | 5.70 bits |
| a 1-in-1,024 event | 1/1024 | 10 bits |
A bit here is a unit of information: the amount gained from one fair yes/no answer. Using the natural logarithm, , gives the unit called a nat (1 nat ≈ 1.44 bits). Machine-learning code uses nats, because PyTorch's log is the natural log. The ideas are identical, only the unit changes.
Why the logarithm? Because information from independent events should add. Two coin flips have probability , and should carry bits. The logarithm is the function that turns multiplying probabilities into adding information: .
Entropy: average surprise
The entropy of a distribution is the expected information content, the average surprise:
Each outcome's surprise, weighted by how often it happens. (By convention, outcomes with probability 0 contribute nothing.)
- Fair coin: bit.
- Coin with 90% heads: bits.
- Fair 8-sided die: bits.
Entropy is highest when all outcomes are equally likely (maximum uncertainty) and zero when one outcome is certain. A language model's next-token distribution has low entropy after "The capital of France is" and high entropy after "My favourite word is".
Entropy is the shortest possible average message length. Shannon proved that no code can describe outcomes using fewer than bits on average, and that good codes come close. The recipe: give an outcome of probability a code of length about bits, so common outcomes get short codes. Morse code does something similar by hand, giving "E", the most common letter in English, a single dot.
A worked example: weather codes
A city's weather is sunny half the time, cloudy a quarter and rainy a quarter: . You must send each day's weather as bits.
And there's a code that achieves it: sunny = 0, cloudy = 10, rain = 11. Its average length is bits per day.
Cross-entropy: surprise under the wrong beliefs
Now suppose you designed your code believing the weather follows , that rain is most common. Your code gives rain the short code: rain = 0, sunny = 10, cloudy = 11. But the real weather still follows . Your average length becomes
That's the cross-entropy of relative to : the average surprise (code length) when outcomes come from but you use the lengths suited to :
Cross-entropy is always at least the entropy: , with equality only when . You can't beat the truth.
KL divergence: the cost of being wrong
The difference is the Kullback–Leibler (KL) divergence:
In the weather example it is bits per day: the price of believing when the truth is . If you had believed the uniform instead, the cross-entropy would be bits and the KL divergence only bits. That belief is less wrong.
Two properties to remember:
- , and it is 0 only when . It behaves like a distance between distributions.
- But it is not symmetric: in general. Order matters, which is why it's called a divergence rather than a distance.
Where it appears in AI: the KL penalty in RLHF and Preference Optimization keeps a fine-tuned model's output distribution close to the original's. In VAEs a KL term keeps the learned codes close to a simple Gaussian. Knowledge Distillation and Small Models trains a small student model to minimise the KL divergence from a large teacher's output distribution.
Cross-entropy as a training loss
Here is the link to training. For a classification example, the "true distribution" puts probability 1 on the correct class and 0 elsewhere (a one-hot distribution). Then every term of the sum vanishes except the correct class, and the cross-entropy collapses to
This is exactly the negative log-likelihood from Maximum Likelihood Estimation. If the model gives the correct class probability 0.8, the loss is nats. If 0.1, it is . If 0.001, it is . Averaged over a dataset, it is the cross-entropy loss. Because is fixed by the data, minimising cross-entropy is the same as minimising the KL divergence between the data's distribution and the model's: making the model's beliefs match reality.
For a language model, every position in the training text is a classification over the vocabulary, with the actual next token as the correct class. The training loss is the average of over trillions of positions.
Perplexity
Losses in nats are hard to picture, so language models are often described by their perplexity, the exponential of the average cross-entropy:
Perplexity is the effective number of equally likely choices the model is hesitating between at each step. A model that spreads its bets evenly over 10 tokens has cross-entropy nats and perplexity 10. A perfect model has perplexity 1. A model that guesses uniformly over a 50,000-token vocabulary has perplexity 50,000. Lower is better, but perplexities are only comparable between models that use the same tokenizer and the same test text.
Information gain in decision trees
Entropy also measures how mixed a group is, which is how Decision Trees pick questions. Take 10 emails, 5 spam and 5 not: entropy 1 bit, as mixed as possible. Split them on "contains free": the 4 emails with "free" are all spam (entropy 0), and the 6 without contain 1 spam and 5 normal (entropy 0.65 bits). The weighted average entropy after the split is bits. The information gain of the split is bits: how much uncertainty the question removed. A tree tries every candidate question and picks the one with the largest gain. (Choosing the guess with the most expected information is also the trick behind a good Wordle strategy.)
In code
import numpy as np
def entropy(p): # in bits
p = np.asarray(p, dtype=float)
p = p[p > 0] # 0 * log 0 counts as 0
return -np.sum(p * np.log2(p))
def cross_entropy(p, q): # reality p, prediction q, in bits
p, q = np.asarray(p, float), np.asarray(q, float)
return -np.sum(p * np.log2(q))
def kl(p, q):
return cross_entropy(p, q) - entropy(p)
print(-np.log2(0.5), -np.log2(1/6), -np.log2(1/1024)) # 1.0 2.584962500721156 10.0
print(entropy([0.5, 0.5]), entropy([0.9, 0.1]).round(3), entropy([1/8] * 8)) # 1.0 0.469 3.0
weather = [0.5, 0.25, 0.25] # sunny, cloudy, rain
print(entropy(weather)) # 1.5
for q in ([1/3, 1/3, 1/3], [0.25, 0.25, 0.5]):
print(cross_entropy(weather, q).round(3), kl(weather, q).round(3))
# 1.585 0.085
# 1.75 0.25
# Information gain of splitting 10 emails (5 spam) on the word "free"
parent = entropy([0.5, 0.5])
left, right = entropy([1.0]), entropy([1/6, 5/6]) # 4 emails all spam; 6 emails, 1 spam
print(round(parent - (0.4 * left + 0.6 * right), 3)) # 0.61
In PyTorch, F.cross_entropy takes raw logits and the indices of the correct classes, and returns the mean cross-entropy in nats. Perplexity is one exp away:
import math
import torch
import torch.nn.functional as F
# A language model's scores over a 5-token vocabulary, at 3 positions
logits = torch.tensor([[3.0, 1.0, 0.2, 0.1, -1.0],
[0.5, 2.5, 0.3, 0.0, 0.0],
[1.0, 1.0, 1.0, 1.2, 0.8]])
targets = torch.tensor([0, 1, 3]) # the tokens that actually came next
loss = F.cross_entropy(logits, targets) # mean negative log-probability, in nats
print(loss.item(), math.exp(loss.item())) # 0.666617214679718 1.9476377241178497
# KL divergence (PyTorch wants log-probabilities as the first argument)
p = torch.tensor([0.5, 0.25, 0.25])
q = torch.tensor([1/3, 1/3, 1/3])
print(F.kl_div(q.log(), p, reduction="sum").item() / math.log(2)) # 0.084962525213943 KL(p||q) in bits
A perplexity of about 1.95 means that on these three positions the model is, on average, as uncertain as if it were choosing between two equally likely tokens.
Common pitfalls
- Mixing bits and nats. PyTorch losses are in nats. Divide by to get bits. A "loss of 2.0" and "2.0 bits per token" are different numbers.
- Taking the log of zero. If a model gives the correct answer probability exactly 0, the cross-entropy is infinite. Always compute losses from logits with
cross_entropyorlog_softmax, never by takinglogof a softmax output. - Comparing perplexities across tokenizers. A model with a larger vocabulary predicts bigger chunks per token, so its per-token perplexity isn't comparable with a model using smaller tokens. Compare bits per character or per byte instead, or use the same tokenizer.
- Getting KL's argument order wrong. and behave differently, and
F.kl_div(input, target)expectsinputto be log-probabilities of and computes . Read the documentation. - Low loss ≠ good behaviour. Cross-entropy rewards matching the training data's distribution. It says nothing about truthfulness or helpfulness, which is why chat models need further tuning (see Instruction Tuning and Chat Models and RLHF and Preference Optimization).
Watch out Cross-entropy punishes confident mistakes without limit: a probability of 0.0001 on the right answer costs 9.2 nats, about 13 times more than a hesitant 0.5. A few mislabelled training examples that the model confidently gets "wrong" can dominate the loss. Label smoothing (training towards, say, 0.9 instead of 1.0 on the correct class) is a common remedy.
Where it leads
- Loss Functions: cross-entropy alongside the other common losses.
- Logistic Regression: binary cross-entropy for two classes.
- Language Modeling and Next-Token Prediction, Pretraining Large Language Models and Evaluating LLMs and Benchmarks: next-token cross-entropy, bits per token and perplexity.
- Decision Trees: entropy and information gain for choosing splits.
- RLHF and Preference Optimization, Variational Autoencoders and Knowledge Distillation and Small Models: KL divergence as a penalty or a training target.
- Scaling Laws: how cross-entropy loss falls predictably as models and data grow.
A bit of history
Claude Shannon, an engineer at Bell Labs, founded information theory in a 1948 paper, A Mathematical Theory of Communication. He defined entropy, proved that it is the limit of lossless compression, and worked out how much information a noisy channel can carry. He reportedly took the name "entropy" on the advice of John von Neumann, because the formula matched the one used in physics. In 1951 Solomon Kullback and Richard Leibler introduced the divergence that bears their names. Shannon also estimated the entropy of English in 1951 by asking people to guess the next letter of a text, a human version of a language model. David Huffman, a student at MIT, found the optimal prefix code in 1952. Cross-entropy became the standard loss for neural network classifiers during the 1990s, and every large language model since has been trained to minimise it.
Try it
- By hand, compute the entropy in bits of a loaded die that shows six half the time and each other face one tenth of the time. Is it more or less than a fair die's 2.585 bits?
- A model predicts and the correct class is the second. What is the cross-entropy loss in nats? What would it be if the model had predicted ?
- A language model reaches an average loss of 3.0 nats per token on a test set. What is its perplexity? How many bits per token is that?
Hint for 3: perplexity is , and bits per token.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Visual Information Theory
Entropy, cross-entropy and KL divergence built up from pictures of codes and probability boxes. The best first read on the topic.
Solving Wordle using information theory
Entropy explained through choosing the best Wordle guess: information as the bits of uncertainty a guess removes.
Information Theory, Inference, and Learning Algorithms
A classic textbook that joins information theory, Bayesian inference and neural networks. Free to read on screen.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/information-theory.md