2 Foundations 4 / 6
  1. In this chapter
  2. Python and tensor shapes
  3. From Language Modeling to Next-Token Prediction
  4. Neural Network Basics
  5. Information Theory Refresher
  6. Tokenizers and Embeddings
  7. Optimizers and Training Stability
All chapters →

Chapter 2 · Foundations 2.4

Information Theory Refresher: Entropy, Cross-Entropy and KL Divergence

Entropy measures how surprising a distribution is on average, cross-entropy is the cost of coding data from p with a code built for q, and KL divergence is the excess over the optimum. A language model's training loss is cross-entropy; perplexity is its exponential.

Intermediate 11 min read Updated Companion code ↓

After this page you will be able to

  • Explain what entropy, cross-entropy and KL divergence each measure, and how they relate.
  • Say why the training loss of a language model is a cross-entropy, and convert it into perplexity and bits-per-byte.
  • Explain why bits-per-byte can be compared across tokenizers.
  • Explain why the direction of the KL divergence matters.
On this page
  1. Why revisit information theory
  2. Surprise and entropy
  3. Cross-entropy: coding with the wrong distribution
  4. KL divergence: the extra cost
  5. Hands-on: the cross-entropy lab
  6. The loss of a language model is cross-entropy
  7. Perplexity and bits-per-byte
  8. The direction of KL
  9. Hands-on code
  10. Summary and exercises
  11. Quick self-check
  12. Further reading
  13. FAQ

Why revisit information theory

The loss used to train a language model is called cross-entropy, evaluations report perplexity, the penalty that keeps an RLHF-tuned model from drifting is called a KL penalty, and distillation makes a student imitate a teacher by minimizing a KL as well. These terms come from one toolkit. Entropy measures how surprising a distribution is on average, cross-entropy is the average cost of describing data from pp with a code designed for qq, and KL divergence is the part of that cost that exceeds the optimum. Once the relations between them are clear, pretraining, scaling laws and preference optimization stop tripping you up over notation.

Surprise and entropy

When an event with probability p(x)p(x) happens, the information it carries (also called surprisal) is

I(x)=−log⁡p(x)I(x) = -\log p(x)

The rarer the event, the more surprising it is. A certain event (p=1p=1) carries 0 information, and every time the probability halves the information grows by 1 bit (with base-2 logarithms). Entropy is the expected information, that is, how surprising the distribution is on average:

H(p)=−∑xp(x)log⁡p(x)=Ex∼p[−log⁡p(x)]H(p) = -\sum_x p(x)\log p(x) = \mathbb{E}_{x\sim p}\big[-\log p(x)\big]

By convention 0log⁡0=00\log 0 = 0. With base-2 logarithms the unit is the bit, with base ee it is the nat, and the two differ by a constant: 1 nat=1/ln⁡2≈1.443 bit1\ \text{nat} = 1/\ln 2 \approx 1.443\ \text{bit}. Deep learning frameworks use the natural logarithm by default, so loss values are in nats.

A few examples (in bits):

DistributionEntropyIntuition
Fair coin (0.5,0.5)(0.5, 0.5)1Every outcome is completely unpredictable
Biased coin (0.9,0.1)(0.9, 0.1)0.469Mostly heads, so little surprise
Eight equally likely outcomes3log⁡28=3\log_2 8 = 3
A certain outcome (1,0)(1, 0)0No surprise at all

Entropy has a concrete meaning. Shannon’s source coding theorem says that for a discrete distribution, the best prefix code has an average length of at least H(p)H(p) bits and can be made to stay below H(p)+1H(p)+1 bits. Entropy is the lower bound on the average number of bits needed to compress data drawn from the distribution.

Cross-entropy: coding with the wrong distribution

Suppose the data really comes from pp, but your coding scheme was designed for another distribution qq: events you consider likely get short codewords and events you consider unlikely get long ones. The average cost per symbol is

H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_x p(x)\log q(x)

This is the cross-entropy. When q=pq = p it equals the entropy H(p)H(p), and the further qq strays from pp, the higher the cost.

KL divergence: the extra cost

The part of the cross-entropy that exceeds the optimal cost is the KL divergence (Kullback–Leibler divergence):

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

