Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsInformation Theory

Mutual information and perplexity

P1.E535 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Mutual information measures how much one thing tells you about another, and perplexity turns a language model's average loss into a count of effective choices, so the first picks splits and features and the second scores models.

  • A decision tree picks the split with the largest information gain, which is the mutual information between the split and the label. (P3.B3: Decision trees)
  • Language models are commonly compared by their perplexity, the exponential of the average next-token loss, on held-out text. (P10.G1: Evaluating LLMs, coming soon)
  • Classic n-gram language models were scored by perplexity long before neural ones. (P6.2: N-gram language models, coming soon)
  • Contrastive learning, which trains CLIP-style models, uses a loss that is tied to a lower bound on the mutual information between the two views. (P8.13: CLIP and contrastive image-text learning, coming soon)

Before this: Entropy, Cross-entropy, KL divergence, Joint, marginal and conditional probability

After this lesson you can

  • Compute the joint entropy H(X,Y)H(X,Y) and the conditional entropy H(Y∣X)=∑xp(x)H(Y∣X=x)H(Y\mid X)=\sum_x p(x)H(Y\mid X=x) from a joint table, use the chain rule H(X,Y)=H(X)+H(Y∣X)H(X,Y)=H(X)+H(Y\mid X), and explain why H(Y∣X)≤H(Y)H(Y\mid X)\le H(Y) on average although one particular observation can leave you more unsure
  • Define the mutual information I(X;Y)=H(Y)−H(Y∣X)=H(X)+H(Y)−H(X,Y)=KL(p(x,y) ∥ p(x)p(y))I(X;Y)=H(Y)-H(Y\mid X)=H(X)+H(Y)-H(X,Y)=\mathrm{KL}\bigl(p(x,y)\,\|\,p(x)p(y)\bigr), state that it is symmetric, at least 00, and 00 exactly for independent variables, and compute it for an independent pair, an exact copy, a noisy copy (0.5310.531 bits) and the weather and umbrella table of P1.D5
  • Read the Venn picture of two variables and say where it breaks (three variables), and explain why mutual information finds a dependence such as Y=X2Y=X^2 that the correlation misses, and why a decision tree's information gain (0.2780.278 bits in P1.E2) is a mutual information
  • Define perplexity as 2H2^{H} (or eH\mathrm{e}^{H} in nats), the effective number of equally likely choices; compute it for a fair die (66) and a loaded die (4.474.47); compute a language model's perplexity as the exponential of its average loss per token; and say why it compares models only on the same text with the same tokenizer

Two questions close this module. When you learn one thing, how much do you learn about another? And when a language model is unsure about the next token, how many tokens is it effectively choosing among?

The first is answered by the mutual information. It is the KL divergence of P1.E4 applied to a pair of variables. The second is answered by the perplexity, which is the entropy of P1.E2 turned back into a count: P1.E2 showed that 2H2^H is the size of the equally likely choice that is just as uncertain, and P1.E3 showed that a language model reports an average loss per token.

Two variables at once: joint entropy

P1.D5 described two variables with a table. Here is its table again. XX is the weather and YY is whether a person carries an umbrella.

YY = NoYY = YesTotal
XX = Sunny0.360.360.040.040.400.40
XX = Cloudy0.200.200.100.100.300.30
XX = Rainy0.060.060.240.240.300.30
Total0.620.620.380.3811

The joint entropy is the entropy of the table, treating each of the six cells as one outcome:

H(X,Y)=−∑x,yp(x,y)log⁡2p(x,y).H(X,Y)=-\sum_{x,y}p(x,y)\log_2p(x,y).

It is the average surprise of learning both values. For this table it is 2.2512.251 bits. The totals give the separate entropies: H(X)=1.571H(X)=1.571 bits for the weather (0.4,0.3,0.30.4,0.3,0.3) and H(Y)=0.958H(Y)=0.958 bits for the umbrella (0.62,0.380.62,0.38). Their sum is 2.5292.529, more than 2.2512.251, and P1.E2 promised exactly that: H(X,Y)≤H(X)+H(Y)H(X,Y)\le H(X)+H(Y). The gap, 0.2780.278 bits, is the subject of this lesson.

Conditional entropy: what is left after you look

Suppose you look at the sky first. If it is sunny, the umbrella distribution is (0.9,0.1)(0.9,0.1), because 0.36/0.40=0.90.36/0.40=0.9. That is an ordinary distribution with an ordinary entropy. The conditional entropy given a value is the entropy of the slice:

H(Y∣X=x)=−∑yp(y∣x)×log⁡2p(y∣x).\begin{aligned} H(Y\mid X=x)&=-\sum_y p(y\mid x)\\ &\qquad\times\log_2p(y\mid x). \end{aligned}

The three slices have 0.4690.469 bits (sunny, (0.9,0.1)(0.9,0.1)), 0.9180.918 bits (cloudy, (23,13)(\frac23,\frac13)) and 0.7220.722 bits (rainy, (0.2,0.8)(0.2,0.8)). Before you look you do not know which slice you will be in, so the uncertainty you expect to be left with is the average, weighted by how likely each slice is. That is the conditional entropy:

H(Y∣X)=∑xp(x) H(Y∣X=x).H(Y\mid X)=\sum_x p(x)\,H(Y\mid X=x).

