# 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.

- URL: https://dmxsf.com/en/wiki/foundations/information-theory/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-08
- Tags: Language modeling, Pretraining

## 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.

## 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 $p$ with a code designed for $q$, 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)$ happens, the **information** it carries (also called surprisal) is

$$
I(x) = -\log p(x)
$$

The rarer the event, the more surprising it is. A certain event ($p=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) = -\sum_x p(x)\log p(x) = \mathbb{E}_{x\sim p}\big[-\log p(x)\big]
$$

By convention $0\log 0 = 0$. With base-2 logarithms the unit is the bit, with base $e$ it is the nat, and the two differ by a constant: $1\ \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):

| Distribution | Entropy | Intuition |
| --- | --- | --- |
| Fair coin $(0.5, 0.5)$ | 1 | Every outcome is completely unpredictable |
| Biased coin $(0.9, 0.1)$ | 0.469 | Mostly heads, so little surprise |
| Eight equally likely outcomes | 3 | $\log_2 8 = 3$ |
| A certain outcome $(1, 0)$ | 0 | No 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)$ bits and can be made to stay below $H(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 $p$, but your coding scheme was designed for another distribution $q$: events you consider likely get short codewords and events you consider unlikely get long ones. The average cost per symbol is

$$
H(p, q) = -\sum_x p(x)\log q(x)
$$

This is the **cross-entropy**. When $q = p$ it equals the entropy $H(p)$, and the further $q$ strays from $p$, 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):