Three properties to remember:

  1. Non-negative: DKL(p ∥ q)≥0D_{KL}(p\,\Vert\,q)\ge 0 (Gibbs’ inequality), with equality if and only if p=qp = q.
  2. Asymmetric: in general DKL(p ∥ q)≠DKL(q ∥ p)D_{KL}(p\,\Vert\,q)\ne D_{KL}(q\,\Vert\,p), so it is not a distance in the strict sense.
  3. Can be infinite: if qq is 0 anywhere pp has probability, then DKL(p ∥ q)=∞D_{KL}(p\,\Vert\,q)=\infty. This is why a language model’s softmax output is never allowed to be exactly 0.

Putting the equations together:

H(p,q)⏟cross-entropy  =  H(p)⏟entropy: the incompressible part  +  DKL(p ∥ q)⏟extra cost caused by the inaccuracy of q\underbrace{H(p,q)}_{\text{cross-entropy}} \;=\; \underbrace{H(p)}_{\text{entropy: the incompressible part}} \;+\; \underbrace{D_{KL}(p\,\Vert\,q)}_{\text{extra cost caused by the inaccuracy of }q}

Hands-on: the cross-entropy lab

The lab below uses five candidate words after “The weather today is …”. The top group of sliders sets the true distribution pp, the bottom group sets the model’s prediction qq, and the case selector jumps to a few typical situations.

  1. The model is exact: with q=pq=p the KL is 0 and the cross-entropy drops to the entropy H(p)=1.303H(p)=1.303 nat and cannot go lower. That term is the randomness of the data itself, not the model’s fault.
  2. The model is too unsure: when qq is close to uniform the cross-entropy is exactly ln⁡5=1.609\ln 5 = 1.609 nat and the perplexity equals the number of candidates, 5.
  3. Confident and wrong: putting 92% of the probability on a candidate that is truly 5% likely pushes the cross-entropy up to 3.721 nat and the perplexity to 41.29, far worse than “knowing nothing” (perplexity 5). Cross-entropy punishes confident mistakes the hardest.
  4. One right answer: when pp is one-hot, H(p)=0H(p)=0 and the cross-entropy is just −ln⁡q(correct answer)-\ln q(\text{correct answer}), here −ln⁡0.6=0.511-\ln 0.6 = 0.511. In this case DKL(q ∥ p)D_{KL}(q\,\Vert\,p) is infinite, so the difference between the two KL directions is plain to see.
  5. Two equally good answers: p=(0.45,0.45,… )p=(0.45, 0.45, \dots) and the model puts 90% on one of them. DKL(p ∥ q)=0.829D_{KL}(p\,\Vert\,q) = 0.829 is larger than DKL(q ∥ p)=0.497D_{KL}(q\,\Vert\,p) = 0.497: the former punishes the model for missing the other answer, while the latter is relatively tolerant of “picking just one”.

The loss of a language model is cross-entropy

Back to training. Let the training text come from a data distribution pdatap_{\text{data}} and let the model be qθq_\theta. At each position the true next token is known, so the target distribution there is one-hot and the loss is −log⁡qθ(xt∣x<t)-\log q_\theta(x_t\mid x_{<t}) (see From Language Modeling to Next-Token Prediction). Averaged over a large amount of text, by the law of large numbers it converges to

L(θ)  →  H(pdata,qθ)=H(pdata)+DKL(pdata  ∥  qθ)\mathcal{L}(\theta) \;\to\; H(p_{\text{data}}, q_\theta) = H(p_{\text{data}}) + D_{KL}(p_{\text{data}}\,\,\Vert\,\,q_\theta)

Here H(pdata)H(p_{\text{data}}) does not depend on the parameters θ\theta, so:

  • Minimizing the average negative log-likelihood, maximum likelihood estimation, and minimizing DKL(pdata ∥ qθ)D_{KL}(p_{\text{data}}\,\Vert\,q_\theta) are three names for the same thing.
  • The loss has a floor of H(pdata)H(p_{\text{data}}). Natural language is random in itself: the same prefix can legitimately be followed by many different words, so no model, however large, can push the loss to 0. The constant term EE in the loss curve fitted by the Chinchilla paper (Hoffmann et al., 2022) is interpreted as the loss of an ideal generative process on the text distribution; see Scaling Laws.
  • The loss also has a compression meaning. The loss in bits is the average number of bits per token you would spend compressing the text with this model and arithmetic coding.