Here it is 0.4×0.469+0.3×0.918+0.3×0.722=0.6800.4\times0.469+0.3\times0.918+0.3\times0.722=0.680 bits, against H(Y)=0.958H(Y)=0.958 bits before looking at the sky. Seeing the weather removes 0.958−0.680=0.2780.958-0.680=0.278 bits of uncertainty about the umbrella.

The conditional entropy fits with the joint entropy through the chain rule:

H(X,Y)=H(X)+H(Y∣X).H(X,Y)=H(X)+H(Y\mid X).

Learning the pair is the same as learning XX and then what is left of YY. Check: 1.571+0.680=2.2511.571+0.680=2.251. It also works in the other order, H(X,Y)=H(Y)+H(X∣Y)=0.958+1.293H(X,Y)=H(Y)+H(X\mid Y)=0.958+1.293. The reason is one line of algebra, shown in the box below, and it repeats along a sequence: the entropy of a text is the entropy of its first token, plus that of the second given the first, and so on. This is the sum of per-token surprises of P1.E1, averaged.

Go deeper Why the chain rule holds

Write the probability of a pair as p(x,y)=p(x) p(y∣x)p(x,y)=p(x)\,p(y\mid x) (P1.D5). Taking the logarithm turns the product into a sum, log⁡p(x,y)=log⁡p(x)+log⁡p(y∣x)\log p(x,y)=\log p(x)+\log p(y\mid x), and the surprise of the pair is the surprise of xx plus the surprise of yy given xx. Average each term over p(x,y)p(x,y). The first average is H(X)H(X), since summing p(x,y)p(x,y) over yy leaves p(x)p(x). The second is ∑xp(x)∑yp(y∣x)(−log⁡p(y∣x))=∑xp(x)H(Y∣X=x)=H(Y∣X)\sum_x p(x)\sum_y p(y\mid x)\bigl(-\log p(y\mid x)\bigr)=\sum_x p(x)H(Y\mid X=x)=H(Y\mid X). For nn variables the same step repeats: H(X1,…,Xn)=∑tH(Xt∣X1,…,Xt−1)H(X_1,\dots,X_n)=\sum_t H(X_t\mid X_1,\dots,X_{t-1}).

Looking helps on average, not every time

It is natural to expect that looking at something can only make you less unsure. On average that is true, and the section on mutual information below proves it. But a particular observation can leave you more unsure.

Take a machine. On a normal day (90%90\% of days) it never fails. On a stress-test day (10%10\%) it fails half the time. Let XX be the kind of day and YY be whether it fails. Overall the machine fails on 0.1×0.5=5%0.1\times0.5=5\% of days, so H(Y)=H(0.05)=0.286H(Y)=H(0.05)=0.286 bits. Now look at the day.

  • Normal day: the machine never fails, H(Y∣X=normal)=0H(Y\mid X=\text{normal})=0.
  • Stress-test day: a fair coin, H(Y∣X=stress)=1H(Y\mid X=\text{stress})=1 bit, more than the 0.2860.286 bits you had before looking.

The average is 0.9×0+0.1×1=0.10.9\times0+0.1\times1=0.1 bits, below 0.2860.286. So H(Y∣X)≤H(Y)H(Y\mid X)\le H(Y) holds, but H(Y∣X=x)≤H(Y)H(Y\mid X=x)\le H(Y) does not have to. The bad news arrived rarely, and the good news (a normal day, nothing to worry about) arrived often.

Mutual information

How much does XX tell you about YY? Count the uncertainty about YY before looking, H(Y)H(Y), and after looking, H(Y∣X)H(Y\mid X). The difference is the mutual information:

I(X;Y)=H(Y)−H(Y∣X).I(X;Y)=H(Y)-H(Y\mid X).

Substitute the chain rule, H(Y∣X)=H(X,Y)−H(X)H(Y\mid X)=H(X,Y)-H(X), to get a form that treats the two variables evenly:

I(X;Y)=H(X)+H(Y)−H(X,Y).\begin{aligned} I(X;Y)&=H(X)+H(Y)\\ &\quad-H(X,Y). \end{aligned}

The right side does not change when XX and YY swap places, so I(X;Y)=I(Y;X)I(X;Y)=I(Y;X): how much the weather tells you about the umbrella equals how much the umbrella tells you about the weather. For the table above, 0.958−0.680=1.571−1.293=0.2780.958-0.680=1.571-1.293=0.278 bits.

There is a third form, and it connects to P1.E4. If the variables were independent, the joint table would be the product of the marginals, p(x)p(y)p(x)p(y). The mutual information is the KL divergence from the real table to that product:

I(X;Y)=∑x,yp(x,y)log⁡2p(x,y)p(x) p(y).I(X;Y)=\sum_{x,y}p(x,y)\log_2\frac{p(x,y)}{p(x)\,p(y)}.

Read each term as the log of how many times more likely the pair is than independence would make it. For the weather table the six terms (in bits, rounded) are 0.1940.194, −0.077-0.077, 0.0210.021, −0.019-0.019, −0.098-0.098 and 0.2580.258, and they add to 0.2780.278. Sunny and no umbrella is more common than independence predicts (0.360.36 against 0.40×0.62=0.2480.40\times0.62=0.248), so it adds. Sunny and umbrella is rarer (0.040.04 against 0.1520.152), so it subtracts.

