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 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. is the weather and is whether a person carries an umbrella.
| = No | = Yes | Total | |
|---|---|---|---|
| = Sunny | |||
| = Cloudy | |||
| = Rainy | |||
| Total |
The joint entropy is the entropy of the table, treating each of the six cells as one outcome:
It is the average surprise of learning both values. For this table it is bits. The totals give the separate entropies: bits for the weather () and bits for the umbrella (). Their sum is , more than , and P1.E2 promised exactly that: . The gap, 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 , because . That is an ordinary distribution with an ordinary entropy. The conditional entropy given a value is the entropy of the slice:
The three slices have bits (sunny, ), bits (cloudy, ) and bits (rainy, ). 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:
Here it is bits, against bits before looking at the sky. Seeing the weather removes bits of uncertainty about the umbrella.
The conditional entropy fits with the joint entropy through the chain rule:
Learning the pair is the same as learning and then what is left of . Check: . It also works in the other order, . 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 (P1.D5). Taking the logarithm turns the product into a sum, , and the surprise of the pair is the surprise of plus the surprise of given . Average each term over . The first average is , since summing over leaves . The second is . For variables the same step repeats: .
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 ( of days) it never fails. On a stress-test day () it fails half the time. Let be the kind of day and be whether it fails. Overall the machine fails on of days, so bits. Now look at the day.
- Normal day: the machine never fails, .
- Stress-test day: a fair coin, bit, more than the bits you had before looking.
The average is bits, below . So holds, but 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 tell you about ? Count the uncertainty about before looking, , and after looking, . The difference is the mutual information:
Substitute the chain rule, , to get a form that treats the two variables evenly:
The right side does not change when and swap places, so : how much the weather tells you about the umbrella equals how much the umbrella tells you about the weather. For the table above, 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, . The mutual information is the KL divergence from the real table to that product:
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 , , , , and , and they add to . Sunny and no umbrella is more common than independence predicts ( against ), so it adds. Sunny and umbrella is rarer ( against ), so it subtracts.
Because it is a KL divergence (P1.E4), three facts follow at once.
- It is at least . This is also why on average: .
- It is exactly when and are independent, since KL is only when the two distributions are equal.
- It is symmetric, unlike KL itself, as the middle form shows.
It is also at most : you cannot remove more uncertainty than there was. It is measured in bits with and in nats with , and nats equal bits times .
The Venn picture, drawn to scale
A classic picture draws and as two overlapping circles. The overlap is . The left crescent is , what is left of after you see . The right crescent is . The whole union is . 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 bar and the bar. Pick a preset, drag the flip probability, or edit the four cells of the joint table.
What to try:
- Independent. The green part has length . The bar is the bar followed by the bar, so and the mutual information is .
- Exact copy. The two crescents vanish and the circles coincide: bit.
- Noisy copy. Drag the flip probability from to . At the shared part is bits; it shrinks to at , where the copy is pure noise. At the copy is wrong every time, and flipping it back recovers exactly, so the shared part is bit again.
- Stress test. The table of the machine above ( is a normal day, a stress-test day, a failure). The crescent is bits, against , and the shared part is .
- Edit a cell. Raise one cell until all the probability is in it. Both variables become certain and everything is .
Three worked examples
Independent. A coin with and a fair die (P1.E2), thrown separately. The pair has bits, so .
An exact copy. If is a copy of a fair coin , then and bit. In general, when is determined by , : the mutual information is all of the uncertainty of . (Then , since a function of cannot be more uncertain than .)
A noisy copy. Let be a fair coin, and let copy it but flip it with probability . This is called a binary symmetric channel, the standard model of a noisy wire. The four pairs have probabilities , the example of P1.E2 with . Then
because given the only uncertainty left in is whether it was flipped. It matches . In general bits for a fair input:
- : bit.
- : bits.
- : bits.
- : bits.
- : bits.
- : , since the copy is pure noise.
A copy that is right times in 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 .
Let be uniform on and let , the table of P1.D5. The values of are (probability ), () and (). The correlation is exactly , because the table is symmetric around . But is a function of , so and
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 rises or falls with ), is not on a scale from to , 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: . Unlike the differential entropy of P1.E2, this stays non-negative and does not change if you rescale or , because the units cancel in the ratio. For two Gaussian variables with correlation it equals nats: nats ( bits) for , for and growing without bound as approaches . 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 examples, positive and negative, into two groups of , one with positives and negative, the other with and . The information gain was bits. Now see it as a joint table of the feature (which group) and the label, with the counts divided by :
| label positive | label negative | |
|---|---|---|
| group A | ||
| group B |
This is exactly the noisy copy with : the label agrees with the group of the time. The label’s entropy is bit, and what is left after learning the group is bits, so bits (the table for 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 bits. That is a coincidence of rounding: the two tables differ in the fourth digit, and .)
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 samples, have an average estimated of about bits, and the estimate is above in about of such samples. The estimate settles toward 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 with the label, yet the pair determines it completely ( 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 is sent through a noisy step to give , and through a second noisy step to give , so that depends on only through (a Markov chain, ). The data processing inequality says : no step that only uses can recover information about that lost. Example: two cascaded flips of probability each give a net flip probability of (the pair is wrong when exactly one of the two flips happens), so bits, below .
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 and and let , which is when they differ. Any two of the three are independent: . But given , learning tells you exactly: bit. The central region of the three-circle picture would be 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 is the size of the fair choice that is as uncertain as the distribution. The name for it is the perplexity:
The two are the same number, because the base cancels: . A fair die has bits and perplexity exactly : six equally likely choices. A loaded die with face probabilities has bits ( nats) and perplexity . 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 and on the others with each has perplexity , close to a single choice. For a distribution on outcomes the perplexity lies between (one outcome is certain) and (all equally likely).
What to try:
- Fair. Perplexity . Move one bar up: it falls below , and it is again only when all six bars are equal.
- Two faces. Four faces have probability and add nothing, so the perplexity is exactly , like a coin. A face that can never happen does not count as a choice.
- Nearly certain. The perplexity is .
- 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 . A model that guesses uniformly has perplexity equal to the number of outcomes, whatever the truth is. “Face 1 underrated” gives : it rates the most likely face lowest, which is worse than guessing uniformly. “Same as the truth” gives , the lowest possible. “Rules out face 6” gives infinity.
Perplexity of a model
A model for data from is scored by its cross-entropy (P1.E3), and its perplexity is . Using (P1.E4):
The first factor is the perplexity of the truth itself, the best any model can do. The second is at least , and is the price of wrong probabilities. For the loaded die and the “Face 1 underrated” model of the widget, .
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:
The example of P1.E3: three tokens that the model gave probabilities , and . The average loss is nats, and . The model is as unsure as a fair choice among tokens at each step, on average. Another reading: perplexity is the geometric mean of over the tokens, .
- It is at least , because each probability is at most . It is only if the model gives every token of the text probability .
- Lower is better, on the same text.
- A uniform guess has perplexity equal to the vocabulary size: a model with a vocabulary of tokens that spreads its probability evenly has perplexity .
- A probability of 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 per token on a text with tokens per word has perplexity 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 on a text of tokens and words. The total is nats, so the per-word perplexity is . For and tokens per word, . 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 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, 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 , 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
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The weather line prints , , , , and . The independent line has , the copy has and the noisy copy has . The KL form gives for the weather table, the same number. The lines show a correlation of but . The die lines print the perplexities , and , and the last line prints nats per token and perplexity . Change the weather table (keep it adding to ) and see move. Try a table whose rows are all equal: is .
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 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 is as unsure at each step as someone choosing fairly among tokens (often pieces of words).
Math
- is symmetric, at least , and exactly for independent variables; .
- on average, though can exceed .
- For a noisy copy of a fair coin with flip probability , .
- Model perplexity is of the average loss per token, and for a model of .
Interview questions. Is mutual information the same as correlation? No: it catches any dependence, and it is 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.0Common mistakes
Check your understanding
Which expression equals the mutual information for any two discrete variables?
The overlap of the two entropies is their sum minus the entropy of the pair. The expression is the negative of that and is at most . The sum is what is left after removing the overlap, which is . A product of two entropies has no such meaning.
is uniform on and . The correlation of and is . What can be said about ?
Knowing determines , so and bits. A correlation of only says that no straight line fits; it does not imply independence. Mutual information is never negative. It is defined for any pair of variables, linear or not.
A machine fails on of days overall. Knowing that today is a stress-test day makes the failure uncertainty larger than before (from to bit). Which statement is still correct?
The average bits is below , as the mutual information is at least . The stress-test day is a value with above , so the claim about every value fails. Mutual information is never negative. The day and the failure are dependent: failures happen only on stress-test days.
A language model has a perplexity of on a held-out text. What does that say?
Perplexity is the exponential of the average loss per token, here nats, which is the uncertainty of a fair choice among options. Accuracy is a different measure: a model can be right much more often than one time in eight. The loss itself is nats, not . The number of distinct tokens in the text does not enter the calculation.
Model A has perplexity on a text with its tokenizer and model B has perplexity on the same text with a different tokenizer. What follows?
The total log-probability of the text is shared across the tokens, so a tokenizer that cuts the text into more pieces gives a lower number per piece, whatever the model. Comparing needs the same tokenizer, or a measure per character, word or byte. A lower perplexity is better only when the two numbers are comparable. A higher perplexity means more uncertainty per token, not better quality, and equal text does not make the per-token numbers equal.
Exercises
- A joint table has , , , . Find , and in bits.
Show answer
The marginals are for and the same for , so bits. The four cells give bits. Then bits, and bits. - A fair coin is copied through a binary symmetric channel with flip probability . Find .
Show answer
bits. - Find the perplexity of the source with probabilities .
Show answer
bits, so the perplexity is , a little below outcomes. - A language model has an average loss of nats per token. What is its perplexity, and what is its loss in bits?
Show answer
, about . In bits the loss is , and again. - A model has perplexity per token on a text that has tokens per word. What is its perplexity per word?
Show answer
. - A program reports an estimated mutual information of bits. What does that tell you?
Show answer
The 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 . (Some estimators can return small negative values from noise, and then the right reading is “about ”.) - A label is the XOR of two fair independent bits and . Find and .
Show answer
Knowing alone leaves the label a fair coin, so , and the same for . Knowing both determines the label, so bit. Ranking features one at a time would drop both. - is uniform on and . Find the correlation and the mutual information.
Show answer
The correlation is , because and . Since is determined by , 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).