Perplexity and bits-per-byte

Perplexity is the exponential of the cross-entropy and does not depend on the unit:

PPL=eH(p,q) (nat)=2H(p,q) (bit)\mathrm{PPL} = e^{H(p,q)\ \text{(nat)}} = 2^{H(p,q)\ \text{(bit)}}

Read it as “the model is, on average, as uncertain as if it were choosing among this many equally likely candidates”. For a uniform prediction over a vocabulary of size VV, H=ln⁡VH=\ln V and PPL=V\mathrm{PPL}=V. Llama 3’s vocabulary has 128,256 tokens, so a randomly initialized model starts with a loss of about ln⁡128256≈11.76\ln 128256 \approx 11.76 nat.

Perplexity is counted per token, and different tokenizers put different amounts of text in a token. Bits-per-byte (BPB) puts the number of bytes of the original text in the denominator, which removes the dependence on the tokenizer:

BPB=loss per token (nat)ln⁡2×number of tokensnumber of bytes\mathrm{BPB} = \frac{\text{loss per token (nat)}}{\ln 2}\times\frac{\text{number of tokens}}{\text{number of bytes}}

For example, model A has a loss of 2.0 nat/token and its tokenizer averages 4 bytes per token, while model B has a loss of 1.0 nat/token and averages 2 bytes per token. A’s perplexity is 7.39 and B’s is only 2.72, which makes B look far better. Yet both have a BPB of 0.721: they compress equally well, and the difference is only the granularity of the tokens.

The direction of KL

DKL(p ∥ q)D_{KL}(p\,\Vert\,q) and DKL(q ∥ p)D_{KL}(q\,\Vert\,p) answer two different questions, and different stages of LLM training use different directions:

ScenarioDirectionMeaning
Pretraining, SFTDKL(pdata ∥ qθ)D_{KL}(p_{\text{data}}\,\Vert\,q_\theta)Expectation over the data distribution. The model must leave probability for every token that appears in the data or the loss explodes (it covers all modes)
Knowledge distillationDKL(pteacher ∥ qstudent)D_{KL}(p_{\text{teacher}}\,\Vert\,q_{\text{student}})The student matches the teacher’s whole distribution, not just its top-1 token (Hinton et al., 2015)
KL penalty in RLHF / DPODKL(πθ ∥ πref)D_{KL}(\pi_\theta\,\Vert\,\pi_{\text{ref}})Expectation over samples from the current policy itself. It penalizes the policy for going where the reference model would not go (it tends to chase one mode)

The last direction is not arbitrary. The RLHF objective is max⁡π E[r]−βDKL(π ∥ πref)\max_\pi\ \mathbb{E}[r] - \beta D_{KL}(\pi\,\Vert\,\pi_{\text{ref}}), and the expectation is naturally taken over samples from the policy π\pi, so this is the direction that falls out. For the details of preference optimization see Preference Optimization: From RLHF to DPO.

Hands-on code

Reproduce the quantities above with NumPy; the numbers match the “confident and wrong” case in the lab:

import numpy as np


def entropy(p):
    p = np.asarray(p, dtype=float)
    p = p[p > 0]  # convention: 0·log0 = 0
    return float(-(p * np.log(p)).sum()) + 0.0


def cross_entropy(p, q):
    p, q = np.asarray(p, dtype=float), np.asarray(q, dtype=float)
    mask = p > 0
    return -(p[mask] * np.log(q[mask])).sum()


def kl(p, q):
    return cross_entropy(p, q) - entropy(p)


p = [0.50, 0.25, 0.10, 0.10, 0.05]  # true distribution
q = [0.02, 0.02, 0.02, 0.02, 0.92]  # model: very confident, but bets on the wrong token
print(f"H(p)      = {entropy(p):.3f} nat")
print(f"H(p, q)   = {cross_entropy(p, q):.3f} nat")
print(f"KL(p||q)  = {kl(p, q):.3f} nat")
print(f"KL(q||p)  = {kl(q, p):.3f} nat")
print(f"perplexity = {np.exp(cross_entropy(p, q)):.2f}")