Because it is a KL divergence (P1.E4), three facts follow at once.

  • It is at least 00. This is also why H(Y∣X)≤H(Y)H(Y\mid X)\le H(Y) on average: I=H(Y)−H(Y∣X)≥0I=H(Y)-H(Y\mid X)\ge0.
  • It is 00 exactly when XX and YY are independent, since KL is 00 only when the two distributions are equal.
  • It is symmetric, unlike KL itself, as the middle form shows.

It is also at most min⁡(H(X),H(Y))\min\bigl(H(X),H(Y)\bigr): you cannot remove more uncertainty than there was. It is measured in bits with log⁡2\log_2 and in nats with ln⁡\ln, and nats equal bits times ln⁡2\ln2.

The Venn picture, drawn to scale

A classic picture draws H(X)H(X) and H(Y)H(Y) as two overlapping circles. The overlap is I(X;Y)I(X;Y). The left crescent is H(X∣Y)H(X\mid Y), what is left of XX after you see YY. The right crescent is H(Y∣X)H(Y\mid X). The whole union is H(X,Y)H(X,Y). Every identity above can be read off it: the union is the two crescents plus the overlap, and each circle is its crescent plus the overlap.

Circles cannot have exactly the right areas for every table, so the widget draws the same picture as three aligned bars, where every length is exactly the number of bits. The shared part is in the same place in the H(X)H(X) bar and the H(Y)H(Y) bar. Pick a preset, drag the flip probability, or edit the four cells of the joint table.

Two variables: what they share, drawn to scale

Joint table p(x, y). Totals are the marginals.
Y=0Y=1p(x)
X=00.450.050.5
X=10.450.050.5
p(y)0.90.11
H(X, Y) = 1.469H(X|Y)H(Y|X)H(X) = 1H(X|Y)H(Y) = 0.469H(Y|X)00.511.52

Length is in bits (axis 0 to 2). The shared part I(X; Y) sits in the same place in the H(X) bar and the H(Y) bar.

  • H(X | Y): left in X after seeing Y
  • I(X; Y): shared by X and Y
  • H(Y | X): left in Y after seeing X
H(X) = 1 bit
H(Y) = 0.469 bits
H(X | Y) = 1 bit
H(Y | X) = 0.469 bits
H(X, Y) = 1.469 bits
I(X; Y) = 0 bits = 0 nats
I = H(X) + H(Y) − H(X, Y) = 1 + 0.469 − 1.469 = 0

I(X; Y) = 0: the joint table equals the product of its marginals, so the two variables are independent. Seeing one tells you nothing about the other, and H(X, Y) = H(X) + H(Y).

The four sliders edit the joint table: raising one cell rescales the other three so that the table still adds up to 1. Values are rounded for display.

The entropies of two yes/no variables X and Y, drawn as three aligned bars on one axis from 0 to 2 bits: the bar for the joint entropy H(X, Y), the bar for H(X) and the bar for H(Y). Each bar is split into colored parts: H(X given Y) in blue, the mutual information I(X; Y) in green, shared by the H(X) and H(Y) bars, and H(Y given X) in pink. The joint table of the two variables is shown above the bars. Four presets set the table: independent, an exact copy, a noisy copy with a flip probability set by a slider, and a stress-test example. Four sliders edit the table cells directly. Readouts give all six quantities in bits, the mutual information in nats, and the identity I = H(X) + H(Y) - H(X, Y) with its numbers. A status line says in words what the current table means.

What to try:

  • Independent. The green part has length 00. The H(X,Y)H(X,Y) bar is the H(X)H(X) bar followed by the H(Y)H(Y) bar, so H(X,Y)=H(X)+H(Y)H(X,Y)=H(X)+H(Y) and the mutual information is 00.
  • Exact copy. The two crescents vanish and the circles coincide: H(X)=H(Y)=H(X,Y)=I=1H(X)=H(Y)=H(X,Y)=I=1 bit.
  • Noisy copy. Drag the flip probability ff from 00 to 0.50.5. At f=0.1f=0.1 the shared part is 0.5310.531 bits; it shrinks to 00 at f=0.5f=0.5, where the copy is pure noise. At f=1f=1 the copy is wrong every time, and flipping it back recovers XX exactly, so the shared part is 11 bit again.
  • Stress test. The table of the machine above (X=0X=0 is a normal day, X=1X=1 a stress-test day, Y=1Y=1 a failure). The crescent H(Y∣X)H(Y\mid X) is 0.10.1 bits, against H(Y)=0.286H(Y)=0.286, and the shared part is 0.1860.186.
  • Edit a cell. Raise one cell until all the probability is in it. Both variables become certain and everything is 00.

Three worked examples

Independent. A coin with P(heads)=0.9P(\text{heads})=0.9 and a fair die (P1.E2), thrown separately. The pair has H(X,Y)=0.469+2.585=3.054H(X,Y)=0.469+2.585=3.054 bits, so I=0.469+2.585−3.054=0I=0.469+2.585-3.054=0.

An exact copy. If YY is a copy of a fair coin XX, then H(Y∣X)=0H(Y\mid X)=0 and I(X;Y)=H(Y)−0=1I(X;Y)=H(Y)-0=1 bit. In general, when YY is determined by XX, I(X;Y)=H(Y)I(X;Y)=H(Y): the mutual information is all of the uncertainty of YY. (Then H(Y)≤H(X)H(Y)\le H(X), since a function of XX cannot be more uncertain than XX.)