$$
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**: $D_{KL}(p\,\Vert\,q)\ge 0$ (Gibbs' inequality), with equality if and only if $p = q$.
2. **Asymmetric**: in general $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 $q$ is 0 anywhere $p$ has probability, then $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:

$$
\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 $p$, the bottom group sets the model's prediction $q$, and the case selector jumps to a few typical situations.

1. **The model is exact**: with $q=p$ the KL is 0 and the cross-entropy drops to the entropy $H(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 $q$ is close to uniform the cross-entropy is exactly $\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 $p$ is one-hot, $H(p)=0$ and the cross-entropy is just $-\ln q(\text{correct answer})$, here $-\ln 0.6 = 0.511$. In this case $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, \dots)$ and the model puts 90% on one of them. $D_{KL}(p\,\Vert\,q) = 0.829$ is larger than $D_{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 $p_{\text{data}}$ and let the model be $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_\theta(x_t\mid x_{<t})$ (see [From Language Modeling to Next-Token Prediction](https://dmxsf.com/en/wiki/foundations/next-token-prediction/)). Averaged over a large amount of text, by the law of large numbers it converges to

$$
\mathcal{L}(\theta) \;\to\; H(p_{\text{data}}, q_\theta) = H(p_{\text{data}}) + D_{KL}(p_{\text{data}}\,\,\Vert\,\,q_\theta)
$$

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

- **Minimizing the average negative log-likelihood, maximum likelihood estimation, and minimizing $D_{KL}(p_{\text{data}}\,\Vert\,q_\theta)$ are three names for the same thing.**
- **The loss has a floor of $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 $E$ 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](https://dmxsf.com/en/wiki/pretraining/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:

$$
\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 $V$, $H=\ln V$ and $\mathrm{PPL}=V$. Llama 3's vocabulary has 128,256 tokens, so a randomly initialized model starts with a loss of about $\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:

$$
\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

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

| Scenario | Direction | Meaning |
| --- | --- | --- |
| Pretraining, SFT | $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 distillation | $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 / DPO | $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_\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](https://dmxsf.com/en/wiki/post-training/preference-optimization/).

## Hands-on code

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

```python
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:

```text
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 $p$ with $q$. KL divergence is the difference between the two, non-negative and asymmetric.
2. $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(\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.25$ to the true next token at some position. What is the cross-entropy loss at that position?**

- [ ] $0.25$ nat
- [x] $-\ln 0.25 \approx 1.386$ nat
- [ ] $\ln 0.25 \approx -1.386$ nat
- [ ] $0.25 \ln 0.25$ nat

> The true distribution is one-hot, so $H(p)=0$ and the cross-entropy is $-\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.25\ln 0.25$ is negative too.

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

- [ ] $2.0$
- [x] $e^{2.0}\approx 7.39$
- [ ] $2^{2.0} = 4$
- [ ] $\ln 2.0 \approx 0.69$

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

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

- [x] Cross-entropy is never smaller than entropy, that is, $H(p,q)\ge H(p)$
- [x] In general $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)=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
- [x] Because $-\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)$. When $q(x)\to 0$ while $x$ 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{,}256$, what are the loss (in nats) and the perplexity of a uniform prediction?
2. Let $p=(0.5, 0.5)$ and $q=(0.9, 0.1)$. Compute $D_{KL}(p\,\Vert\,q)$ and $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?

<details>
<summary>Reference answers</summary>

1. The loss is $\ln 128256\approx 11.76$ nat and the perplexity is exactly $128256$.
2. $D_{KL}(p\,\Vert\,q)=0.5\ln\frac{0.5}{0.9}+0.5\ln\frac{0.5}{0.1}\approx 0.511$ and $D_{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$ and $\ln 2.72 = 1.0$ nat/token, and the BPB values are $2.0/\ln 2/4 = 0.721$ and $1.0/\ln 2/2 = 0.721$, so the two compress equally well.

</details>

## Further reading

- Next steps: cross-entropy and perplexity in [From Language Modeling to Next-Token Prediction](https://dmxsf.com/en/wiki/foundations/next-token-prediction/), loss curves in [Scaling Laws](https://dmxsf.com/en/wiki/pretraining/scaling-laws/), and the KL constraint in [Preference Optimization](https://dmxsf.com/en/wiki/post-training/preference-optimization/).
- C. E. Shannon, [A Mathematical Theory of Communication](https://doi.org/10.1002/j.1538-7305.1948.tb01338.x), Bell System Technical Journal, 1948: the original source for entropy and the source coding theorem.
- T. M. Cover and J. A. Thomas, *Elements of Information Theory* (Wiley): the standard textbook on entropy, KL divergence and the coding theorems.
- Hoffmann et al., [Training Compute-Optimal Large Language Models](https://arxiv.org/abs/2203.15556) (Chinchilla, 2022): the parametric form of the loss curve and the constant term $E$.
- Hinton et al., [Distilling the Knowledge in a Neural Network](https://arxiv.org/abs/1503.02531) (2015): training a student on the teacher's soft labels.
- Rafailov et al., [Direct Preference Optimization](https://arxiv.org/abs/2305.18290) (2023) and Ouyang et al., [InstructGPT](https://arxiv.org/abs/2203.02155) (2022): the KL penalty term in the objective.
- Ho et al., [Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239) (DDPM, 2020); [paper breakdown](https://dmxsf.com/en/blog/ddpm-denoising-diffusion-probabilistic-models/): a generative model trained on a variational bound, a sum of KL terms.
- Lipman et al., [Flow Matching for Generative Modeling](https://arxiv.org/abs/2210.02747) (2022); [paper breakdown](https://dmxsf.com/en/blog/flow-matching-for-generative-modeling/): generative modeling written as regression onto a velocity field.
- Hafner et al., [Mastering Diverse Domains through World Models](https://arxiv.org/abs/2301.04104) (DreamerV3, 2023); [paper breakdown](https://dmxsf.com/en/blog/dreamerv3-mastering-diverse-domains-through-world-models/): regression recast as cross-entropy over exponentially spaced bins (twohot encoding), which decouples gradient size from target size.

## Companion code

[Next-token prediction and information theory](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/next-token-prediction): Bigram counts on the page's toy corpus, entropy, cross-entropy and KL divergence checked against each other, character n-grams on Shakespeare until the counts run out, and a neural bigram that learns the count table by gradient descent.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/next-token-prediction`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/next-token-prediction/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/next-token-prediction/README.en.md)
- [`information.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/foundations/information.py)
- [`language_model.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/foundations/language_model.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#next-token-prediction)

## 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.
