Module 03 · Part I · Foundations
Probability and Information
Random Variables, Expectation and Variance, Conditional Probability, Maximum Likelihood, Entropy, Cross-Entropy, KL Divergence, and the Sigmoid
By the end you can use the rules for expectation and variance, read conditional probability notation, and explain cross-entropy, perplexity and KL divergence.
Check yourself ▸
Before you start, can you already…
- ☐compute gradients through a small computation graph by hand, and explain why a learning rate can be too large. (Module 2)
If any is shaky, the linked module teaches it.
A language model's output is a probability distribution, its training objective is a statement about probabilities, and one of its key design choices (section 6.3) rests on a calculation with averages and spreads. This module teaches the probability the course uses, in the order it uses it. Nothing here is specific to transformers, and every later module leans on it.
3.1 Random Variables, Distributions, and SamplingRun this section
A random variable is a quantity whose value is uncertain until you observe it: the face of a die, the next token of a text, the initial value of a weight. Its distribution says how likely each value is.
For a variable with a list of possible values, the distribution gives each value a probability between 0 and 1, summing to 1. A fair die gives each face ; a language model gives one probability to each of its tokens. , or just , is "the probability that comes out as ".
A variable that can take any real value, such as a weight, is described by a density instead: the probability of landing in a small interval around is about times the interval's width, and the total area under is 1. The most important density is the normal distribution (the bell curve), written :
It is centred on with width set by : about 68% of draws land within one of , and 95% within two. Weights are usually initialized from a normal distribution with and small (section 10.4). reads " is drawn from a normal distribution with mean 0 and variance 1".
Sampling draws a value at random according to the distribution. Generating text is sampling, one token at a time (section 12.3).
Two random variables are independent when knowing one tells you nothing about the other: two dice rolls are, the first and second tokens of a sentence are not.
3.2 Expectation and VarianceRun this section
The expectation is the average value of , weighting each value by its probability. It is also called the mean:
For a fair die, . (For a density the sum becomes an integral, and the rules below still hold.) The average of many independent samples settles toward the expectation.
The variance is the average squared distance from the mean. Its square root, the standard deviation , is in the same units as :
The second form, "the average of the square minus the square of the average", is usually easier to compute.
The Rules
These rules are used repeatedly, most importantly in section 6.3. Here and are fixed numbers.
- Expectation is linear, always. , whether or not and are independent.
- For independent variables, the expectation of a product is the product of the expectations. .
- Scaling a variable scales its variance by the square. : doubling every value quadruples the squared distances. Adding a constant leaves the variance unchanged.
- For independent variables, variances add. . So a sum of independent variables with variance each has standard deviation : spread grows like the square root of the number of terms.
By rules 3 and 4, the average of independent samples has standard deviation shrinking like . A gradient on a random batch is such an average: by rule 1 its expectation is the full-dataset gradient, and its noise shrinks as the batch grows. A quantity whose expectation equals what it estimates is unbiased.
Each sample is the dot product of two random vectors whose entries are drawn from N(0, 1). The dashed curve is the normal distribution with variance d that the rules predict.
The figure draws two random vectors of length , every entry from , and records their dot product. Using rules 2 and 4, predict the standard deviation of the dot product at .
In words. The figure repeatedly draws two random vectors of a chosen length and adds their dot product to a histogram, over a normal curve with variance equal to the length. The measured standard deviation tracks the predicted square root of the length as the length grows.
3.3 Joint and Conditional Probability
The joint probability is the probability that both and happen. The conditional probability , "the probability of given ", is the share of 's probability in which also happens:
Worked example. In a corpus, the word
themakes up 5% of tokens, andthefollowed bycatmakes up 0.01% of adjacent pairs. Then : of all the places atheappears,catfollows in 0.2% of them.
Rearranged, . Applied repeatedly, this gives the chain rule of probability: a joint probability is a product of one-at-a-time conditionals.
This is exact, and it is the foundation of every text-writing model in this course: a model that answers "how likely is the next token, given everything before it?" can multiply its answers into the probability of a whole text (section 8.4).
Independence means , or equivalently .
3.4 Maximum LikelihoodRun this section
A model with assigns a probability to each possible observation. The of is the probability it gives the data actually observed, and maximum likelihood chooses the that makes it largest.
For independent observations the likelihood is a product, which underflows in floating point and is awkward to differentiate. The logarithm turns it into a sum, and since the log only increases, maximizing it picks the same . Flipping the sign gives the negative log-likelihood (NLL), a loss to minimize:
Every log of a probability is at most 0, so the loss is positive, and zero only when every observation gets probability 1.
Worked example. A coin with unknown heads-probability is flipped 10 times and lands heads 7 times. The likelihood is , so the NLL is . Its derivative is . Setting it to zero gives , so : the maximum-likelihood estimate is the observed frequency.
With many values, value seen times out of gets probability . A language model is fitted by the same principle, but its probabilities come from a neural network, so there is no formula for the best and gradient descent (section 2.4) does the minimizing.
Maximum likelihood recovers the observed frequency
Run it several times at 10 flips and then at 5000. The estimate always equals the observed frequency; how close that frequency is to the hidden truth depends on how much data you have.
3.5 Information: Entropy, Cross-Entropy, KL, PerplexityRun this section
The surprise of an outcome with probability is : 0 when , growing without limit as shrinks. With base-2 logs it is in bits (a fair coin flip carries 1 bit); with natural logs, nats.
The of a distribution is its average surprise: how unpredictable it is.
A distribution that puts all its probability on one value has entropy 0. A uniform distribution over values has the largest possible entropy, .
If the true distribution is but you predict with , your average surprise, using 's probabilities over what really happens, is the :
It is never smaller than , and equals it only when . The excess is the Kullback–Leibler divergence, a measure of how far is from :
It is never negative, is 0 only when the distributions agree, and is not symmetric: and usually differ. Section 21.5 uses it to stop a model drifting far from where it started.
Why This Is the Training Loss
For one training example, the "true distribution" over the next token is one-hot: probability 1 on the token that actually came next. The cross-entropy collapses to one term:
That is the NLL of section 3.4. Minimizing cross-entropy, minimizing NLL and maximizing likelihood are the same thing. This cross-entropy loss trains every classifier and language model in this course.
Perplexity
is of the average NLL per token. A perplexity of 20 means the model is as unsure as if choosing uniformly among 20 tokens; 1 is perfect. Section 13.1 explains why perplexities across different tokenizers cannot be compared.
The left bars are the true distribution p. Drag the right bars to change the model q; they rescale so they always add to 1.
Drag the model's distribution until it matches the true distribution exactly. What will the cross-entropy and the KL divergence read then?
In words. Two bar charts over four outcomes: a fixed true distribution and a draggable model distribution. The readout shows entropy, cross-entropy and KL divergence. Cross-entropy never drops below entropy, and the gap, the KL divergence, closes only when the bars match.
3.6 The Sigmoid and Preferences Between PairsRun this section
The squashes any real score into a probability between 0 and 1:
, and . Its slope is , the "" from Module 2's exercises, because the sigmoid is the two-class softmax: .
That makes it the natural model for comparisons. Give each item a score , and say item beats item with probability
Only the difference matters, so adding a constant to every score changes nothing. This is the Bradley–Terry model, long used to rate chess players from match results by maximum likelihood. Section 21.4 fits it to people's judgments of which of two answers is better, and calls the scores .
Exercises
Which of these need the two variables to be independent? (a) ; (b) ; (c) .
Prove that from the definition .
is a sum of 256 independent terms, each with mean 0 and variance 1. What is its standard deviation?
Factor with the chain rule of probability, in left-to-right order.
A model gives probability to every token of a test text. What is its perplexity?
What is the entropy, in bits, of a distribution that gives probability to three outcomes?
Show that , and compute .
Under the Bradley–Terry model, answer A has reward 1.5 and answer B has reward 0.5. What is the predicted probability that A is preferred, and what would it be if both rewards were raised by 10?
Core Academic References
- Cover & Thomas (2006): Elements of Information Theory (2nd ed.). Wiley.
- Shannon (1948): A Mathematical Theory of Communication. Bell System Technical Journal, 27: 379–423.
- Bradley & Terry (1952): Rank Analysis of Incomplete Block Designs: I. The Method of Paired Comparisons. Biometrika, 39(3/4): 324–345.
- Goodfellow, Bengio & Courville (2016): Deep Learning, chapter 3 (Probability and Information Theory). MIT Press.