A noisy copy. Let XX be a fair coin, and let YY copy it but flip it with probability f=0.1f=0.1. This is called a binary symmetric channel, the standard model of a noisy wire. The four pairs have probabilities 0.45,0.05,0.05,0.450.45,0.05,0.05,0.45, the example of P1.E2 with H(X,Y)=1.469H(X,Y)=1.469. Then

I(X;Y)=H(Y)−H(Y∣X)=1−H(0.1)=1−0.469=0.531 bits,\begin{aligned} I(X;Y)&=H(Y)-H(Y\mid X)\\ &=1-H(0.1)\\ &=1-0.469=0.531\text{ bits}, \end{aligned}

because given XX the only uncertainty left in YY is whether it was flipped. It matches H(X)+H(Y)−H(X,Y)=2−1.469=0.531H(X)+H(Y)-H(X,Y)=2-1.469=0.531. In general I=1−H(f)I=1-H(f) bits for a fair input:

  • f=0f=0: I=1I=1 bit.
  • f=0.05f=0.05: 0.7140.714 bits.
  • f=0.1f=0.1: 0.5310.531 bits.
  • f=0.2f=0.2: 0.2780.278 bits.
  • f=0.3f=0.3: 0.1190.119 bits.
  • f=0.5f=0.5: 00, since the copy is pure noise.

A copy that is right 99 times in 1010 still carries about half a bit of the one bit.

Mutual information versus correlation

The correlation of P1.D7 measures how well a straight line explains one variable from the other. A dependence that is not a line can give correlation 00.

Let XX be uniform on {−2,−1,0,1,2}\{-2,-1,0,1,2\} and let Y=X2Y=X^2, the table of P1.D5. The values of YY are 44 (probability 0.40.4), 11 (0.40.4) and 00 (0.20.2). The correlation is exactly 00, because the table is symmetric around x=0x=0. But YY is a function of XX, so H(Y∣X)=0H(Y\mid X)=0 and

I(X;Y)=H(Y)=H(0.4, 0.4, 0.2)=1.522 bits,\begin{aligned} I(X;Y)&=H(Y)\\ &=H(0.4,\,0.4,\,0.2)\\ &=1.522\text{ bits}, \end{aligned}

which is positive. Mutual information finds the dependence because it asks whether the joint table differs from the product at all, not whether a line fits.

The comparison cuts both ways. Mutual information is not signed (it does not say whether YY rises or falls with XX), is not on a scale from −1-1 to 11, and is harder to estimate from data (below). Correlation is the cheap first look. Mutual information is the right tool when the dependence may be curved or the variables are categories.

Go deeper Mutual information for continuous variables

For variables with densities, replace the sums by integrals: I(X;Y)=∬p(x,y)ln⁡p(x,y)p(x)p(y) dx dyI(X;Y)=\iint p(x,y)\ln\frac{p(x,y)}{p(x)p(y)}\,dx\,dy. Unlike the differential entropy of P1.E2, this stays non-negative and does not change if you rescale XX or YY, because the units cancel in the ratio. For two Gaussian variables with correlation ρ\rho it equals −12ln⁡(1−ρ2)-\frac12\ln(1-\rho^2) nats: 0.5110.511 nats (0.7370.737 bits) for ρ=0.8\rho=0.8, 00 for ρ=0\rho=0 and growing without bound as ρ\rho approaches ±1\pm1. So for jointly Gaussian pairs mutual information and correlation carry the same information. Beyond that case, estimating mutual information from a sample takes care: estimators bin the values or use neighbour distances, and the estimates are noisy.

Information gain in a decision tree

P1.E2 split 1010 examples, 55 positive and 55 negative, into two groups of 55, one with 44 positives and 11 negative, the other with 11 and 44. The information gain was 1−0.722=0.2781-0.722=0.278 bits. Now see it as a joint table of the feature (which group) and the label, with the counts divided by 1010:

label positivelabel negative
group A0.40.40.10.1
group B0.10.10.40.4

This is exactly the noisy copy with f=0.2f=0.2: the label agrees with the group 80%80\% of the time. The label’s entropy is H(Y)=1H(Y)=1 bit, and what is left after learning the group is H(Y∣X)=H(0.2)=0.722H(Y\mid X)=H(0.2)=0.722 bits, so I(X;Y)=1−0.722=0.278I(X;Y)=1-0.722=0.278 bits (the table for f=0.2f=0.2 above). The information gain of a split is the mutual information between the feature and the label, measured on the data. The word “gain” says what it is: the uncertainty about the label that the feature removes. A tree picks the split with the largest one (P3.B3). Many libraries default to the Gini index instead, a related measure.

(The weather table above also has I=0.278I=0.278 bits. That is a coincidence of rounding: the two tables differ in the fourth digit, 0.27840.2784 and 0.27810.2781.)

Feature selection uses the same idea: rank the features by their estimated mutual information with the label and keep the highest. Three cautions apply.

  • A sample gives a positive estimate for independent variables. Two independent fair coins, judged from 1010 samples, have an average estimated II of about 0.090.09 bits, and the estimate is above 00 in about 88%88\% of such samples. The estimate settles toward 00 only as the samples grow.
  • Redundant features score alike. A feature and a copy of it both have a high score, and the second adds nothing.
  • A feature can matter only together with another. If the label is the XOR of two fair independent bits, each bit alone has I=0I=0 with the label, yet the pair determines it completely (11 bit). A one-feature-at-a-time score misses this. The Go-deeper box on three variables explains why.
