Lecture 1 — Language Models are Probability Distributions
Project connection. Project Step 1 constructs the bigram model studied below. Numerical values in this lecture refer to the course’s 1,115,394-character Shakespeare corpus.
0. What is a language model
Let be a set, called the vocabulary, of finite cardinality . Elements of are called tokens. We write for finite sequences from , and for a sequence , we write for its prefix before position . The empty sequence is allowed as an element of .
Define
This is called the probability simplex. Its elements can be thought of as probability distributions: an element is the function
such that . Since , a topologist would notice this is homeomorphic to .
Let be a subset of , which we call the parameter space. Then a parametrized autoregressive language model on , or a language model (LM) for short, is a function
that is differentiable in for any fixed . The notation foreshadows the roles of and , which we will explain shortly. Here, is called the parameter and is called the context. Fixing , we obtain a function which is called a trained language model.
By adjunction, we can also think of as a function
with the property that for all and ,
A trained language model is a function that takes in a string of tokens, and returns a probability distribution on the next token: informally, we call it a token predictor. Above, we wrote
This is because the probability distribution on next tokens can be viewed as a conditional probability, conditional on the input string , of the possible next tokens. For each , the chain rule therefore gives a probability distribution on , the space of sequences of length , defined by
When the length is clear from the argument, we will often write simply . Thus the next-token distributions determine the model’s probability for every fixed-length token string.
Example 0.1. Let’s see how a next-token predictor can capture a whole body of text, in a tiny example. Suppose the complete sentences we could ever encounter in a language are
occurring with probabilities
respectively.
In standard terminology, the set of sentences alone is a language; , where is the end-of-sequence token, so a complete sentence is a token sequence like . The language together with these frequencies is a probability distribution on , called the data distribution, and it is what a trained model is meant to imitate.
The single most probable sentence is . So it may seem that a good model, predicting one token at a time, ought to begin with . But sentences beginning with have total probability , so an ideal token predictor , given the empty context , in fact favors :
The remaining conditional distributions are read off from the data distribution in the same way: after the sentence is over, and each of the three sentences beginning with is equally likely among sentences beginning with , so
and after any two-letter sentence, . Now the chain rule defining from recovers the data distribution exactly:
and
and likewise . A model that samples one token at a time from these conditional distributions speaks the language perfectly: every sentence is produced with exactly the right probability.
Above, we said that a token predictor is actually sufficient to obtain a sentence predictor, using the chain rule (that is, we derived from ). You might feel that a token predictor should output and a sentence predictor should output , and that these are at odds with each other. But the output of a model is actually a probability distribution, not a single token or single answer. For this reason, there is no contradiction in the fact that is the most likely sentence and is the most likely first token.
1. Corpus and tokenization
A corpus is a body of text used to build a language model: the entire internet, more or less, in the case of large language models like ChatGPT; the complete works of Shakespeare in our toy models.
Typically when building a model, one gathers a corpus and divides it into three sets of data to work with:
- A training set, which is usually most of the corpus. This is used to set the parameters initially.
- A dev set, used during model development to compare choices and tune the model without looking at the test set. We will return to this role later in the course.
- A test set, held out from training and model development and used to evaluate, or benchmark, the final model. We will discuss this evaluation later in this lecture, when we define perplexity.
The corpus arrives as raw text, so the first task is to turn it into tokens. Tokens might be letters or words or phonemes or letter combinations, etc. But on a computer, you probably want things to be encoded differently, for example, you want your information written in ASCII strings.
Tokenization is the process of changing text into tokens. Let be a set of raw texts or strings (the stuff you type in). A tokenizer is an injection (“encoding”)
with a left inverse (“decoding”), i.e. . This left-inverse property is referred to as losslessness.
It makes sense to choose your vocabulary based on the corpus, and there are algorithms to determine the best tokens to use for a given corpus. That is, the text itself can naturally dictate by the nature of its statistics. But for the moment, we’ll just do the dumbest thing in our Shakespeare example.
As an aside, for the transformer models studied later in the course, the cost of standard self-attention grows quadratically with sequence length. A tokenizer that represents text using fewer tokens is therefore computationally valuable; character-by-character encoding is very uncompressed.
2. -gram models
The simplest language models are obtained by requiring that the distribution of the next token depend only on a fixed number of preceding tokens. These are called -gram models and defined as follows:
Definition 2.1. Let be a vocabulary including one distinguished token called a beginning of sequence token. An -gram model is an autoregressive language model with the Markov assumption that for ,
and for ,
In other words, the model output depends only on the previous tokens. So we need only consider contexts from . For a short context of length , we simply prepend tokens (the special token that says “I haven’t started talking yet, stand by!”).
Warning: we are really hoping to model a corpus which does not contain . This definition is appropriate if we assume that our corpus and our language do not themselves contain the token . This extra token is merely a practical formality.
The model is parametrized by a matrix with entries
indexed by contexts and next tokens , subject to the condition that for every , i.e. each -th row is a probability distribution, so the entries are non-negative with row sum . A matrix with this property is called a row-stochastic matrix.
The case is a unigram model. Here the context is empty ( contains only the empty sequence), so the model ignores context entirely: it is a single fixed probability distribution on the next token. Its parameter matrix is a row-stochastic matrix, i.e. a single row, which is just an element of .
Example 2.2 (a small unigram model). Take , so . A unigram model is given by a row-stochastic matrix, for example
where the columns are indexed by in that order. Thus this model never generates ; regardless of what has come before, it predicts with probability , with probability , and with probability . It produces text with the right letter frequencies but no structure at all, such as .
The case is a bigram model; its parameter matrix is a row-stochastic matrix. A bigram model defines a Markov chain: a stochastic process in which the probabilities of the next state depend only on the current state. In this case, the probability distribution of the next token depends only on the previous one, and not on any earlier history. The only contexts needed to define the model are single tokens, i.e. .
Example 2.3 (a small bigram model). With the same , a bigram model is given by a row-stochastic matrix. One choice is
where both rows (contexts) and columns (next tokens) are indexed by in that order. Each row is a probability distribution on the next token. The first row gives the distribution of the first token. For instance, the -row says that after seeing , the model predicts with probability . After the first token, the model tends to produce alternating text like , since each of and strongly prefers the other as its successor; the last row says that after the model chooses or with equal probability, and never produces twice in a row.
3. Maximum likelihood
Training is the process of incrementally adjusting to achieve some “best” value. Maximum likelihood is the mathematical definition of “best”. (This is true during the training phase. There are later phases where we do other types of adjustments to the parameters.)
When we encode the training set, it becomes a sequence of tokens, which we will also call the training set.
Fix a training set . The likelihood of for this training set is
We are thinking of the training set as fixed, so that this is a function on with values in :
The idea here is that we wish to train our model to assign a high probability to our training set. Then the hope is that it would perform well on similar test data. The likelihood is a measure of how likely a model of parameter thinks the training set is. We want to choose to maximize this.
The log likelihood is the function
Don’t worry about for right now.
A maximum likelihood estimator is any maximizer of the log likelihood as a function of . The log is just more convenient to work with. That is, is an element of at which a maximum occurs.
For any token string , define the model’s average negative log-likelihood, or average log loss, on by
For the fixed training set, we abbreviate
so that
Thus maximizing likelihood is equivalent to minimizing average log loss. The latter is often more convenient because the product of next-token probabilities becomes an average of their negative logarithms. If means logarithm to base , the units are bits per token; natural logarithms give nats per token.
To fix ideas, let’s determine the maximum likelihood estimator for the bigram model. This means finding a row-stochastic matrix that maximizes the log likelihood , or, equivalently, finding its entries for all .
Let denote the beginning of sequence token, and set . Recall that the training set does not contain the token . For , let count the occurrences of the sequence in the training set, including the initial transition , i.e.
Then for , counts the occurrences of in the training set (except in the last token), while
Recall that for a bigram model, a context is just a single token.
Theorem 3.1 (Maximum Likelihood Estimator for the bigram model). Let be a maximum likelihood estimator for a bigram model. For every context with , the -th row of is
Any matrix satisfying this is a maximum likelihood estimator.
In other words, when , the -th row may be chosen arbitrarily in . Note that , so the theorem also determines the -th row: , i.e. the model is certain to begin with the same token the training set begins with.
Proof
We want to maximize
For a bigram model, the conditional distribution of depends only on the preceding token. With the convention , this gives
for every . Therefore
Taking logarithms, we obtain
If , then for every , so the -th row contributes nothing to the log-likelihood. Hence that row may be chosen arbitrarily.
Now suppose that and define
We claim that this is the unique choice of the -th row which maximizes its contribution to the log-likelihood. If for some with , then the log-likelihood is , so we may assume that
whenever .
Using the inequality
we have
Here we used
It follows that
Moreover, equality in occurs only when . Hence equality forces
whenever . Summing over those values of , we obtain
On the other hand, the -th row of is a probability distribution, so
and every . Therefore
Since each term in this sum is nonnegative, it follows that
whenever . Thus, for every with , the unique maximizing row is
This proves the result.
Remark 3.2 (parameter sharing). The proof separates the likelihood question into independent multinomial estimation problems, one for each context. Neural models deliberately destroy this separation by sharing parameters across contexts; that sharing permits evidence from one context to affect predictions in another.
We will see later that zero entries in are problematic. This motivates the following adjustment to .
Definition 3.3 (Laplace smoothing). For , the Laplace-smoothed estimator is
In a Laplace-smoothed estimator, every coordinate is strictly positive.
4. Perplexity
We need a way to compare trained models (compare different values of ). To do this, we will define perplexity, which is a sort of measure of how surprising the trained model finds a string of text.
When we tokenize the test set, we obtain a sequence of tokens , also called the test set. Then the perplexity of the model on the test set is
Example 4.1. In the unigram model,
and in the bigram model,
For example, if , and all are assigned equal probability in a unigram model, then every factor in the product is , so for a string of length ,
Intuitively, choosing the next token amounts to picking one of three equal options. On the other hand, using the same vocabulary , if while and , then the perplexity of a string changes with the string. For example,
while
So this model, which prefers the token (i.e., thinks it is more probable), is much more perplexed by the less likely string than by the unsurprising .
The goal is to measure how good a model is. We want to be high when is the test set. The idea is that when the model finds the test set probable, this is an indication that it is a good model. However, for obscure (to me) reasons, we want a statistic that is low on very probable test sets. The inverse of the probability of the test set is a natural candidate. However, by nature, will be lower on long strings (we’re multiplying probabilities , so the more ‘s, the smaller the number gets). In other words, test set length may vary, and longer test sets will be less probable simply because of their length. Hence, perplexity is designed to be an average over the tokens of the test set. More precisely, it is the geometric average of the inverse probability of each successive token. (We use the geometric average because probabilities naturally live in the world of multiplication.)
We sometimes refer to the inverse of a probability as a branching factor. For example, we should think of the probability distribution in the second example above as if there are actually 10 options at any moment, 8 of which are , one of which is , and one of which is . Then choosing is “like” choosing 1 of 10 branches. This motivates the following definition: the branching factor of a token given context (the choice of at node ) is the inverse of the probability . We say that the choice of has a branching factor of , while the choice of has a branching factor of . We are averaging this geometrically as we move forward through the text. So the perplexity is the geometric mean of the branching factors encountered along the string:
For an -gram model, the probabilities of the first tokens are computed using the -padding convention of Definition 2.1. Thus the same perplexity formula applies to every token in the test string; no initial factors need to be dropped.
The uniform unigram model is the unigram model which applies the same probability to every token in the vocabulary.
Proposition 4.2. The uniform unigram model on a vocabulary of size has perplexity exactly on any test set.
Proof
Every next-token probability is , so and .
5. Entropy
Perplexity is closely related to entropy and cross-entropy, two fundamental notions from information theory that will come up repeatedly.
We begin with entropy. Let be a probability distribution on a finite set .
Definition 5.1 (entropy). The entropy of is
The quantity
is sometimes called the information content or surprisal of . An unlikely outcome has large surprisal, while a likely outcome has small surprisal. Thus entropy is the average surprisal of an outcome drawn according to :
If the logarithm is base , entropy is measured in bits; if we use the natural logarithm, it is measured in nats.
For language, it is useful to apply this idea not to a single token, but to long strings. Fix a trained language model. For every , recall that the chain rule gives a probability distribution on :
This is the fixed-length distribution introduced in Section 0; here we keep the superscript explicit because we will compare distributions for different string lengths.
Its entropy is
This measures the average information contained in a string of length . To obtain an average per token, we divide by .
Definition 5.2 (entropy rate). Suppose that the limit exists. The entropy rate of the stochastic process described by is
Thus measures the average information in an entire length- string, while measures the asymptotic average information per token.
The entropy-rate discussion concerns an idealized process that continues indefinitely. It is therefore separate from the optional -stopping convention used to model finite responses in the appendix.
There is another way to understand the entropy rate which is particularly useful for language models. Suppose that the token sequence
is a stationary ergodic stochastic process with joint distributions .
Stationary and ergodic. A stochastic process is simply a sequence of random variables , in our case taking values in the vocabulary . It is stationary if its statistical behavior does not depend on where we are in the sequence: for every ,
have the same distribution.
Roughly speaking, the process is ergodic if it does not decompose into several different stationary regimes. The significance of ergodicity is that averages taken along one sufficiently long realization agree with averages over the probability distribution. For example, the frequency of a fixed token, or of a fixed finite block of tokens, in one typical long sequence converges to its probability under the process.
An -gram model uses the same finite-memory prediction rule at every position: the probability of the next token depends only on the preceding tokens, and not explicitly on the position in the sequence. This is sometimes informally referred to as a stationarity assumption. Strictly speaking, however, stationarity of a stochastic process is a stronger condition: it requires the joint distribution of the sequence to be unchanged by shifting all positions. When we invoke the Shannon—McMillan—Breiman theorem, it is stationarity in this latter sense, together with ergodicity, that we assume.
Natural language itself is not literally stationary: its statistics vary with topic, genre, speaker, historical time, and other changing context, and its dependence can extend far beyond a fixed window. Thus stationarity and ergodicity should be understood here as useful assumptions on an idealized stochastic model of language.
Now sample one infinite sequence
from the process. The quantity
measures how surprising its first tokens are under the model, and hence
is the average surprisal per token along this particular string.
The Shannon—McMillan—Breiman theorem says that, under the stationary and ergodic hypotheses, almost every sufficiently long sample is representative in exactly this sense:
Theorem 5.3 (Shannon—McMillan—Breiman). Let be a stationary ergodic stochastic process on the finite vocabulary . Then, with probability ,
There are two rather different-looking ways to compute the same number. The definition
averages over all possible strings of length , weighting each string by its probability.
The Shannon—McMillan—Breiman theorem says that, for a stationary ergodic process, we can instead take one typical long string
and compute
As becomes large, this converges to the same entropy rate. This is the sense in which one sufficiently long realization of an ergodic process is representative of the distribution as a whole.
Using the autoregressive factorization,
Thus the entropy rate can be recovered as the limiting average token-by-token surprisal along one typical long string. This is particularly convenient: instead of summing over all possible strings with their probability weights, we can estimate the entropy rate by following a single long sample.
There is an immediate connection with perplexity. For any token sequence , Section 4 defined
Taking logarithms gives
Thus the logarithm of perplexity is exactly the average surprisal per token. In particular, under the hypotheses of the Shannon—McMillan—Breiman theorem, the log perplexity of a typical long sample converges to the entropy rate:
We have now also seen two quantities used to evaluate a model: during training we maximize likelihood, while during testing we hope for low perplexity. These goals are not at odds. When likelihood and perplexity are computed on the same sequence of tokens, they are exactly the same measurement in different forms.
Theorem 5.4 (maximum likelihood minimizes training perplexity). Let be any sequence of tokens — for instance, the training set. Then for every ,
Consequently, for the training set, is a maximum likelihood estimator if and only if it minimizes the training loss , and this is equivalent to minimizing training perplexity.
Proof
By definition,
Therefore
The middle equality is the autoregressive factorization of the string probability.
Now fix the training set and regard these quantities as functions of . Maximizing its likelihood
is equivalent to minimizing
Since the logarithm is strictly increasing, this is in turn equivalent to minimizing .
The theorem concerns likelihood and perplexity evaluated on the same data. In particular, maximizing likelihood on the training set necessarily minimizes perplexity on that training set. But this does not tell us that the model will have low perplexity on new text. What we really want is for the probabilities learned from the training set to perform well on new samples from the underlying language. To formulate this distinction mathematically, we need to compare two probability distributions: the distribution generating the data and the distribution predicted by the model. This leads to the notion of cross-entropy, which we see in the next section.
Example 5.5 (entropy and data compression). There is a useful interpretation of entropy in terms of data compression. Suppose that is a finite set and is a probability distribution on , and take all logarithms in base . Recall that
is the surprisal of . Coding theory gives this quantity another interpretation: it measures, roughly, how many bits we should need to record the outcome . Common outcomes should be cheap to describe, while rare outcomes can be assigned longer descriptions.
A binary code assigns to each a finite string of ‘s and ‘s, called its codeword. We will use prefix codes: no codeword is allowed to be the beginning of another codeword. This condition guarantees that a sequence of codewords can be decoded unambiguously. If denotes the length of the codeword assigned to , then the expected number of bits needed to encode a symbol drawn from is
A fundamental result of coding theory says that this expected length is bounded below by the entropy
For a concrete example, suppose
One simple code is to use the ordinary three-bit binary representations:
Every codeword has length , so for every probability distribution on , the expected code length is
Now suppose that the distribution is very far from uniform:
The three-bit code ignores the fact that some symbols are much more common than others: it spends three bits on the very common symbol and also three bits on the much rarer symbol .
We can do better by assigning shorter codewords to more likely symbols and longer codewords to less likely symbols. Consider the following prefix code:
| codeword | length | ||
|---|---|---|---|
For example, after reading the bit we know immediately that the symbol was , while a word beginning with requires more bits before it is determined. Because no codeword is a prefix of another, concatenations of these words can still be decoded uniquely.
The expected number of bits per symbol is now
Thus adapting the code to the probability distribution reduces the average length from bits to bits.
Now compare this with the entropy. In this example,
takes the values for , respectively, and the value for . Hence
This is exactly the same computation as the expected code length. This is in contrast with the ordinary three-bit representation code we started with. In that example,
This calculation tells us right away that the ordinary three-bit encoding is not optimal.
In fact, our second code has
for every . Thus the coding interpretation agrees perfectly with the interpretation of entropy as average surprisal: in this example, the surprisal of a symbol is exactly the number of bits used to encode it.
This exact agreement is special. Codeword lengths must be integers, whereas need not be. Thus for a general distribution there may be no prefix code for individual symbols whose expected length is exactly . Nevertheless, entropy remains the fundamental limit. If we encode long blocks of independent symbols drawn from , the source coding theorem says that the average number of bits per symbol can be made arbitrarily close to , but not asymptotically smaller than .
For comparison, if is uniform on , then
and the original fixed-length three-bit code is already optimal.
6. Cross-entropy
When we evaluate a language model on new text, there are really two probability distributions in the background. At a context , imagine that the language itself has some true, but unknown, next-token distribution
while our trained model predicts
The next token is generated by the language, but we want to evaluate how well our model predicted it.
Suppose, for example, that the next token is drawn according to . If , the model incurs the log loss
Averaging this loss over the possible tokens that the language might actually produce gives
This is the next-token version of cross-entropy; after defining the general notion, we will return to whole strings.
Definition 6.1 (cross-entropy). Let and be probability distributions on a finite set . The cross-entropy of relative to is
If but for some , we set .
The two distributions play different roles. The distribution tells us how often each outcome actually occurs, so it supplies the weights in the average. The distribution tells us how surprising that outcome is according to the model, through the quantity
Thus
is the average surprisal of an outcome drawn according to , when surprisal is measured using the probabilities .
For a language model, represents the true language and represents the model. At a fixed context , the true language produces the next token with probability , while the model assigns that token the surprisal
Averaging over all possible next tokens therefore gives
This is the cross-entropy of the true next-token distribution relative to the model’s next-token distribution.
Compare this with entropy:
Entropy uses both to determine how often an outcome occurs and to measure its surprisal. Cross-entropy uses to determine how often the outcome occurs, but uses to measure its surprisal. We should therefore expect
with equality when the model gets the probabilities exactly right.
Indeed, we will prove in the next section:
Theorem 6.2 (cross-entropy lower bound). For probability distributions and ,
with equality if and only if .
Let’s return to language models and long strings. The true next-token distributions , when combined by the same chain rule as the model, determine joint distributions on length- strings. Thus is the true, unknown distribution of length- text, while is the distribution assigned by the model. The cross-entropy
is the expected log loss of the model on a length- string generated by the true language. Dividing by gives the expected log loss per token.
When the limit exists, we call
the cross-entropy rate of the model relative to the source.
The cross-entropy rate is the quantity we would ideally like to know, but it involves the true language distribution , which is unknown. To see how we can nevertheless estimate it from data, rewrite the finite-length cross-entropy per token as
This formula separates the roles of the true language and the model very clearly. The true distribution tells us how likely each length- string is to occur, and therefore supplies the weights in the average. For each possible string, the quantity
measures how surprising that string is according to the model, per token.
In practice, we do not know the weights , so we cannot perform the sum over all possible strings. What we do have is a held-out string
of actual language that was not used to train the model. For this observed string we can compute the quantity appearing inside the average:
This is exactly the average log loss introduced in Section 3, now evaluated on held-out text rather than on the training set.
The connection with our discussion of entropy can be made precise. Recall that the Shannon—McMillan—Breiman theorem says that if is a stationary ergodic source and
is sampled from , then, with probability ,
Thus the entropy rate, which is defined by averaging over all possible strings, can be recovered from the probability of one typical long string.
For cross-entropy, the same principle holds with the string scored by a second distribution . Under suitable stationary and ergodic hypotheses on the source and model, a relative form of the Shannon—McMillan—Breiman theorem gives
where the sequence is generated according to the true source .
The distinction between the two formulas is worth emphasizing. In the entropy formula, the source both generates and scores the string. In the cross-entropy formula, the source generates the string, but the model scores it. Consequently, for one sufficiently long held-out sample,
approximates the cross-entropy rate of the model relative to the source. This is why the model’s average log loss on held-out text is the practical quantity used to estimate cross-entropy: it can be computed without knowing .
But we have already encountered exactly the quantity
By the definition of perplexity,
and therefore
So perplexity on held-out text is simply an exponential version of the quantity used to estimate cross-entropy. The relationship can be summarized as follows:
- Cross-entropy averages the model’s log loss over all possible text generated by the true language.
- Held-out log loss computes that same loss on one observed sample of real text.
- Perplexity is the exponential of the held-out log loss.
Thus low perplexity on new text is evidence that the model has low cross-entropy relative to the language generating that text.
7. KL divergence and Gibbs’ inequality
In the preceding section, we compared two distributions on strings of length : , the true distribution of the language, and , the distribution predicted by the model. Their cross-entropy
measures the average log loss when strings are generated according to the true language but scored using the model.
If we knew the true distribution and used it to score the same strings, the corresponding quantity would instead be the entropy
Thus the difference
measures the extra average log loss caused by using the model distribution instead of the true distribution . This difference is an instance of the Kullback—Leibler divergence.
We first define KL divergence for arbitrary probability distributions.
Definition 7.1 (Kullback—Leibler divergence). Let and be probability distributions on a finite set . The Kullback—Leibler divergence, or KL divergence, from to is
If and for some , we set
Equivalently,
Indeed,
As usual, terms with contribute .
The identity
is the most useful way to think about KL divergence here.
The entropy is the average surprisal when outcomes occur according to and we also use the correct probabilities to score them. The cross-entropy is the average surprisal when outcomes still occur according to , but we score them using the probabilities . Therefore
measures the extra average log loss caused by using instead of .
Returning to language models,
therefore measures the extra expected log loss on length- text caused by using the model rather than the true language distribution .
Despite its name, KL divergence is not a distance: in general,
and it does not satisfy the triangle inequality.
The interpretation above suggests that KL divergence should never be negative: using the true probabilities should be at least as good, on average, as using some other probabilities. This is Gibbs’ inequality. The proof is elementary so we leave it out.
Theorem 7.2 (Gibbs’ inequality). For probability distributions and ,
with equality if and only if .
Combining Gibbs’ inequality with
immediately gives
with equality if and only if . This proves the cross-entropy lower bound from the preceding section.
For the language model distributions, we obtain for every
Thus the cross-entropy of the model on length- text decomposes into two parts:
The first term is uncertainty inherent in the source itself. The second term measures the additional loss caused by the model’s failure to reproduce the true distribution.
There is a corresponding statement for the rates introduced in the preceding section. When the relevant limits exist, define the KL divergence rate by
Dividing the preceding identity by and taking limits gives
In particular,
Thus, at the level of long strings, the excess cross-entropy rate of the model over the entropy rate of the source is precisely its KL divergence rate from the true language.
Looking ahead to Lecture 2. There are two equivalent levels at which to view these quantities. In this section we have compared the distributions and on complete strings of length . Recall, however, that these distributions are built from the next-token distributions by
Consequently,
Thus the loss on a string is the sum of the losses of its individual next-token predictions. In Lecture 2 we will return to this local viewpoint: the problem will be to construct and parametrize the map
from contexts to next-token probability distributions.
8. Summary: measuring the quality of a language model
Let denote the true distribution of length- text, and let denote the distribution predicted by the language model.
The main quantities introduced above fit together as follows:
-
For an observed string , the model’s average log loss is . Smaller is better.
-
The perplexity of the model on this string is . Thus . Perplexity is therefore just a monotone rescaling of the same measurement.
-
The cross-entropy rate is the idealized average log loss of the model on text generated by the true language. Since is unknown, in practice we estimate this quantity using average log loss, or equivalently perplexity, on held-out text.
-
The entropy rate measures the irreducible uncertainty in the language itself.
-
The difference between these two quantities is the KL divergence rate: . Thus the KL term measures the additional predictive loss caused by the model’s failure to match the true language distribution.
In short, training and evaluation revolve around the same basic quantity: the probabilities that the model assigns to the tokens that actually occur. On a fixed held-out string, assigning larger probability is exactly the same as having lower average log loss and lower perplexity. On sufficiently representative held-out text, these quantities estimate the model’s cross-entropy rate on the underlying language.
9. A language model as a compression scheme
For this subsection, we take all logarithms in base . We have just seen that the average log loss
measures how well the model assigns probabilities to an observed string. There is another useful interpretation of exactly the same quantity: it is closely related to the number of bits per token needed to compress the string using the probabilities supplied by the model.
Suppose that the sender and receiver both have access to the same language model. At the context
the model assigns the next token probability
A probability corresponds to an ideal code length of approximately
bits. Thus likely continuations receive short descriptions, while unlikely continuations require longer descriptions.
The code depends on the context, but this causes no problem: once the receiver has decoded , they know the same context as the sender and therefore know the same next-token distribution.
For a string
the total idealized code length is therefore approximately
Dividing by , the idealized bitrate is
bits per token.
But this is exactly the average log loss of the model when logarithms are taken in base . Equivalently,
Thus lower perplexity corresponds to a shorter probabilistic description of the text.
Cross-entropy as bitrate. Suppose now that the text is generated according to the true language distribution , but compressed using the probabilities supplied by the model . For one observed string, the quantity
is the model’s bitrate on that string.
Under the stationary ergodic hypotheses discussed above, for a sufficiently long typical sample this quantity converges to the cross-entropy rate
measured in bits per token. Thus cross-entropy rate is the asymptotic average bitrate obtained when data are generated by the true language but encoded using the model.
If we instead knew the true distribution and used it for coding, the corresponding optimal rate would be the entropy rate
By the identity from the preceding section,
Thus the KL divergence rate measures the extra number of bits per token caused by using the imperfect model instead of the true source distribution.
The code lengths
need not be integers, so they should be understood as ideal code lengths rather than literal lengths of individual binary codewords. Coding methods such as arithmetic coding make this probabilistic picture precise up to small coding overheads.
The main conceptual point is that the same quantity has now appeared in several forms:
For long text generated by the source, the corresponding population quantity is the cross-entropy rate, and the KL divergence rate measures the extra compression cost due to model mismatch.
Dividing a log loss in nats by converts it to bits, and multiplying by the ratio of tokens to characters gives bits per character, a tokenizer-independent unit. Measured on the course corpus:
| model | nats/token | bits/character | perplexity |
|---|---|---|---|
| uniform | 4.1744 | 6.0224 | 65.000 |
| bigram (add-one) | 2.4549 | 3.5417 | 11.646 |
| trigram (add-one) | 1.9532 | 2.8178 | 7.051 |
Historical aside. In Prediction and Entropy of Printed English (1951), Shannon estimated English at roughly one bit per character using human guessing experiments. His number concerns a language source’s long-run entropy rate; the course’s progression from the uniform baseline, through -grams, to the transformer is most readily compared in bits per character.
Appendix. Normalization and the end-of-sequence token
In the main text, we explained informally how an end-of-sequence token turns next-token probabilities into probabilities of finite sentences. We give the details here.
Let be a finite vocabulary containing a distinguished end-of-sequence token , and write
for the set of ordinary tokens. Fix a trained language model
Thus, for every context ,
To sample from the model, we begin with the empty context. We draw a token according to . If that token is , we stop. Otherwise we append it to the context and repeat. In this way the model may produce
We call such a sequence a complete sentence. The corresponding sentence, with the stopping symbol suppressed, is the finite string .
The chain rule suggests assigning to this complete sentence the probability
For , the empty product is , so this formula says
There is a small normalization issue. Although each is a probability distribution, it does not automatically follow that the probabilities of all finite sentences sum to . There could, in principle, be positive probability that the model continues producing ordinary tokens forever and never emits .
The following proposition makes this precise.
Proposition A.1. The numbers satisfy
More precisely,
Hence these probabilities sum to if and only if the model emits with probability .
Proof
For , let be the event that the model produces exactly ordinary tokens and then emits . For a fixed sequence , the probability of producing
is, by the chain rule,
The possible strings are mutually exclusive, so
The events are also mutually exclusive, and their union is exactly the event that the model eventually emits . Therefore
The left-hand side is a probability, so it is at most .
Finally, either the model eventually emits , or it continues forever without emitting . Thus
The displayed sum is therefore equal to precisely when the latter probability is .
A collection of nonnegative numbers whose total is at most is sometimes called a sub-probability distribution. Thus the language model always gives a sub-probability distribution on finite sentences. The “missing mass” has a concrete interpretation:
For example, if the probabilities of all finite sentences sum to , the remaining is exactly the probability that the model generates ordinary tokens forever.
When the probability of continuing forever is , we say that the sampling process halts almost surely. Here “almost surely” is standard probability terminology: it means “with probability .” In that case, appending gives a bijection
and therefore gives an ordinary probability distribution on finite sentences in .
There is a simple sufficient condition which guarantees this normalization. Suppose there is some such that
for every context that can arise before the model stops. At each step, the probability of producing another ordinary token is then at most . Consequently, the probability that the model produces at least ordinary tokens without stopping is at most
Since
the probability that the model continues forever is . Hence the model halts almost surely, and its probabilities on finite sentences sum to .
Exercises (paired with Step 1)
- ★ Extend Theorem 3.1 to a general -gram model, implement the bigram estimator, and confirm an average log loss (cross-entropy) of 2.4549 nats for add-one smoothing.
- Show that the Laplace-smoothed estimator (Definition 3.3) is the mean of the posterior obtained from a prior on the simplex and the observed counts. Determine the limits as and .
- ★ Compute perplexity for the uniform, bigram, and trigram models, and verify Proposition 4.2 numerically.
- Sampling versus scoring. Construct a distribution on with excellent training perplexity but poor samples.
- Held-out zeros. Fit an unsmoothed bigram model on the first 90% of the corpus. Estimate the probability that a uniformly selected held-out position receives probability zero, and relate it to missing mass.
- Context length and training loss. Prove that the training loss of the th-order MLE is non-increasing in , and explain why this does not establish better held-out performance.
- Prove that is convex in and that is jointly convex in .
Pointers
Shannon, A Mathematical Theory of Communication (1948) and Prediction and Entropy of Printed English (1951); Cover and Thomas, Elements of Information Theory, Chapters 2 and 5. See the resources page and Project Step 1.