◆ AI All-in-One

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
↗ Plan a path here

Read first

Probability Distributions

This leads to

Variational AutoencodersDecision Trees
The full path from zero — 2 concepts before this one
  1. Probability Basics
  2. Probability Distributions
  3. 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 pp carries log⁡2(1/p)\log_2(1/p) 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, pp, but you expected another, qq. 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 =−log⁡p= -\log p. Entropy = average surprise of the truth. Cross-entropy = average surprise when you predict with qq but reality is pp. KL divergence = cross-entropy − entropy, the cost of being wrong. Training minimises cross-entropy, and perplexity =ecross-entropy= e^{\text{cross-entropy}}.

How it works

Information content of one event

The information content (also called surprisal) of an outcome with probability pp is

I(p)=−log⁡2pbitsI(p) = -\log_2 p \quad \text{bits}
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, −ln⁡p-\ln p, 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 1/2×1/2=1/41/2 \times 1/2 = 1/4, and should carry 1+1=21 + 1 = 2 bits. The logarithm is the function that turns multiplying probabilities into adding information: −log⁡2(1/4)=2-\log_2(1/4) = 2.

Surprise of one event −log₂ p bits: rare events carry more information probability p of the event bits 0 0.5 1 0 2 4 6 8 10 1 in 1,024: 10 bits a six on a die: 2.58 a coin flip: 1 bit certain: 0 Entropy of a coin the average surprise per flip probability of heads bits 0 0.5 1 0 0.5 1 fair: 1 bit 0.9 heads: 0.47
Fig. 1 Left: surprise −log₂ p for an event of probability p. A certain event carries 0 bits, a coin flip 1 bit, a six on a die 2.58 bits, and a 1-in-1,024 event 10 bits. Right: the entropy of a coin as its chance of heads varies, highest (1 bit) when fair and falling to 0 when the outcome is certain.

Entropy: average surprise

The entropy of a distribution pp is the expected information content, the average surprise:

H(p)=−∑xp(x)log⁡2p(x)H(p) = -\sum_x p(x) \log_2 p(x)

Each outcome's surprise, weighted by how often it happens. (By convention, outcomes with probability 0 contribute nothing.)

  • Fair coin: H=−(0.5log⁡20.5+0.5log⁡20.5)=1H = -(0.5 \log_2 0.5 + 0.5 \log_2 0.5) = 1 bit.
  • Coin with 90% heads: H=−(0.9log⁡20.9+0.1log⁡20.1)=0.137+0.332=0.469H = -(0.9 \log_2 0.9 + 0.1 \log_2 0.1) = 0.137 + 0.332 = 0.469 bits.
  • Fair 8-sided die: H=log⁡28=3H = \log_2 8 = 3 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 H(p)H(p) bits on average, and that good codes come close. The recipe: give an outcome of probability pp a code of length about −log⁡2p-\log_2 p 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: p=[0.5,0.25,0.25]p = [0.5, 0.25, 0.25]. You must send each day's weather as bits.

H(p)=0.5×1+0.25×2+0.25×2=1.5 bitsH(p) = 0.5 \times 1 + 0.25 \times 2 + 0.25 \times 2 = 1.5 \text{ bits}

And there's a code that achieves it: sunny = 0, cloudy = 10, rain = 11. Its average length is 0.5×1+0.25×2+0.25×2=1.50.5 \times 1 + 0.25 \times 2 + 0.25 \times 2 = 1.5 bits per day.

Cross-entropy: surprise under the wrong beliefs

Now suppose you designed your code believing the weather follows q=[0.25,0.25,0.5]q = [0.25, 0.25, 0.5], that rain is most common. Your code gives rain the short code: rain = 0, sunny = 10, cloudy = 11. But the real weather still follows pp. Your average length becomes

0.5×2+0.25×2+0.25×1=1.75 bits0.5 \times 2 + 0.25 \times 2 + 0.25 \times 1 = 1.75 \text{ bits}

That's the cross-entropy of qq relative to pp: the average surprise (code length) when outcomes come from pp but you use the lengths −log⁡q-\log q suited to qq:

H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_x p(x) \log q(x)
Weather in a city where half the days are sunny send each day’s weather in bits, using a code built for some belief weather reality p best code belief q q’s code sunny 0.5 0 0.25 10 cloudy 0.25 10 0.25 11 rain 0.25 11 0.5 0 Rare outcomes get longer codes: length = −log₂ (probability). Coding real weather with q’s code wastes bits on average. 1.5 bits H(p) entropy 1.75 bits H(p, q) cross-entropy KL = 0.25 wasted bits Average bits per day
Fig. 2 Weather with true probabilities 0.5, 0.25 and 0.25 needs 1.5 bits per day on average with the best code. A code built for the wrong belief q = 0.25, 0.25, 0.5 averages 1.75 bits. The extra 0.25 bits per day is the KL divergence.