Go deeper Processing cannot add information

Suppose XX is sent through a noisy step to give YY, and YY through a second noisy step to give ZZ, so that ZZ depends on XX only through YY (a Markov chain, X→Y→ZX\to Y\to Z). The data processing inequality says I(X;Z)≤I(X;Y)I(X;Z)\le I(X;Y): no step that only uses YY can recover information about XX that YY lost. Example: two cascaded flips of probability 0.10.1 each give a net flip probability of 2×0.1×0.9=0.182\times0.1\times0.9=0.18 (the pair is wrong when exactly one of the two flips happens), so I(X;Z)=1−H(0.18)=0.320I(X;Z)=1-H(0.18)=0.320 bits, below 0.5310.531.

For machine learning it says that a function of the input cannot have more information about the label than the input has. A learned representation is useful when it keeps the part about the label in a form that is easy to use, not because it creates information.

Go deeper Three variables: where the Venn picture misleads

The two-circle picture is correct. Extending it to three circles tempts one to read an area in the middle as the information shared by all three, and that area can be negative. Take two independent fair bits XX and YY and let Z=X⊕YZ=X\oplus Y, which is 11 when they differ. Any two of the three are independent: I(X;Y)=I(X;Z)=0I(X;Y)=I(X;Z)=0. But given ZZ, learning XX tells you YY exactly: I(X;Y∣Z)=1I(X;Y\mid Z)=1 bit. The central region of the three-circle picture would be I(X;Y)−I(X;Y∣Z)=0−1=−1I(X;Y)-I(X;Y\mid Z)=0-1=-1 bit, and an area cannot be negative. This quantity is called the interaction information (or co-information; books differ in its sign). Use the diagram for two variables. For three or more, work with the formulas.

From entropy to perplexity

P1.E2 showed that 2H2^H is the size of the fair choice that is as uncertain as the distribution. The name for it is the perplexity:

perplexity=2H=eH in nats.\text{perplexity}=2^{H}=\mathrm{e}^{H\text{ in nats}}.

The two are the same number, because the base cancels: 2H in bits=eH in nats2^{H\text{ in bits}}=\mathrm{e}^{H\text{ in nats}}. A fair die has H=log⁡26=2.585H=\log_26=2.585 bits and perplexity exactly 66: six equally likely choices. A loaded die with face probabilities (0.5,0.1,0.1,0.1,0.1,0.1)(0.5,0.1,0.1,0.1,0.1,0.1) has H=2.161H=2.161 bits (1.4981.498 nats) and perplexity 4.474.47. It is about as hard to predict as a fair die with between four and five faces. A die that lands on one face with probability 0.950.95 and on the others with 0.010.01 each has perplexity 1.321.32, close to a single choice. For a distribution on KK outcomes the perplexity lies between 11 (one outcome is certain) and KK (all equally likely).

The perplexity of a die: how many equally likely faces?

00.510.1710.1720.1730.1740.1750.176

Horizontal: the six faces. Vertical: probability. Dragging one bar rescales the others so that the total stays 1.

Perplexity on a scale from 1 to 6 effective faces
entropy H = 2.585 bits
in nats: 1.792
perplexity 2H = eH in nats = 6

All 6 faces are equally likely, so H = log₂ 6 = 2.585 bits and the perplexity is exactly 6, the largest possible for six faces.

Drag on the chart (it snaps to 0.01), or Tab to a bar and use the arrow keys (0.01), Page Up and Page Down (0.1), Home (0) and End (1). Values are rounded for display.

The perplexity of a six-faced die. In the first panel you reshape the six face probabilities with draggable bars (the other faces rescale so the total stays 1) or with presets for a fair die, a loaded die, a nearly certain die and a die with two faces. Readouts give the entropy H in bits and nats and the perplexity 2 to the power H, and a scale from 1 to 6 marks the perplexity. In the second panel the die is the true one and you edit a model q of it. A short line on each bar marks the true probability. Readouts give the perplexity of the truth, the perplexity of the model, which is 2 to the power of the cross-entropy H(p, q), the cross-entropy and the KL divergence. A model that gives a face probability 0 where the true probability is positive has infinite perplexity.

What to try:

  • Fair. Perplexity 66. Move one bar up: it falls below 66, and it is 66 again only when all six bars are equal.
  • Two faces. Four faces have probability 00 and add nothing, so the perplexity is exactly 22, like a coin. A face that can never happen does not count as a choice.
  • Nearly certain. The perplexity is 1.321.32.
  • A model of the die. Make the truth the loaded die, open the model panel and press “Fair die”: the model’s perplexity is exactly 66. A model that guesses uniformly has perplexity equal to the number of outcomes, whatever the truth is. “Face 1 underrated” gives 7.457.45: it rates the most likely face lowest, which is worse than guessing uniformly. “Same as the truth” gives 4.474.47, the lowest possible. “Rules out face 6” gives infinity.

Perplexity of a model

A model qq for data from pp is scored by its cross-entropy H(p,q)H(p,q) (P1.E3), and its perplexity is 2H(p,q)2^{H(p,q)}. Using H(p,q)=H(p)+KL(p ∥ q)H(p,q)=H(p)+\mathrm{KL}(p\,\|\,q) (P1.E4):