# When training a language model, p is one-hot: the true next token has probability 1
one_hot = [1, 0, 0, 0, 0]
q = [0.60, 0.20, 0.10, 0.05, 0.05]
print(f"one-hot: H(p) = {entropy(one_hot):.3f}, H(p, q) = {cross_entropy(one_hot, q):.3f} = -ln 0.6 = {-np.log(0.6):.3f}")

# A tokenizer-independent metric: bits per byte
for name, loss, bytes_per_token in [("A", 2.0, 4.0), ("B", 1.0, 2.0)]:
    print(f"model {name}: perplexity {np.exp(loss):.2f}, bits-per-byte {loss / np.log(2) / bytes_per_token:.3f}")

Output:

H(p)      = 1.303 nat
H(p, q)   = 3.721 nat
KL(p||q)  = 2.417 nat
KL(q||p)  = 2.500 nat
perplexity = 41.29
one-hot: H(p) = 0.000, H(p, q) = 0.511 = -ln 0.6 = 0.511
model A: perplexity 7.39, bits-per-byte 0.721
model B: perplexity 2.72, bits-per-byte 0.721

Summary and exercises

Key points:

  1. Entropy is the average surprise of a distribution and the lower bound on the average number of bits needed to compress data from it. Cross-entropy is the average cost of coding pp with qq. KL divergence is the difference between the two, non-negative and asymmetric.
  2. H(p,q)=H(p)+DKL(p ∥ q)H(p,q) = H(p) + D_{KL}(p\,\Vert\,q): the training loss is the entropy of the data itself plus the model’s inaccuracy. The former cannot be removed, and the latter is the only part the model can improve.
  3. Perplexity =exp⁡(loss)=\exp(\text{loss}). Bits-per-byte removes the effect of the tokenizer, so compare models on it rather than on perplexity.
  4. The direction of KL matters: pretraining and distillation take the expectation over the data (or the teacher), while the KL penalty in RLHF takes it over the policy’s own samples.

Quick self-check

1. When training a language model, the model assigns probability 0.250.25 to the true next token at some position. What is the cross-entropy loss at that position?

  • 0.250.25 nat
  • −ln⁡0.25≈1.386-\ln 0.25 \approx 1.386 nat
  • ln⁡0.25≈−1.386\ln 0.25 \approx -1.386 nat
  • 0.25ln⁡0.250.25 \ln 0.25 nat

The true distribution is one-hot, so H(p)=0H(p)=0 and the cross-entropy is −∑xp(x)ln⁡q(x)=−ln⁡q(correct token)-\sum_x p(x)\ln q(x) = -\ln q(\text{correct token}). A loss must be non-negative, so the version with the opposite sign is wrong, and 0.25ln⁡0.250.25\ln 0.25 is negative too.

2. A model has a loss of 2.02.0 nat/token. What is its perplexity?

  • 2.02.0
  • e2.0≈7.39e^{2.0}\approx 7.39
  • 22.0=42^{2.0} = 4
  • ln⁡2.0≈0.69\ln 2.0 \approx 0.69

Perplexity is the exponential eLe^{\mathcal{L}} of the loss in nats. You use 2L2^{\mathcal{L}} only when the loss is in bits.

3. Which of the following statements are correct? (select all that apply)

  • Cross-entropy is never smaller than entropy, that is, H(p,q)≥H(p)H(p,q)\ge H(p)
  • In general DKL(p ∥ q)≠DKL(q ∥ p)D_{KL}(p\,\Vert\,q)\ne D_{KL}(q\,\Vert\,p)
  • With enough training the cross-entropy loss can reach 0
  • Perplexity can be used directly to compare two models with different tokenizers

H(p,q)−H(p)=DKL(p ∥ q)≥0H(p,q)-H(p)=D_{KL}(p\,\Vert\,q)\ge 0, and KL is asymmetric. Natural language is random in itself, so the floor of the loss is the entropy of the data distribution, not 0. Different tokenizers have different token granularity, so compare bits-per-byte instead.