Cross-entropy is always at least the entropy: H(p,q)≥H(p)H(p, q) \ge H(p), with equality only when q=pq = p. You can't beat the truth.

KL divergence: the cost of being wrong

The difference is the Kullback–Leibler (KL) divergence:

DKL(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x)D_{\text{KL}}(p \,\|\, q) = H(p, q) - H(p) = \sum_x p(x) \log \frac{p(x)}{q(x)}

In the weather example it is 1.75−1.5=0.251.75 - 1.5 = 0.25 bits per day: the price of believing qq when the truth is pp. If you had believed the uniform q=[1/3,1/3,1/3]q = [1/3, 1/3, 1/3] instead, the cross-entropy would be log⁡23=1.585\log_2 3 = 1.585 bits and the KL divergence only 0.0850.085 bits. That belief is less wrong.

Two properties to remember:

  • DKL(p ∥ q)≥0D_{\text{KL}}(p \,\|\, q) \ge 0, and it is 0 only when p=qp = q. It behaves like a distance between distributions.
  • But it is not symmetric: DKL(p ∥ q)≠DKL(q ∥ p)D_{\text{KL}}(p \,\|\, q) \ne D_{\text{KL}}(q \,\|\, p) 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" pp 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

H(p,q)=−log⁡q(correct class)H(p, q) = -\log q(\text{correct class})

This is exactly the negative log-likelihood from Maximum Likelihood Estimation. If the model gives the correct class probability 0.8, the loss is −ln⁡0.8=0.223-\ln 0.8 = 0.223 nats. If 0.1, it is 2.3032.303. If 0.001, it is 6.9086.908. Averaged over a dataset, it is the cross-entropy loss. Because H(p)H(p) 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 −log⁡q(actual next token)-\log q(\text{actual next token}) 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=e cross-entropy in nats=2 cross-entropy in bits\text{perplexity} = e^{\,\text{cross-entropy in nats}} = 2^{\,\text{cross-entropy in bits}}

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 ln⁡10≈2.30\ln 10 \approx 2.30 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 0.4×0+0.6×0.65=0.390.4 \times 0 + 0.6 \times 0.65 = 0.39 bits. The information gain of the split is 1−0.39=0.611 - 0.39 = 0.61 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 ln⁡2≈0.693\ln 2 \approx 0.693 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_entropy or log_softmax, never by taking log of 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. DKL(p ∥ q)D_{\text{KL}}(p \,\|\, q) and DKL(q ∥ p)D_{\text{KL}}(q \,\|\, p) behave differently, and F.kl_div(input, target) expects input to be log-probabilities of qq and computes DKL(target ∥ q)D_{\text{KL}}(\text{target} \,\|\, q). 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

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

  1. 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?
  2. A model predicts [0.7,0.2,0.1][0.7, 0.2, 0.1] and the correct class is the second. What is the cross-entropy loss in nats? What would it be if the model had predicted [0.1,0.8,0.1][0.1, 0.8, 0.1]?
  3. 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 e3.0≈20.1e^{3.0} \approx 20.1, and 3.0/ln⁡2≈4.333.0 / \ln 2 \approx 4.33 bits per token.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Which has the highest entropy?

  2. A language model reaches an average cross-entropy of 3.0 nats per token. What is its perplexity, roughly?

  3. Model A (50,000-token vocabulary) has perplexity 15; model B (a much smaller vocabulary with shorter tokens) has perplexity 9 on the same text. What can you conclude?

  4. The true weather is p = [0.5, 0.25, 0.25] (entropy 1.5 bits). A code designed for belief q has average length 1.75 bits. What is the KL divergence D(p‖q)?

  5. You compute a loss as torch.log(torch.softmax(logits, dim=-1)) and occasionally get -inf. What is the better approach?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Visual Information Theory

Christopher Olah · 2015 · Beginner · Free

Entropy, cross-entropy and KL divergence built up from pictures of codes and probability boxes. The best first read on the topic.

Video

Solving Wordle using information theory

3Blue1Brown · 2022 · Beginner · Free

Entropy explained through choosing the best Wordle guess: information as the bits of uncertainty a guess removes.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

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