2H(p,q)=2H(p)⋅2KL(p∥q).2^{H(p,q)}=2^{H(p)}\cdot2^{\mathrm{KL}(p\|q)}.

The first factor is the perplexity of the truth itself, the best any model can do. The second is at least 11, and is the price of wrong probabilities. For the loaded die and the “Face 1 underrated” model of the widget, 4.47×1.667=7.454.47\times1.667=7.45.

For text there is no list of true probabilities, only a sample of text. P1.E3 showed that a language model’s loss on it is the average negative log-probability per token (the average negative log-likelihood of P1.D10), in nats for the usual frameworks. The perplexity is its exponential:

perplexity=exp⁡(−1T∑t=1Tln⁡p(xt∣x<t)).\begin{aligned} \text{perplexity}&=\exp\Bigl(-\frac1T\sum_{t=1}^{T}\\ &\qquad\ln p\bigl(x_t\mid x_{\lt t}\bigr)\Bigr). \end{aligned}

The example of P1.E3: three tokens that the model gave probabilities 0.50.5, 0.250.25 and 0.1250.125. The average loss is 1.3861.386 nats, and e1.386=4\mathrm{e}^{1.386}=4. The model is as unsure as a fair choice among 44 tokens at each step, on average. Another reading: perplexity is the geometric mean of 1/p1/p over the tokens, (2×4×8)1/3=4(2\times4\times8)^{1/3}=4.

  • It is at least 11, because each probability is at most 11. It is 11 only if the model gives every token of the text probability 11.
  • Lower is better, on the same text.
  • A uniform guess has perplexity equal to the vocabulary size: a model with a vocabulary of 50,00050{,}000 tokens that spreads its probability evenly has perplexity 50,00050{,}000.
  • A probability of 00 on a token that occurs makes it infinite. Classic n-gram models need smoothing for this reason (P6.2). A neural network ending in a softmax (P3.A8) gives every token a positive probability.

What perplexity can and cannot tell you

It compares models on the same text and the same tokenizer. The loss is an average per token, and the number of tokens depends on how the text is cut. Cut into small pieces (characters, say) and each piece is easier to predict, so the per-token perplexity is lower, although the same text is being modelled. If model A uses one tokenizer and model B another, a lower number for A says nothing about which model is better. Normalizing by something that does not depend on the tokenizer, such as the number of characters, words or bytes in the text, makes the numbers comparable. A model with perplexity 44 per token on a text with 1.51.5 tokens per word has perplexity 41.5=84^{1.5}=8 per word.

Go deeper Converting perplexity between tokens and words

The total negative log-probability of the text does not change when it is cut differently, only the number it is divided by. Say a model has per-token perplexity PP on a text of NtokN_{\text{tok}} tokens and NwordN_{\text{word}} words. The total is Ntokln⁡PN_{\text{tok}}\ln P nats, so the per-word perplexity is exp⁡(Ntokln⁡P / Nword)=PNtok/Nword\exp\bigl(N_{\text{tok}}\ln P\,/\,N_{\text{word}}\bigr)=P^{N_{\text{tok}}/N_{\text{word}}}. For P=4P=4 and 1.51.5 tokens per word, 41.5=84^{1.5}=8. The same calculation with bits per character or bits per byte uses the total in bits divided by the number of characters or bytes, and gives a number that two models can share even when their tokenizers differ. Tokenizers are the subject of P10.A2.

It depends on the text. A model can have a low perplexity on one kind of text and a high one on another. If the test text also appeared in the training data, the perplexity is too good to be true, which is called contamination (P10.G1).

It is not quality. It scores how well a model predicts the next token of a reference text. It does not say whether the answers are true, helpful or safe, and a model with a worse perplexity can be the more useful one. Perplexity is one tool for comparing models; benchmarks, human ratings and task tests are the others (P10.G1).

Where these ideas show up

Language-model evaluation. Pretraining minimizes the average next-token loss (P10.A1), and the perplexity of held-out text is that loss’s exponential. It is used to follow training, to compare checkpoints and to compare sizes of the same model family, on the same text and tokenizer (P10.G1). Tokenizer effects are in P10.A2 and P10.A3, and n-gram models in P6.2.

Decision trees and feature selection. Information gain is mutual information (above and P3.B3).

Representation learning. Contrastive learning, behind CLIP-style models (P8.13), contrastive self-supervised vision such as SimCLR (P5.16) and embedding models (P10.E4), trains a model to pick out the true partner of an example among NN candidates, with a cross-entropy loss over the candidates called InfoNCE. The paper that introduced it (van den Oord and colleagues, 2018) shows that, in expectation and under its assumptions, log⁡N\log N minus this loss is a lower bound on the mutual information between the two views. Two consequences: lowering the loss raises a lower bound on the mutual information, and the bound cannot exceed log⁡N\log N, so a small batch limits it. This is a preview. P8.13 does the training.

The information bottleneck is a framework that asks a representation to keep the information about a label and discard the rest about the input. It is named here only, as a place that the data processing inequality leads.

Try it