4. Why must a language model’s softmax never output exactly 0 for a token that appears in the data?

  • Because the softmax outputs must sum to more than 1
  • Because −log⁡q-\log q would be infinite, and so would the KL divergence and the loss
  • Because tokens with probability 0 cannot take part in backpropagation
  • Because the vocabulary size would shrink

The cross-entropy contains −log⁡q(x)-\log q(x). When q(x)→0q(x)\to 0 while xx really occurs in the data, the loss goes to infinity. The softmax output is always positive, which avoids exactly this.

Exercises:

  1. For a vocabulary of size V=128,256V=128{,}256, what are the loss (in nats) and the perplexity of a uniform prediction?
  2. Let p=(0.5,0.5)p=(0.5, 0.5) and q=(0.9,0.1)q=(0.9, 0.1). Compute DKL(p ∥ q)D_{KL}(p\,\Vert\,q) and DKL(q ∥ p)D_{KL}(q\,\Vert\,p) (in nats) and check that they are not equal.
  3. Model A has a perplexity of 7.39 (4 bytes per token on average) and model B has a perplexity of 2.72 (2 bytes per token). Which compresses better?
Reference answers
  1. The loss is ln⁡128256≈11.76\ln 128256\approx 11.76 nat and the perplexity is exactly 128256128256.
  2. DKL(p ∥ q)=0.5ln⁡0.50.9+0.5ln⁡0.50.1≈0.511D_{KL}(p\,\Vert\,q)=0.5\ln\frac{0.5}{0.9}+0.5\ln\frac{0.5}{0.1}\approx 0.511 and DKL(q ∥ p)=0.9ln⁡0.90.5+0.1ln⁡0.10.5≈0.368D_{KL}(q\,\Vert\,p)=0.9\ln\frac{0.9}{0.5}+0.1\ln\frac{0.1}{0.5}\approx 0.368, so they are not equal.
  3. The losses are ln⁡7.39=2.0\ln 7.39 = 2.0 and ln⁡2.72=1.0\ln 2.72 = 1.0 nat/token, and the BPB values are 2.0/ln⁡2/4=0.7212.0/\ln 2/4 = 0.721 and 1.0/ln⁡2/2=0.7211.0/\ln 2/2 = 0.721, so the two compress equally well.

Further reading

FAQ

What is the difference between cross-entropy and KL divergence?
Cross-entropy H(p, q) is the average amount of information needed to encode data from the true distribution p with a code built for q. KL divergence KL(p‖q) is the part that exceeds the optimal code, which is the entropy H(p), so H(p, q) = H(p) + KL(p‖q). In training, p is the fixed data distribution and H(p) does not depend on the model parameters, so minimizing cross-entropy and minimizing KL divergence are the same thing.
How are perplexity and cross-entropy loss related?
Perplexity is the exponential of the cross-entropy. With the loss in nats PPL = exp(loss), and with the loss in bits PPL = 2^loss. It can be read as the number of equally likely candidates the model is effectively choosing among; for a uniform distribution over a vocabulary of size V, the perplexity is exactly V.
Why do language models use cross-entropy as the training loss?
Because maximizing the log-likelihood of the training text is equivalent to minimizing the KL divergence between the data distribution and the model distribution. Cross-entropy also pairs with softmax to give a simple gradient (predicted probability minus the one-hot label) that is numerically stable. It has a direct compression meaning too, since a lower loss means fewer bits are needed to compress the same text with the model.
Why is KL divergence asymmetric, and what does it change in practice?
KL(p‖q) takes the expectation under p and penalizes q for putting too little probability where p has mass. KL(q‖p) takes the expectation under q and penalizes q for putting mass where p has none. The first tends to make q cover all modes of p, the second tends to make q chase a single mode. Pretraining and distillation use the first direction, while the KL penalty in RLHF uses the second.
What is bits-per-byte, and why is it better than perplexity for comparing models?
Bits-per-byte is the average number of bits the model needs per byte of text, equal to the loss per token (in bits) divided by the average number of bytes per token. Perplexity is per token, and different tokenizers put different amounts of text in a token, so the numbers are not comparable. Per byte, the denominator is the original text itself and no longer depends on the tokenizer.