Try it: joint and conditional entropy, mutual information and perplexity

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The weather line prints H(X)=1.571H(X)=1.571, H(Y)=0.958H(Y)=0.958, H(X,Y)=2.251H(X,Y)=2.251, H(Y∣X)=0.680H(Y\mid X)=0.680, H(X∣Y)=1.293H(X\mid Y)=1.293 and I=0.278I=0.278. The independent line has I=0I=0, the copy has I=1I=1 and the noisy copy has I=0.531I=0.531. The KL form gives 0.2780.278 for the weather table, the same number. The Y=X2Y=X^2 lines show a correlation of 00 but I=1.522I=1.522. The die lines print the perplexities 66, 4.4724.472 and 22, and the last line prints 1.3861.386 nats per token and perplexity 44. Change the weather table (keep it adding to 11) and see II move. Try a table whose rows are all equal: II is 00.

Intuition, math and code at a glance

Intuition

Mutual information is the part of the uncertainty that two variables share: what you learn about one by looking at the other. It is 00 if looking tells you nothing, and it is as large as the whole uncertainty when one variable determines the other. Perplexity is the entropy turned back into a count: how many equally likely options would be as hard to guess. A language model with perplexity 2020 is as unsure at each step as someone choosing fairly among 2020 tokens (often pieces of words).

Math

I(X;Y)=H(X)+H(Y)−H(X,Y)=H(Y)−H(Y∣X)=KL(p(x,y)∥ p(x)p(y))≥0\begin{aligned} I(X;Y)&=H(X)+H(Y)\\ &\quad-H(X,Y)\\ &=H(Y)-H(Y\mid X)\\ &=\mathrm{KL}\bigl(p(x,y)\\ &\qquad\|\,p(x)p(y)\bigr)\ge0 \end{aligned}H(X,Y)=H(X)+H(Y∣X)perplexity=2H=eH in nats\begin{aligned} H(X,Y)&=H(X)+H(Y\mid X)\\ \text{perplexity}&=2^{H}=\mathrm{e}^{H\text{ in nats}} \end{aligned}
  • II is symmetric, at least 00, and 00 exactly for independent variables; I≤min⁡(H(X),H(Y))I\le\min\bigl(H(X),H(Y)\bigr).
  • H(Y∣X)≤H(Y)H(Y\mid X)\le H(Y) on average, though H(Y∣X=x)H(Y\mid X=x) can exceed H(Y)H(Y).
  • For a noisy copy of a fair coin with flip probability ff, I=1−H(f)I=1-H(f).
  • Model perplexity is exp⁡\exp of the average loss per token, and 2H(p)⋅2KL(p∥q)2^{H(p)}\cdot2^{\mathrm{KL}(p\|q)} for a model qq of pp.

Interview questions. Is mutual information the same as correlation? No: it catches any dependence, and it is 00 only for independent variables. Can conditioning increase entropy? A particular observation can; on average it cannot. Why can’t you compare perplexities across tokenizers? The average is per token, and the number of tokens differs. What is the perplexity of a uniform guess? The number of outcomes.

Code

Mutual information from a joint table in NumPy, and the perplexity of a language model from its loss. In PyTorch, torch.exp(loss) gives the perplexity when loss is the mean cross-entropy in nats per token (the default of CrossEntropyLoss with mean reduction).

import numpy as np

def mutual_information(joint):              # bits; joint[x, y] adds to 1
    J = np.asarray(joint, float)
    prod = np.outer(J.sum(1), J.sum(0))
    m = J > 0
    return float((J[m] * np.log2(J[m] / prod[m])).sum())

def perplexity(log_probs):                  # natural-log probabilities of the true tokens
    return float(np.exp(-np.mean(log_probs)))

print(mutual_information([[0.45, 0.05], [0.05, 0.45]]))       # about 0.531
print(perplexity(np.log([0.5, 0.25, 0.125])))                 # 4.0

Common mistakes

Check your understanding

  1. Which expression equals the mutual information I(X;Y)I(X;Y) for any two discrete variables?

  2. XX is uniform on {−1,0,1}\{-1,0,1\} and Y=X2Y=X^2. The correlation of XX and YY is 00. What can be said about I(X;Y)I(X;Y)?

  3. A machine fails on 5%5\% of days overall. Knowing that today is a stress-test day makes the failure uncertainty larger than before (from 0.2860.286 to 11 bit). Which statement is still correct?

  4. A language model has a perplexity of 88 on a held-out text. What does that say?

  5. Model A has perplexity 1212 on a text with its tokenizer and model B has perplexity 1515 on the same text with a different tokenizer. What follows?

Exercises

  1. A joint table has p(0,0)=0.3p(0,0)=0.3, p(0,1)=0.1p(0,1)=0.1, p(1,0)=0.1p(1,0)=0.1, p(1,1)=0.5p(1,1)=0.5. Find H(X)H(X), H(X,Y)H(X,Y) and I(X;Y)I(X;Y) in bits.
    Show answerThe marginals are (0.4,0.6)(0.4,0.6) for XX and the same for YY, so H(X)=H(Y)=0.971H(X)=H(Y)=0.971 bits. The four cells give H(X,Y)=1.685H(X,Y)=1.685 bits. Then I=0.971+0.971−1.685=0.256I=0.971+0.971-1.685=0.256 bits, and H(Y∣X)=1.685−0.971=0.715H(Y\mid X)=1.685-0.971=0.715 bits.
  2. A fair coin is copied through a binary symmetric channel with flip probability 0.250.25. Find I(X;Y)I(X;Y).
    Show answerI=1−H(0.25)=1−0.811=0.189I=1-H(0.25)=1-0.811=0.189 bits.
  3. Find the perplexity of the source with probabilities 12,14,18,18\frac12,\frac14,\frac18,\frac18.
    Show answerH=1.75H=1.75 bits, so the perplexity is 21.75=3.362^{1.75}=3.36, a little below 44 outcomes.
  4. A language model has an average loss of 2.32.3 nats per token. What is its perplexity, and what is its loss in bits?
    Show answere2.3=9.97\mathrm{e}^{2.3}=9.97, about 1010. In bits the loss is 2.3/ln⁡2=3.322.3/\ln2=3.32, and 23.32=9.972^{3.32}=9.97 again.
  5. A model has perplexity 2020 per token on a text that has 1.31.3 tokens per word. What is its perplexity per word?
    Show answer201.3=49.120^{1.3}=49.1.
  6. A program reports an estimated mutual information of −0.1-0.1 bits. What does that tell you?
    Show answerThe true value is never negative, so the number reveals a mistake, for example marginals computed from different data than the joint, or a table that does not add to 11. (Some estimators can return small negative values from noise, and then the right reading is “about 00”.)
  7. A label is the XOR of two fair independent bits AA and BB. Find I(A;label)I(A;\text{label}) and I((A,B);label)I((A,B);\text{label}).
    Show answerKnowing AA alone leaves the label a fair coin, so I(A;label)=0I(A;\text{label})=0, and the same for BB. Knowing both determines the label, so I((A,B);label)=H(label)=1I((A,B);\text{label})=H(\text{label})=1 bit. Ranking features one at a time would drop both.
  8. XX is uniform on {−1,0,1}\{-1,0,1\} and Y=X2Y=X^2. Find the correlation and the mutual information.
    Show answerThe correlation is 00, because E[XY]=E[X3]=0\mathbb{E}[XY]=\mathbb{E}[X^3]=0 and E[X]=0\mathbb{E}[X]=0. Since YY is determined by XX, I=H(Y)=H(13,23)=0.918I=H(Y)=H(\frac13,\frac23)=0.918 bits.

Next: Module 1F turns from information to optimization. P1.F1 asks what it means to minimize a function, the idea behind training every model in this course. The ideas here return in P3.B3 (decision trees), P6.2 (perplexity of n-gram models), P8.13 (contrastive learning) and P10.G1 (evaluating language models).

Key takeaways

  • The joint entropy H(X,Y)H(X,Y) is the average surprise of the pair. The conditional entropy H(Y∣X)=∑xp(x)H(Y∣X=x)H(Y\mid X)=\sum_x p(x)H(Y\mid X=x) is the uncertainty left in YY after you see XX, averaged over XX. The chain rule H(X,Y)=H(X)+H(Y∣X)H(X,Y)=H(X)+H(Y\mid X) holds for any two variables. For the weather and umbrella table of P1.D5, 1.571+0.680=2.2511.571+0.680=2.251 bits.
  • On average, seeing XX cannot increase the uncertainty about YY: H(Y∣X)≤H(Y)H(Y\mid X)\le H(Y), with equality exactly when the two are independent. A single observation can still increase it: on a rare stress-test day the machine of the lesson fails half the time, which is more uncertain than its usual 0.2860.286 bits, yet the average over days is 0.10.1 bits.
  • The mutual information I(X;Y)=H(Y)−H(Y∣X)=H(X)+H(Y)−H(X,Y)I(X;Y)=H(Y)-H(Y\mid X)=H(X)+H(Y)-H(X,Y) is the uncertainty about one variable that the other removes. It equals KL(p(x,y) ∥ p(x)p(y))\mathrm{KL}\bigl(p(x,y)\,\|\,p(x)p(y)\bigr), so it is at least 00, symmetric, and 00 exactly when the variables are independent. It is 00 for independent variables, H(X)H(X) for an exact copy, and 1−H(0.1)=0.5311-H(0.1)=0.531 bits for a fair coin copied with a flip probability of 0.10.1.
  • The Venn picture (two overlapping circles for H(X)H(X) and H(Y)H(Y), with the overlap I(X;Y)I(X;Y)) is correct for two variables and misleading for three: the shared amount of three variables can be negative (two fair coins and their XOR).
  • Correlation sees only straight-line dependence. For XX uniform on {−2,−1,0,1,2}\{-2,-1,0,1,2\} and Y=X2Y=X^2 the correlation is 00 but I(X;Y)=1.522I(X;Y)=1.522 bits. The information gain of a decision-tree split is the mutual information between the split and the label: 0.2780.278 bits for the split of P1.E2. Mutual information estimated from a small sample is almost always above 00 even for independent variables.
  • Perplexity is 2H2^{H} (or eH\mathrm{e}^{H} for HH in nats): the size of the fair choice that is equally uncertain. A fair die has perplexity 66, a loaded die (0.5,0.1,0.1,0.1,0.1,0.1)(0.5,0.1,0.1,0.1,0.1,0.1) has 4.474.47. A language model's perplexity is e\mathrm{e} to the power of its average loss per token; it is at least 11, lower is better, and it equals 2H(p)⋅2KL(p∥q)2^{H(p)}\cdot2^{\mathrm{KL}(p\|q)}.
  • Perplexity compares models only on the same text and the same tokenizer, because it is measured per token and the number of tokens depends on how the text is cut. It scores how well a model predicts text, not whether its answers are correct or useful.
Found a mistake? Tell us