Electric Sheaves

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 V\mathcal{V} be a set, called the vocabulary, of finite cardinality VV. Elements of V\mathcal V are called tokens. We write V\mathcal{V}^* for finite sequences from V\mathcal{V}, and for a sequence x=(x1,,xT)x = (x_1, \ldots, x_T), we write x<t=(x1,,xt1)x_{<t} = (x_1, \ldots, x_{t-1}) for its prefix before position tt. The empty sequence \varnothing is allowed as an element of V\mathcal{V}^*.

Define

Δ(V):={qR0V:aVqa=1}.\Delta(\mathcal{V}) := \left\{ q \in \mathbb{R}^{\mathcal V}_{\ge 0} : \sum_{a \in \mathcal{V}} q_a = 1 \right\}.

This is called the probability simplex. Its elements can be thought of as probability distributions: an element qq is the function

q():V[0,1]aqa,q(\cdot): \mathcal{V} \rightarrow [0,1] \qquad a \mapsto q_a,

such that aVq(a)=1\sum_{a \in \mathcal{V}} q(a) = 1. Since V=V|\mathcal V| = V, a topologist would notice this is homeomorphic to ΔV1\Delta^{V-1}.

Let Θ\Theta be a subset of Rd\mathbb{R}^d, which we call the parameter space. Then a parametrized autoregressive language model on V\mathcal{V}, or a language model (LM) for short, is a function

P:Θ×VΔ(V),(θ,c)pθ(c):=P(θ,c)P: \Theta \times \mathcal{V}^* \rightarrow \Delta(\mathcal{V}), \quad (\theta, c) \mapsto p_\theta( \cdot | c) := P(\theta,c)

that is differentiable in θ\theta for any fixed cc. The notation pθ(c)p_\theta( \cdot | c) foreshadows the roles of θ\theta and cc, which we will explain shortly. Here, θ\theta is called the parameter and cc is called the context. Fixing θΘ\theta \in \Theta, we obtain a function P(θ,):VΔ(V)P(\theta, \cdot): \mathcal{V}^* \rightarrow \Delta(\mathcal{V}) which is called a trained language model.

By adjunction, we can also think of PP as a function

P:Θ×V×V[0,1]P: \Theta \times \mathcal{V}^* \times \mathcal V \rightarrow [0,1]

with the property that for all θ\theta and cc,

xVP(θ,c,x)=1.\sum_{x\in \mathcal V} P(\theta, c, x) = 1.

A trained language model is a function P(θ,)P(\theta, \cdot) 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

P(θ,c)=pθ(c).P(\theta, c) = p_\theta( \cdot | c).

This is because the probability distribution on next tokens can be viewed as a conditional probability, conditional on the input string cc, of the possible next tokens. For each T1T \geq 1, the chain rule therefore gives a probability distribution qθ(T)q_\theta^{(T)} on VT\mathcal{V}^T, the space of sequences of length TT, defined by

qθ(T)(x1,,xT):=i=1Tpθ(xix1,,xi1).q_\theta^{(T)}(x_1, \ldots, x_T) := \prod_{i=1}^T p_\theta(x_i \mid x_1, \ldots, x_{i-1}).

When the length is clear from the argument, we will often write simply qθ(x1,,xT)q_\theta(x_1,\ldots,x_T). Thus the next-token distributions pθ(c)p_\theta(\cdot \mid c) 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

b,aa,ab,ac,\texttt{b}, \qquad \texttt{aa}, \qquad \texttt{ab}, \qquad \texttt{ac},

occurring with probabilities

25,15,15,15,\frac{2}{5}, \qquad \frac{1}{5}, \qquad \frac{1}{5}, \qquad \frac{1}{5},

respectively.

In standard terminology, the set of sentences alone is a language; V={a,b,c,}\mathcal{V} = \{ \texttt{a}, \texttt{b}, \texttt{c}, \dashv \}, where \dashv is the end-of-sequence token, so a complete sentence is a token sequence like b\texttt{b}\dashv. The language together with these frequencies is a probability distribution on V\mathcal{V}^*, called the data distribution, and it is what a trained model is meant to imitate.

The single most probable sentence is b\texttt{b}. So it may seem that a good model, predicting one token at a time, ought to begin with b\texttt{b}. But sentences beginning with a\texttt{a} have total probability 15+15+15=35\frac{1}{5} + \frac{1}{5} + \frac{1}{5} = \frac{3}{5}, so an ideal token predictor pθp_\theta, given the empty context c=c = \varnothing, in fact favors a\texttt{a}:

pθ(a)=35,pθ(b)=25,pθ(c)=0.p_\theta(\texttt{a} \mid \varnothing) = \frac{3}{5}, \qquad p_\theta(\texttt{b} \mid \varnothing) = \frac{2}{5}, \qquad p_\theta(\texttt{c} \mid \varnothing) = 0.

The remaining conditional distributions are read off from the data distribution in the same way: after b\texttt{b} the sentence is over, and each of the three sentences beginning with a\texttt{a} is equally likely among sentences beginning with a\texttt{a}, so

pθ(b)=1,pθ(aa)=pθ(ba)=pθ(ca)=13,p_\theta(\dashv \mid \texttt{b}) = 1, \qquad p_\theta(\texttt{a} \mid \texttt{a}) = p_\theta(\texttt{b} \mid \texttt{a}) = p_\theta(\texttt{c} \mid \texttt{a}) = \frac{1}{3},

and after any two-letter sentence, pθ((x,y))=1p_\theta(\dashv \mid (x,y)\,) = 1. Now the chain rule defining qθq_\theta from pθp_\theta recovers the data distribution exactly:

qθ(b)=pθ(b)pθ(b)=251=25,q_\theta(\texttt{b}\dashv) = p_\theta(\texttt{b} \mid \varnothing)\, p_\theta(\dashv \mid \texttt{b}) = \frac{2}{5} \cdot 1 = \frac{2}{5},

and

qθ(aa)=pθ(a)pθ(aa)pθ(aa)=35131=15,q_\theta(\texttt{aa}\dashv) = p_\theta(\texttt{a} \mid \varnothing)\, p_\theta(\texttt{a} \mid \texttt{a})\, p_\theta(\dashv \mid \texttt{aa}) = \frac{3}{5} \cdot \frac{1}{3} \cdot 1 = \frac{1}{5},

and likewise qθ(ab)=qθ(ac)=15q_\theta(\texttt{ab}\dashv) = q_\theta(\texttt{ac}\dashv) = \frac{1}{5}. 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 qθq_\theta from pθp_\theta). You might feel that a token predictor should output a\texttt{a} and a sentence predictor should output b\texttt{b} \dashv, 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 b\texttt{b}\dashv is the most likely sentence and a\texttt{a} 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:

  1. A training set, which is usually most of the corpus. This is used to set the parameters initially.
  2. 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.
  3. 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 S\mathcal{S} be a set of raw texts or strings (the stuff you type in). A tokenizer is an injection (“encoding”)

enc:SV\operatorname{enc} : \mathcal S \rightarrow \mathcal{V}^*

with a left inverse dec\operatorname{dec} (“decoding”), i.e. decenc(s)=s\operatorname{dec} \circ \operatorname{enc} (s) = s. This left-inverse property is referred to as losslessness.

It makes sense to choose your vocabulary V\mathcal{V} 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 V\mathcal{V} 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. nn-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 nn-gram models and defined as follows:

Definition 2.1. Let V\mathcal{V} be a vocabulary including one distinguished token *\texttt{*} called a beginning of sequence token. An nn-gram model is an autoregressive language model with the Markov assumption that for tnt \ge n,

P(θ,(x1,,xt1))=pθ(x1,,xt1)  =  pθ(xtn+1,,xt1)=P(θ,(xtn+1,,xt1)),P(\theta, (x_1, \ldots, x_{t-1})) = p_\theta(\cdot \mid x_1, \ldots, x_{t-1}) \;=\; p_\theta( \cdot \mid x_{t-n+1},\dots,x_{t-1}) = P(\theta, (x_{t-n+1}, \ldots, x_{t-1})),

and for t<nt < n,

P(θ,(x1,,xt1))=pθ(*,*,,*,x1,,xt1).P(\theta, (x_1, \ldots, x_{t-1})) = p_\theta( \cdot \mid \texttt{*}, \texttt{*}, \ldots, \texttt{*}, x_{1}, \ldots, x_{t-1} ).

In other words, the model output depends only on the previous n1n-1 tokens. So we need only consider contexts from Vn1V\mathcal V^{n-1} \subseteq \mathcal{V}^*. For a short context of length k<n1k < n-1, we simply prepend n1kn-1-k *\texttt{*} 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 *\texttt{*}. This definition is appropriate if we assume that our corpus and our language do not themselves contain the token *\texttt{*}. This extra token is merely a practical formality.

The model PP is parametrized by a matrix θΘMVn1×V(R)\theta \in \Theta \subseteq M_{V^{n-1} \times V}(\mathbb{R}) with entries

θc,b=pθ(bc)=P(θ,c)(b)\theta_{c,b} = p_\theta(b \mid c) = P(\theta, c)(b)

indexed by contexts cVn1c \in \mathcal V^{n-1} and next tokens bVb \in \mathcal{V}, subject to the condition that θc,Δ(V)\theta_{c,\cdot} \in \Delta(\mathcal V) for every cc, i.e. each cc-th row is a probability distribution, so the entries are non-negative with row sum 11. A matrix with this property is called a row-stochastic matrix.

The case n=1n=1 is a unigram model. Here the context is empty (Vn1=V0\mathcal{V}^{n-1} = \mathcal{V}^0 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 θ\theta is a 1×V1 \times V row-stochastic matrix, i.e. a single row, which is just an element of Δ(V)\Delta(\mathcal{V}).

Example 2.2 (a small unigram model). Take V={*,a,b,.}\mathcal{V} = \{\texttt{*}, \texttt{a}, \texttt{b}, \texttt{.}\}, so V=4V = 4. A unigram model is given by a 1×41 \times 4 row-stochastic matrix, for example

θ=(00.50.40.1),\theta = \begin{pmatrix} 0 & 0.5 & 0.4 & 0.1 \end{pmatrix},

where the columns are indexed by *,a,b,.\texttt{*}, \texttt{a}, \texttt{b}, \texttt{.} in that order. Thus this model never generates *\texttt{*}; regardless of what has come before, it predicts a\texttt{a} with probability 0.50.5, b\texttt{b} with probability 0.40.4, and .\texttt{.} with probability 0.10.1. It produces text with the right letter frequencies but no structure at all, such as ba.aabbaa\texttt{ba.aabbaa}.

The case n=2n=2 is a bigram model; its parameter matrix θ\theta is a V×VV\times V 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. Vn1=V\mathcal{V}^{n-1} = \mathcal{V}.

Example 2.3 (a small bigram model). With the same V={*,a,b,.}\mathcal{V} = \{\texttt{*}, \texttt{a}, \texttt{b}, \texttt{.}\}, a bigram model is given by a 4×44 \times 4 row-stochastic matrix. One choice is

θ=(00.50.5000.10.80.100.70.20.100.50.50),\theta = \begin{pmatrix} 0 & 0.5 & 0.5 & 0 \\ 0 & 0.1 & 0.8 & 0.1 \\ 0 & 0.7 & 0.2 & 0.1 \\ 0 & 0.5 & 0.5 & 0 \end{pmatrix},

where both rows (contexts) and columns (next tokens) are indexed by *,a,b,.\texttt{*}, \texttt{a}, \texttt{b}, \texttt{.} 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 a\texttt{a}-row says that after seeing a\texttt{a}, the model predicts b\texttt{b} with probability θa,b=pθ(ba)=0.8\theta_{\texttt{a},\texttt{b}} = p_\theta(\texttt{b} \mid \texttt{a}) = 0.8. After the first token, the model tends to produce alternating text like abababab.\texttt{abababab.}, since each of a\texttt{a} and b\texttt{b} strongly prefers the other as its successor; the last row says that after .\texttt{.} the model chooses a\texttt{a} or b\texttt{b} with equal probability, and never produces .\texttt{.} twice in a row.


3. Maximum likelihood

Training is the process of incrementally adjusting θ\theta 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 (x1,,xT)V(x_1, \ldots, x_T) \in \mathcal{V}^*. The likelihood of θΘ\theta \in \Theta for this training set is

L(θ)=L(θ:x1,,xT):=qθ(T)(x1,,xT).L(\theta)=L(\theta : x_1, \ldots, x_T) := q_\theta^{(T)}( x_1, \ldots, x_T).

We are thinking of the training set as fixed, so that this is a function on θΘ\theta \in \Theta with values in [0,1][0,1]:

L():Θ[0,1].L( \cdot ) : \Theta \rightarrow [0,1].

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 θ\theta thinks the training set is. We want to choose θ\theta to maximize this.

The log likelihood is the function

logL ⁣:Θ[,0].\log L \colon \Theta \to [-\infty,0].

Don’t worry about log0\log 0 for right now.

A maximum likelihood estimator is any maximizer θ^\widehat{\theta} of the log likelihood as a function of θ\theta. The log is just more convenient to work with. That is, θ^\widehat{\theta} is an element of Θ\Theta at which a maximum occurs.

For any token string x=(x1,,xT)x=(x_1,\ldots,x_T), define the model’s average negative log-likelihood, or average log loss, on xx by

L(θ:x1,,xT):=1TlogL(θ:x1,,xT)=1Tt=1Tlogpθ(xtx1,,xt1).\mathcal L(\theta : x_1,\ldots,x_T) :=-\frac1T\log L(\theta : x_1,\ldots,x_T) =-\frac1T\sum_{t=1}^T\log p_\theta(x_t\mid x_1,\ldots,x_{t-1}).

For the fixed training set, we abbreviate

L(θ):=L(θ:x1,,xT),\mathcal L(\theta):=\mathcal L(\theta : x_1,\ldots,x_T),

so that

L(θ)=1TlogL(θ).\mathcal L(\theta) =-\frac1T\log L(\theta).

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 log\log means logarithm to base 22, 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 θ^\widehat{\theta} that maximizes the log likelihood logL\log L, or, equivalently, finding its entries θ^a,b\widehat{\theta}_{a,b} for all a,bVa,b \in \mathcal{V}.

Let *V\texttt{*}\in\mathcal V denote the beginning of sequence token, and set x0=*x_0=\texttt{*}. Recall that the training set (x1,,xT)(x_1,\ldots,x_T) does not contain the token *\texttt{*}. For a,bVa,b\in\mathcal V, let Na,bN_{a,b} count the occurrences of the sequence abab in the training set, including the initial transition (x0,x1)=(*,x1)(x_0,x_1)=(\texttt{*},x_1), i.e.

Na,b=#{i{1,,T}:(xi1,xi)=(a,b)},Na=bVNa,b.N_{a,b}=\#\{i\in\{1,\ldots,T\}:(x_{i-1},x_i)=(a,b)\}, \qquad N_a=\sum_{b\in\mathcal V}N_{a,b}.

Then for a*a\neq\texttt{*}, NaN_a counts the occurrences of aa in the training set (except in the last token), while

N*,x1=1,N*,b=0for bx1,N*=1.N_{\texttt{*},x_1}=1, \qquad N_{\texttt{*},b}=0 \quad\text{for }b\neq x_1, \qquad N_{\texttt{*}}=1.

Recall that for a bigram model, a context is just a single token.

Theorem 3.1 (Maximum Likelihood Estimator for the bigram model). Let θ^\widehat{\theta} be a maximum likelihood estimator for a bigram model. For every context aa with Na>0N_a>0, the aa-th row of θ^\widehat{\theta} is

θ^a,b=Na,bNa.\widehat\theta_{a,b}=\frac{N_{a,b}}{N_a}.

Any matrix satisfying this is a maximum likelihood estimator.

In other words, when Na=0N_a=0, the aa-th row may be chosen arbitrarily in Δ(V)\Delta(\mathcal V). Note that N*=1N_{\texttt{*}}=1, so the theorem also determines the *\texttt{*}-th row: θ^*,x1=1\widehat\theta_{\texttt{*},x_1}=1, i.e. the model is certain to begin with the same token the training set begins with.

Proof

We want to maximize

logL(θ:x1,,xT).\log L(\theta:x_1,\ldots,x_T).

For a bigram model, the conditional distribution of xix_i depends only on the preceding token. With the convention x0=*x_0=\texttt{*}, this gives

pθ(xix1,,xi1)=pθ(xixi1)=θxi1,xip_\theta(x_i\mid x_1,\ldots,x_{i-1}) = p_\theta(x_i\mid x_{i-1}) = \theta_{x_{i-1},x_i}

for every 1iT1\leq i\leq T. Therefore

L(θ:x1,,xT)=qθ(T)(x1,,xT)=i=1Tpθ(xix1,,xi1)=i=1Tθxi1,xi=a,bVθa,bNa,b.\begin{aligned} L(\theta:x_1,\ldots,x_T) &= q_\theta^{(T)}(x_1,\ldots,x_T)\\ &= \prod_{i=1}^T p_\theta(x_i\mid x_1,\ldots,x_{i-1})\\ &= \prod_{i=1}^T \theta_{x_{i-1},x_i}\\ &= \prod_{a,b\in\mathcal V} \theta_{a,b}^{N_{a,b}}. \end{aligned}

Taking logarithms, we obtain

logL(θ:x1,,xT)=a,bVNa,blogθa,b.\log L(\theta:x_1,\ldots,x_T) = \sum_{a,b\in\mathcal V} N_{a,b}\log\theta_{a,b}.

If Na=0N_a=0, then Na,b=0N_{a,b}=0 for every bVb\in\mathcal V, so the aa-th row contributes nothing to the log-likelihood. Hence that row may be chosen arbitrarily.

Now suppose that Na>0N_a>0 and define

θ^a,b=Na,bNa.\widehat\theta_{a,b} = \frac{N_{a,b}}{N_a}.

We claim that this is the unique choice of the aa-th row which maximizes its contribution to the log-likelihood. If θa,b=0\theta_{a,b}=0 for some bb with Na,b>0N_{a,b}>0, then the log-likelihood is -\infty, so we may assume that

θa,b>0\theta_{a,b}>0

whenever Na,b>0N_{a,b}>0.

Using the inequality

logxx1,\log x\leq x-1,

we have

bVNa,blogθa,bbVNa,blogθ^a,b=bVNa,b>0Na,blog(θa,bθ^a,b)bVNa,b>0Na,b(θa,bθ^a,b1)=bVNa,b>0(Naθa,bNa,b)=NabVNa,b>0θa,bNa0.\begin{aligned} &\sum_{b\in\mathcal V} N_{a,b}\log\theta_{a,b} - \sum_{b\in\mathcal V} N_{a,b}\log\widehat\theta_{a,b}\\ &\qquad= \sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} N_{a,b} \log\left( \frac{\theta_{a,b}}{\widehat\theta_{a,b}} \right)\\ &\qquad\leq \sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} N_{a,b} \left( \frac{\theta_{a,b}}{\widehat\theta_{a,b}}-1 \right)\\ &\qquad= \sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} \left( N_a\theta_{a,b}-N_{a,b} \right)\\ &\qquad= N_a \sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} \theta_{a,b} - N_a\\ &\qquad\leq 0. \end{aligned}

Here we used

bVθa,b=1andbVNa,b=Na.\sum_{b\in\mathcal V}\theta_{a,b}=1 \qquad\text{and}\qquad \sum_{b\in\mathcal V}N_{a,b}=N_a.

It follows that

logL(θ:x1,,xT)logL(θ^:x1,,xT).\log L(\theta:x_1,\ldots,x_T) \leq \log L(\widehat\theta:x_1,\ldots,x_T).

Moreover, equality in logxx1\log x\leq x-1 occurs only when x=1x=1. Hence equality forces

θa,b=θ^a,b=Na,bNa\theta_{a,b} = \widehat\theta_{a,b} = \frac{N_{a,b}}{N_a}

whenever Na,b>0N_{a,b}>0. Summing over those values of bb, we obtain

bVNa,b>0θa,b=bVNa,b>0Na,bNa=1NabVNa,b=1.\sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} \theta_{a,b} = \sum_{\substack{b\in\mathcal V\\N_{a,b}>0}} \frac{N_{a,b}}{N_a} = \frac{1}{N_a} \sum_{b\in\mathcal V}N_{a,b} = 1.

On the other hand, the aa-th row of θ\theta is a probability distribution, so

bVθa,b=1\sum_{b\in\mathcal V}\theta_{a,b}=1

and every θa,b0\theta_{a,b}\geq 0. Therefore

bVNa,b=0θa,b=0.\sum_{\substack{b\in\mathcal V\\N_{a,b}=0}} \theta_{a,b}=0.

Since each term in this sum is nonnegative, it follows that

θa,b=0\theta_{a,b}=0

whenever Na,b=0N_{a,b}=0. Thus, for every aa with Na>0N_a>0, the unique maximizing row is

θ^a,b=Na,bNa.\widehat\theta_{a,b} = \frac{N_{a,b}}{N_a}.

This proves the result. \square

Remark 3.2 (parameter sharing). The proof separates the likelihood question into VV 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 θ^\widehat{\theta} are problematic. This motivates the following adjustment to θ^\widehat{\theta}.

Definition 3.3 (Laplace smoothing). For α>0\alpha>0, the Laplace-smoothed estimator is

θ^a,b(α)=Na,b+αNa+αV.\widehat\theta^{(\alpha)}_{a,b} =\frac{N_{a,b}+\alpha}{N_a+\alpha V}.

In a Laplace-smoothed estimator, every coordinate is strictly positive.


4. Perplexity

We need a way to compare trained models (compare different values of θ\theta). 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 (x1,,xN)(x_1, \ldots, x_N), also called the test set. Then the perplexity of the model on the test set is

PPLθ(x1,,xN):=qθ(N)(x1,,xN)1/N=i=1Npθ(xix1,,xi1)1/N.PPL_\theta(x_1, \ldots, x_N) := q_\theta^{(N)}( x_1, \ldots, x_N)^{-1/N} = \prod_{i=1}^N p_\theta( x_i \mid x_1, \ldots, x_{i-1})^{-1/N}.

Example 4.1. In the unigram model,

PPLθ(x1,,xN)=i=1Npθ(xi)1/N,PPL_\theta(x_1, \ldots, x_N) = \prod_{i=1}^N p_\theta(x_i)^{-1/N},

and in the bigram model,

PPLθ(x1,,xN)=i=1Npθ(xixi1)1/N.PPL_\theta(x_1, \ldots, x_N) = \prod_{i=1}^N p_\theta( x_i | x_{i-1})^{-1/N}.

For example, if V={a,b,c}\mathcal{V} = \{ \texttt{a}, \texttt{b}, \texttt{c}\}, and all are assigned equal probability in a unigram model, then every factor in the product is pθ(xi)=1/3p_\theta(x_i) = 1/3, so for a string of length NN,

PPLθ(x1,,xN)=((1/3)N)1/N=3.PPL_\theta(x_1, \ldots, x_N) = \left( (1/3)^N \right)^{-1/N} = 3.

Intuitively, choosing the next token amounts to picking one of three equal options. On the other hand, using the same vocabulary V\mathcal{V}, if pθ(a)=0.8p_\theta(\texttt{a}) = 0.8 while pθ(b)=0.1p_\theta(\texttt{b}) = 0.1 and pθ(c)=0.1p_\theta(\texttt{c}) = 0.1, then the perplexity of a string changes with the string. For example,

PPLθ(aaa)=(pθ(a)pθ(a)pθ(a))1/3=(0.83)1/3=10.8=54=1.25,PPL_\theta(\texttt{aaa}) = \left( p_\theta(\texttt{a})\,p_\theta(\texttt{a})\,p_\theta(\texttt{a}) \right)^{-1/3} = \left( 0.8^3 \right)^{-1/3} = \frac{1}{0.8} = \frac{5}{4} = 1.25,

while

PPLθ(abc)=(pθ(a)pθ(b)pθ(c))1/3=(810110110)1/3=(10008)1/3=1081/3=5.PPL_\theta(\texttt{abc}) = \left( p_\theta(\texttt{a})\,p_\theta(\texttt{b})\,p_\theta(\texttt{c}) \right)^{-1/3} = \left( \frac{8}{10} \cdot \frac{1}{10} \cdot \frac{1}{10} \right)^{-1/3} = \left( \frac{1000}{8} \right)^{1/3} = \frac{10}{8^{1/3}} = 5.

So this model, which prefers the token a\texttt{a} (i.e., thinks it is more probable), is much more perplexed by the less likely string abc\texttt{abc} than by the unsurprising aaa\texttt{aaa}.

The goal is to measure how good a model is. We want qθ(x1,,xN)q_\theta(x_1, \ldots, x_N) to be high when (x1,,xN)(x_1, \ldots, x_N) 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 qθ(x1,,xN)q_\theta(x_1, \ldots, x_N) of the test set is a natural candidate. However, by nature, qθ(x1,,xN)q_\theta(x_1, \ldots, x_N) will be lower on long strings (we’re multiplying probabilities 0pθ(xix<i)10\leq p_\theta(x_i | x_{<i})\leq 1, so the more xix_i‘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 a\texttt{a}, one of which is b\texttt{b}, and one of which is c\texttt{c}. Then choosing b\texttt{b} is “like” choosing 1 of 10 branches. This motivates the following definition: the branching factor of a token xx given context cc (the choice of xx at node cc) is the inverse of the probability pθ(xc)p_\theta(x | c). We say that the choice of b\texttt{b} has a branching factor of 1010, while the choice of a\texttt{a} has a branching factor of 10/8=5/410/8 = 5/4. 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:

PPLθ(abc)=(541010)1/3=1251/3=5.PPL_\theta(\texttt{abc}) = \left( \frac{5}{4} \cdot 10 \cdot 10 \right)^{1/3} = 125^{1/3} = 5.
a a a a a a a a b c node c
The distribution p(a) = 8/10, p(b) = p(c) = 1/10, pictured as ten equally likely branches at the node c: choosing b takes 1 branch of 10 (branching factor 10), while choosing a takes 8 of the 10 (branching factor 10/8).

For an nn-gram model, the probabilities of the first n1n-1 tokens are computed using the *\texttt{*}-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 VV has perplexity exactly VV on any test set.

Proof

Every next-token probability is 1/V1/V, so qθ(N)(x1,,xN)=VNq_\theta^{(N)}(x_1, \ldots, x_N) = V^{-N} and PPL=(VN)1/N=VPPL = (V^{-N})^{-1/N} = V. \square


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 pp be a probability distribution on a finite set X\mathcal X.

Definition 5.1 (entropy). The entropy of pp is

H(p)=xXp(x)logp(x).H(p) = -\sum_{x\in\mathcal X} p(x)\log p(x).

The quantity

logp(x)-\log p(x)

is sometimes called the information content or surprisal of xx. 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 pp:

H(p)=xXp(x)(logp(x)).H(p) = \sum_{x\in\mathcal X}p(x)\bigl(-\log p(x)\bigr).

If the logarithm is base 22, 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 nn, recall that the chain rule gives a probability distribution on Vn\mathcal V^n:

qθ(n)(x1,,xn):=t=1npθ(xtx1,,xt1).q_\theta^{(n)}(x_1,\ldots,x_n) := \prod_{t=1}^n p_\theta(x_t\mid x_1,\ldots,x_{t-1}).

This is the fixed-length distribution introduced in Section 0; here we keep the superscript nn explicit because we will compare distributions for different string lengths.

Its entropy is

H(qθ(n))=(x1,,xn)Vnqθ(n)(x1,,xn)logqθ(n)(x1,,xn).H(q_\theta^{(n)}) = -\sum_{(x_1,\ldots,x_n)\in\mathcal V^n} q_\theta^{(n)}(x_1,\ldots,x_n) \log q_\theta^{(n)}(x_1,\ldots,x_n).

This measures the average information contained in a string of length nn. To obtain an average per token, we divide by nn.

Definition 5.2 (entropy rate). Suppose that the limit exists. The entropy rate of the stochastic process described by qθq_\theta is

h(qθ):=limn1nH(qθ(n)).h(q_\theta) := \lim_{n\to\infty} \frac{1}{n}H(q_\theta^{(n)}).

Thus H(qθ(n))H(q_\theta^{(n)}) measures the average information in an entire length-nn string, while h(qθ)h(q_\theta) 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 \dashv-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

X1,X2,X3,X_1,X_2,X_3,\ldots

is a stationary ergodic stochastic process with joint distributions qθ(n)q_\theta^{(n)}.

Stationary and ergodic. A stochastic process is simply a sequence of random variables X1,X2,X_1,X_2,\ldots, in our case taking values in the vocabulary V\mathcal V. It is stationary if its statistical behavior does not depend on where we are in the sequence: for every k,n1k,n\geq 1,

(X1,,Xn)and(Xk+1,,Xk+n)(X_1,\ldots,X_n) \qquad\text{and}\qquad (X_{k+1},\ldots,X_{k+n})

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 nn-gram model uses the same finite-memory prediction rule at every position: the probability of the next token depends only on the preceding n1n-1 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

s=(x1,x2,x3,)s=(x_1,x_2,x_3,\ldots)

from the process. The quantity

logqθ(n)(x1,,xn)-\log q_\theta^{(n)}(x_1,\ldots,x_n)

measures how surprising its first nn tokens are under the model, and hence

1nlogqθ(n)(x1,,xn)-\frac{1}{n}\log q_\theta^{(n)}(x_1,\ldots,x_n)

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 X1,X2,X_1,X_2,\ldots be a stationary ergodic stochastic process on the finite vocabulary V\mathcal V. Then, with probability 11,

1nlogqθ(n)(X1,,Xn)h(qθ).-\frac{1}{n} \log q_\theta^{(n)}(X_1,\ldots,X_n) \longrightarrow h(q_\theta).

There are two rather different-looking ways to compute the same number. The definition

1nH(qθ(n))=1n(x1,,xn)Vnqθ(n)(x1,,xn)logqθ(n)(x1,,xn)\frac{1}{n}H(q_\theta^{(n)}) = -\frac{1}{n} \sum_{(x_1,\ldots,x_n)\in\mathcal V^n} q_\theta^{(n)}(x_1,\ldots,x_n) \log q_\theta^{(n)}(x_1,\ldots,x_n)

averages over all possible strings of length nn, 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

(x1,x2,)(x_1,x_2,\ldots)

and compute

1nlogqθ(n)(x1,,xn).-\frac{1}{n}\log q_\theta^{(n)}(x_1,\ldots,x_n).

As nn 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,

1nlogqθ(n)(x1,,xn)=1nlogt=1npθ(xtx1,,xt1)=1nt=1nlogpθ(xtx1,,xt1).\begin{aligned} -\frac{1}{n}\log q_\theta^{(n)}(x_1,\ldots,x_n) &= -\frac{1}{n}\log \prod_{t=1}^n p_\theta(x_t\mid x_1,\ldots,x_{t-1})\\ &= -\frac{1}{n} \sum_{t=1}^n \log p_\theta(x_t\mid x_1,\ldots,x_{t-1}). \end{aligned}

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 (x1,,xN)(x_1,\ldots,x_N), Section 4 defined

PPLθ(x1,,xN)=qθ(N)(x1,,xN)1/N.PPL_\theta(x_1,\ldots,x_N) = q_\theta^{(N)}(x_1,\ldots,x_N)^{-1/N}.

Taking logarithms gives

logPPLθ(x1,,xN)=1Nlogqθ(N)(x1,,xN).\log PPL_\theta(x_1,\ldots,x_N) = -\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N).

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:

logPPLθ(X1,,XN)h(qθ).\log PPL_\theta(X_1,\ldots,X_N) \longrightarrow h(q_\theta).

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 (x1,,xN)V(x_1,\ldots,x_N)\in\mathcal V^* be any sequence of tokens — for instance, the training set. Then for every θΘ\theta\in\Theta,

logPPLθ(x1,,xN)=L(θ:x1,,xN).\log PPL_\theta(x_1,\ldots,x_N) = \mathcal L( \theta : x_1,\ldots,x_N).

Consequently, for the training set, θ^\widehat{\theta} is a maximum likelihood estimator if and only if it minimizes the training loss L(θ)\mathcal L(\theta), and this is equivalent to minimizing training perplexity.

Proof

By definition,

PPLθ(x1,,xN)=qθ(N)(x1,,xN)1/N.PPL_\theta(x_1,\ldots,x_N) = q_\theta^{(N)}(x_1,\ldots,x_N)^{-1/N}.

Therefore

logPPLθ(x1,,xN)=1Nlogqθ(N)(x1,,xN)=1Nt=1Nlogpθ(xtx1,,xt1)=L(θ:x1,,xN).\begin{aligned} \log PPL_\theta(x_1,\ldots,x_N) &= -\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N)\\ &= -\frac{1}{N} \sum_{t=1}^N \log p_\theta(x_t\mid x_1,\ldots,x_{t-1})\\ &= \mathcal L(\theta:x_1,\ldots,x_N). \end{aligned}

The middle equality is the autoregressive factorization of the string probability.

Now fix the training set and regard these quantities as functions of θ\theta. Maximizing its likelihood

L(θ:x1,,xN)=qθ(N)(x1,,xN)L(\theta:x_1,\ldots,x_N) = q_\theta^{(N)}(x_1,\ldots,x_N)

is equivalent to minimizing

1Nlogqθ(N)(x1,,xN)=logPPLθ(x1,,xN).-\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N) = \log PPL_\theta(x_1,\ldots,x_N).

Since the logarithm is strictly increasing, this is in turn equivalent to minimizing PPLθ(x1,,xN)PPL_\theta(x_1,\ldots,x_N). \square

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 X\mathcal X is a finite set and pp is a probability distribution on X\mathcal X, and take all logarithms in base 22. Recall that

log2p(x)-\log_2 p(x)

is the surprisal of xx. Coding theory gives this quantity another interpretation: it measures, roughly, how many bits we should need to record the outcome xx. Common outcomes should be cheap to describe, while rare outcomes can be assigned longer descriptions.

A binary code assigns to each xXx\in\mathcal X a finite string of 00‘s and 11‘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 (x)\ell(x) denotes the length of the codeword assigned to xx, then the expected number of bits needed to encode a symbol drawn from pp is

xXp(x)(x).\sum_{x\in\mathcal X}p(x)\ell(x).

A fundamental result of coding theory says that this expected length is bounded below by the entropy

H(p)=xXp(x)log2p(x).H(p)=-\sum_{x\in\mathcal X}p(x)\log_2p(x).

For a concrete example, suppose

X={0,1,,7}.\mathcal X=\{0,1,\ldots,7\}.

One simple code is to use the ordinary three-bit binary representations:

0000,1001,2010,,7111.0\mapsto\texttt{000},\qquad 1\mapsto\texttt{001},\qquad 2\mapsto\texttt{010},\qquad \ldots,\qquad 7\mapsto\texttt{111}.

Every codeword has length 33, so for every probability distribution pp on X\mathcal X, the expected code length is

xXp(x)3=3.\sum_{x\in\mathcal X}p(x)\cdot 3=3.

Now suppose that the distribution is very far from uniform:

p(0)=12,p(1)=14,p(2)=18,p(3)=116,p(4)=p(5)=p(6)=p(7)=164.p(0)=\frac12,\qquad p(1)=\frac14,\qquad p(2)=\frac18,\qquad p(3)=\frac1{16},\qquad p(4)=p(5)=p(6)=p(7)=\frac1{64}.

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 00 and also three bits on the much rarer symbol 77.

We can do better by assigning shorter codewords to more likely symbols and longer codewords to less likely symbols. Consider the following prefix code:

xxcodewordlengthp(x)p(x)
000\texttt{0}111/21/2
1110\texttt{10}221/41/4
22110\texttt{110}331/81/8
331110\texttt{1110}441/161/16
44111100\texttt{111100}661/641/64
55111101\texttt{111101}661/641/64
66111110\texttt{111110}661/641/64
77111111\texttt{111111}661/641/64

For example, after reading the bit 0\texttt{0} we know immediately that the symbol was 00, while a word beginning with 1\texttt{1} 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

12(1)+14(2)+18(3)+116(4)+464(6)=2.\frac12(1)+\frac14(2)+\frac18(3)+\frac1{16}(4) +\frac4{64}(6) =2.

Thus adapting the code to the probability distribution reduces the average length from 33 bits to 22 bits.

Now compare this with the entropy. In this example,

log2p(x)-\log_2p(x)

takes the values 1,2,3,41,2,3,4 for x=0,1,2,3x=0,1,2,3, respectively, and the value 66 for x=4,5,6,7x=4,5,6,7. Hence

H(p)=xp(x)log2p(x)=12(1)+14(2)+18(3)+116(4)+464(6)=2.\begin{aligned} H(p) &= -\sum_xp(x)\log_2p(x)\\ &= \frac12(1)+\frac14(2)+\frac18(3)+\frac1{16}(4) +\frac4{64}(6)\\ &=2. \end{aligned}

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,

xXp(x)3>2=H(p).\sum_{x\in\mathcal X}p(x)\cdot 3 > 2 = H(p).

This calculation tells us right away that the ordinary three-bit encoding is not optimal.

In fact, our second code has

(x)=log2p(x)\ell(x)=-\log_2p(x)

for every xx. 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 log2p(x)-\log_2p(x) need not be. Thus for a general distribution there may be no prefix code for individual symbols whose expected length is exactly H(p)H(p). Nevertheless, entropy remains the fundamental limit. If we encode long blocks of independent symbols drawn from pp, the source coding theorem says that the average number of bits per symbol can be made arbitrarily close to H(p)H(p), but not asymptotically smaller than H(p)H(p).

For comparison, if pp is uniform on X\mathcal X, then

H(p)=log28=3,H(p)=\log_2 8=3,

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 cVc \in \mathcal V^*, imagine that the language itself has some true, but unknown, next-token distribution

p(c)Δ(V),p_*(\,\cdot\mid c)\in\Delta(\mathcal V),

while our trained model predicts

pθ(c)Δ(V).p_\theta(\,\cdot\mid c)\in\Delta(\mathcal V).

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 XX is drawn according to p(c)p_*(\,\cdot\mid c). If X=xX=x, the model incurs the log loss

logpθ(xc).-\log p_\theta(x\mid c).

Averaging this loss over the possible tokens that the language might actually produce gives

xVp(xc)logpθ(xc).-\sum_{x\in\mathcal V} p_*(x\mid c)\log p_\theta(x\mid c).

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 pp and qq be probability distributions on a finite set X\mathcal X. The cross-entropy of pp relative to qq is

H(p,q)=xXp(x)logq(x).H(p,q) = -\sum_{x\in\mathcal X}p(x)\log q(x).

If p(x)>0p(x)>0 but q(x)=0q(x)=0 for some xx, we set H(p,q)=+H(p,q)=+\infty.

The two distributions play different roles. The distribution pp tells us how often each outcome actually occurs, so it supplies the weights in the average. The distribution qq tells us how surprising that outcome is according to the model, through the quantity

logq(x).-\log q(x).

Thus

H(p,q)=xXp(x)(logq(x))H(p,q) = \sum_{x\in\mathcal X} p(x)\bigl(-\log q(x)\bigr)

is the average surprisal of an outcome drawn according to pp, when surprisal is measured using the probabilities qq.

For a language model, pp represents the true language and qq represents the model. At a fixed context cc, the true language produces the next token xx with probability p(xc)p_*(x\mid c), while the model assigns that token the surprisal

logpθ(xc).-\log p_\theta(x\mid c).

Averaging over all possible next tokens therefore gives

xVp(xc)logpθ(xc).-\sum_{x\in\mathcal V} p_*(x\mid c)\log p_\theta(x\mid c).

This is the cross-entropy of the true next-token distribution relative to the model’s next-token distribution.

Compare this with entropy:

H(p)=xXp(x)(logp(x)).H(p) = \sum_{x\in\mathcal X} p(x)\bigl(-\log p(x)\bigr).

Entropy uses pp both to determine how often an outcome occurs and to measure its surprisal. Cross-entropy uses pp to determine how often the outcome occurs, but uses qq to measure its surprisal. We should therefore expect

H(p,q)H(p),H(p,q)\geq H(p),

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 pp and qq,

H(p,q)H(p),H(p,q)\geq H(p),

with equality if and only if p=qp=q.

Let’s return to language models and long strings. The true next-token distributions p(c)p_*(\cdot\mid c), when combined by the same chain rule as the model, determine joint distributions q(n)q_*^{(n)} on length-nn strings. Thus q(n)q_*^{(n)} is the true, unknown distribution of length-nn text, while qθ(n)q_\theta^{(n)} is the distribution assigned by the model. The cross-entropy

H(q(n),qθ(n))=(x1,,xn)Vnq(n)(x1,,xn)logqθ(n)(x1,,xn)H\bigl(q_*^{(n)},q_\theta^{(n)}\bigr) = -\sum_{(x_1,\ldots,x_n)\in\mathcal V^n} q_*^{(n)}(x_1,\ldots, x_n) \log q_\theta^{(n)}(x_1,\ldots, x_{n})

is the expected log loss of the model on a length-nn string generated by the true language. Dividing by nn gives the expected log loss per token.

When the limit exists, we call

h(q,qθ):=limn1nH(q(n),qθ(n))h(q_*,q_\theta) := \lim_{n\to\infty} \frac{1}{n} H\bigl(q_*^{(n)},q_\theta^{(n)}\bigr)

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 qq_*, which is unknown. To see how we can nevertheless estimate it from data, rewrite the finite-length cross-entropy per token as

1NH(q(N),qθ(N))=(x1,,xN)VNq(N)(x1,,xN)(1Nlogqθ(N)(x1,,xN)).\frac{1}{N}H\bigl(q_*^{(N)},q_\theta^{(N)}\bigr) = \sum_{(x_1,\ldots,x_N)\in\mathcal V^N} q_*^{(N)}(x_1,\ldots,x_N) \left( -\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N) \right).

This formula separates the roles of the true language and the model very clearly. The true distribution q(N)q_*^{(N)} tells us how likely each length-NN string is to occur, and therefore supplies the weights in the average. For each possible string, the quantity

1Nlogqθ(N)(x1,,xN)-\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N)

measures how surprising that string is according to the model, per token.

In practice, we do not know the weights q(N)q_*^{(N)}, so we cannot perform the sum over all possible strings. What we do have is a held-out string

(x1,,xN)(x_1,\ldots,x_N)

of actual language that was not used to train the model. For this observed string we can compute the quantity appearing inside the average:

1Nlogqθ(N)(x1,,xN)=1Nt=1Nlogpθ(xtx1,,xt1)=L(θ:x1,,xN).\begin{aligned} -\frac{1}{N}\log q_\theta^{(N)}(x_1,\ldots,x_N) &= -\frac{1}{N} \sum_{t=1}^N \log p_\theta(x_t\mid x_1,\ldots,x_{t-1})\\ &=\mathcal L(\theta:x_1,\ldots,x_N). \end{aligned}

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 qq_* is a stationary ergodic source and

(X1,X2,)(X_1,X_2,\ldots)

is sampled from qq_*, then, with probability 11,

1Nlogq(N)(X1,,XN)h(q).-\frac{1}{N}\log q_*^{(N)}(X_1,\ldots,X_N) \longrightarrow h(q_*).

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 qθq_\theta. Under suitable stationary and ergodic hypotheses on the source and model, a relative form of the Shannon—McMillan—Breiman theorem gives

1Nlogqθ(N)(X1,,XN)h(q,qθ)with probability 1,-\frac{1}{N}\log q_\theta^{(N)}(X_1,\ldots,X_N) \longrightarrow h(q_*,q_\theta) \qquad\text{with probability 1,}

where the sequence X1,X2,X_1,X_2,\ldots is generated according to the true source qq_*.

The distinction between the two formulas is worth emphasizing. In the entropy formula, the source qq_* both generates and scores the string. In the cross-entropy formula, the source qq_* generates the string, but the model qθq_\theta scores it. Consequently, for one sufficiently long held-out sample,

1Nlogqθ(N)(X1,,XN)-\frac{1}{N}\log q_\theta^{(N)}(X_1,\ldots,X_N)

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 qq_*.

But we have already encountered exactly the quantity

1Nlogqθ(N)(x1,,xN).-\frac{1}{N}\log q_\theta^{(N)}(x_1,\ldots,x_N).

By the definition of perplexity,

PPLθ(x1,,xN)=qθ(N)(x1,,xN)1/N,PPL_\theta(x_1,\ldots,x_N) = q_\theta^{(N)}(x_1,\ldots,x_N)^{-1/N},

and therefore

logPPLθ(x1,,xN)=1Nlogqθ(N)(x1,,xN).\log PPL_\theta(x_1,\ldots,x_N) = -\frac{1}{N} \log q_\theta^{(N)}(x_1,\ldots,x_N).

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 nn: q(n)q_*^{(n)}, the true distribution of the language, and qθ(n)q_\theta^{(n)}, the distribution predicted by the model. Their cross-entropy

H(q(n),qθ(n))H\bigl(q_*^{(n)},q_\theta^{(n)}\bigr)

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

H(q(n)).H\bigl(q_*^{(n)}\bigr).

Thus the difference

H(q(n),qθ(n))H(q(n))H\bigl(q_*^{(n)},q_\theta^{(n)}\bigr) - H\bigl(q_*^{(n)}\bigr)

measures the extra average log loss caused by using the model distribution qθ(n)q_\theta^{(n)} instead of the true distribution q(n)q_*^{(n)}. 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 pp and qq be probability distributions on a finite set X\mathcal X. The Kullback—Leibler divergence, or KL divergence, from pp to qq is

DKL(pq)=xXp(x)>0p(x)logp(x)q(x).D_{\mathrm{KL}}(p\|q) = \sum_{\substack{x\in\mathcal X\\p(x)>0}} p(x)\log\frac{p(x)}{q(x)}.

If p(x)>0p(x)>0 and q(x)=0q(x)=0 for some xx, we set

DKL(pq)=+.D_{\mathrm{KL}}(p\|q)=+\infty.

Equivalently,

DKL(pq)=H(p,q)H(p).D_{\mathrm{KL}}(p\|q) = H(p,q)-H(p).

Indeed,

H(p,q)H(p)=xXp(x)logq(x)+xXp(x)logp(x)=xXp(x)>0p(x)logp(x)q(x).\begin{aligned} H(p,q)-H(p) &= -\sum_{x\in\mathcal X}p(x)\log q(x) + \sum_{x\in\mathcal X}p(x)\log p(x)\\ &= \sum_{\substack{x\in\mathcal X\\p(x)>0}} p(x)\log\frac{p(x)}{q(x)}. \end{aligned}

As usual, terms with p(x)=0p(x)=0 contribute 00.

The identity

H(p,q)=H(p)+DKL(pq)H(p,q)=H(p)+D_{\mathrm{KL}}(p\|q)

is the most useful way to think about KL divergence here.

The entropy H(p)H(p) is the average surprisal when outcomes occur according to pp and we also use the correct probabilities pp to score them. The cross-entropy H(p,q)H(p,q) is the average surprisal when outcomes still occur according to pp, but we score them using the probabilities qq. Therefore

DKL(pq)D_{\mathrm{KL}}(p\|q)

measures the extra average log loss caused by using qq instead of pp.

Returning to language models,

DKL(q(n)qθ(n))D_{\mathrm{KL}} \bigl(q_*^{(n)}\|q_\theta^{(n)}\bigr)

therefore measures the extra expected log loss on length-nn text caused by using the model qθ(n)q_\theta^{(n)} rather than the true language distribution q(n)q_*^{(n)}.

Despite its name, KL divergence is not a distance: in general,

DKL(pq)DKL(qp),D_{\mathrm{KL}}(p\|q) \neq D_{\mathrm{KL}}(q\|p),

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 pp and qq,

DKL(pq)0,D_{\mathrm{KL}}(p\|q)\geq 0,

with equality if and only if p=qp=q.

Combining Gibbs’ inequality with

H(p,q)=H(p)+DKL(pq)H(p,q)=H(p)+D_{\mathrm{KL}}(p\|q)

immediately gives

H(p,q)H(p),H(p,q)\geq H(p),

with equality if and only if p=qp=q. This proves the cross-entropy lower bound from the preceding section.

For the language model distributions, we obtain for every nn

H(q(n),qθ(n))=H(q(n))+DKL(q(n)qθ(n)).H\bigl(q_*^{(n)},q_\theta^{(n)}\bigr) = H\bigl(q_*^{(n)}\bigr) + D_{\mathrm{KL}} \bigl(q_*^{(n)}\|q_\theta^{(n)}\bigr).

Thus the cross-entropy of the model on length-nn text decomposes into two parts:

cross-entropy=source entropy+model mismatch.\boxed{ \text{cross-entropy} = \text{source entropy} + \text{model mismatch}. }

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

dKL(qqθ):=limn1nDKL(q(n)qθ(n)).d_{\mathrm{KL}}(q_*\|q_\theta) := \lim_{n\to\infty} \frac{1}{n} D_{\mathrm{KL}} \bigl(q_*^{(n)}\|q_\theta^{(n)}\bigr).

Dividing the preceding identity by nn and taking limits gives

h(q,qθ)=h(q)+dKL(qqθ).h(q_*,q_\theta) = h(q_*) + d_{\mathrm{KL}}(q_*\|q_\theta).

In particular,

h(q,qθ)h(q).h(q_*,q_\theta)\geq h(q_*).

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 q(n)q_*^{(n)} and qθ(n)q_\theta^{(n)} on complete strings of length nn. Recall, however, that these distributions are built from the next-token distributions by

qθ(n)(x1,,xn)=t=1npθ(xtx1,,xt1).q_\theta^{(n)}(x_1,\ldots,x_n) = \prod_{t=1}^n p_\theta(x_t\mid x_1,\ldots,x_{t-1}).

Consequently,

logqθ(n)(x1,,xn)=t=1nlogpθ(xtx1,,xt1).-\log q_\theta^{(n)}(x_1,\ldots,x_n) = \sum_{t=1}^n -\log p_\theta(x_t\mid x_1,\ldots,x_{t-1}).

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

cpθ(c)Δ(V)c\longmapsto p_\theta(\,\cdot\mid c)\in\Delta(\mathcal V)

from contexts to next-token probability distributions.


8. Summary: measuring the quality of a language model

Let q(n)q_*^{(n)} denote the true distribution of length-nn text, and let qθ(n)q_\theta^{(n)} denote the distribution predicted by the language model.

The main quantities introduced above fit together as follows:

  • For an observed string (x1,,xN)(x_1,\ldots,x_N), the model’s average log loss is L(θ:x1,,xN)=1Nlogqθ(N)(x1,,xN)\mathcal L(\theta:x_1,\ldots,x_N) = -\frac1N\log q_\theta^{(N)}(x_1,\ldots,x_N). Smaller is better.

  • The perplexity of the model on this string is PPLθ(x1,,xN)=qθ(N)(x1,,xN)1/NPPL_\theta(x_1,\ldots,x_N) = q_\theta^{(N)}(x_1,\ldots,x_N)^{-1/N}. Thus logPPLθ(x1,,xN)=L(θ:x1,,xN)\log PPL_\theta(x_1,\ldots,x_N) = \mathcal L(\theta:x_1,\ldots,x_N). Perplexity is therefore just a monotone rescaling of the same measurement.

  • The cross-entropy rate h(q,qθ)h(q_*,q_\theta) is the idealized average log loss of the model on text generated by the true language. Since qq_* is unknown, in practice we estimate this quantity using average log loss, or equivalently perplexity, on held-out text.

  • The entropy rate h(q)h(q_*) measures the irreducible uncertainty in the language itself.

  • The difference between these two quantities is the KL divergence rate: h(q,qθ)=h(q)+dKL(qqθ)h(q_*,q_\theta) = h(q_*) + d_{\mathrm{KL}}(q_*\|q_\theta). 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 22. We have just seen that the average log loss

L(θ:x1,,xN)=1Nlog2qθ(N)(x1,,xN)\mathcal L(\theta:x_1,\ldots,x_N) = -\frac1N\log_2 q_\theta^{(N)}(x_1,\ldots,x_N)

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

(x1,,xt1),(x_1,\ldots,x_{t-1}),

the model assigns the next token xtx_t probability

pθ(xtx1,,xt1).p_\theta(x_t\mid x_1,\ldots,x_{t-1}).

A probability pθ(xtx<t)p_\theta(x_t\mid x_{<t}) corresponds to an ideal code length of approximately

log2pθ(xtx<t)-\log_2 p_\theta(x_t\mid x_{<t})

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 x1,,xt1x_1,\ldots,x_{t-1}, they know the same context as the sender and therefore know the same next-token distribution.

For a string

(x1,,xN),(x_1,\ldots,x_N),

the total idealized code length is therefore approximately

t=1Nlog2pθ(xtx1,,xt1)=log2t=1Npθ(xtx1,,xt1)=log2qθ(N)(x1,,xN).\begin{aligned} \sum_{t=1}^N -\log_2 p_\theta(x_t\mid x_1,\ldots,x_{t-1}) &= -\log_2 \prod_{t=1}^N p_\theta(x_t\mid x_1,\ldots,x_{t-1})\\ &= -\log_2 q_\theta^{(N)}(x_1,\ldots,x_N). \end{aligned}

Dividing by NN, the idealized bitrate is

1Nlog2qθ(N)(x1,,xN)-\frac1N \log_2 q_\theta^{(N)}(x_1,\ldots,x_N)

bits per token.

But this is exactly the average log loss of the model when logarithms are taken in base 22. Equivalently,

log2PPLθ(x1,,xN)=1Nlog2qθ(N)(x1,,xN).\log_2 PPL_\theta(x_1,\ldots,x_N) = -\frac1N \log_2 q_\theta^{(N)}(x_1,\ldots,x_N).

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 qq_*, but compressed using the probabilities supplied by the model qθq_\theta. For one observed string, the quantity

1Nlog2qθ(N)(x1,,xN)-\frac1N \log_2 q_\theta^{(N)}(x_1,\ldots,x_N)

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

h(q,qθ),h(q_*,q_\theta),

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 qq_* and used it for coding, the corresponding optimal rate would be the entropy rate

h(q).h(q_*).

By the identity from the preceding section,

h(q,qθ)=h(q)+dKL(qqθ).h(q_*,q_\theta) = h(q_*) + d_{\mathrm{KL}}(q_*\|q_\theta).

Thus the KL divergence rate measures the extra number of bits per token caused by using the imperfect model qθq_\theta instead of the true source distribution.

The code lengths

log2pθ(xtx<t)-\log_2 p_\theta(x_t\mid x_{<t})

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:

average log loss=log2(perplexity)bits per token.\boxed{ \text{average log loss} \quad=\quad \log_2(\text{perplexity}) \quad\approx\quad \text{bits per token}. }

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 ln2\ln 2 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:

modelnats/tokenbits/characterperplexity
uniform4.17446.022465.000
bigram (add-one)2.45493.541711.646
trigram (add-one)1.95322.81787.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 nn-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 V\mathcal V be a finite vocabulary containing a distinguished end-of-sequence token \dashv, and write

V0:=V{}\mathcal V_0:=\mathcal V\setminus\{\dashv\}

for the set of ordinary tokens. Fix a trained language model

P(θ,):VΔ(V),cpθ(c).P(\theta,\cdot):\mathcal V^*\longrightarrow\Delta(\mathcal V), \qquad c\longmapsto p_\theta(\,\cdot\mid c).

Thus, for every context cc,

aV0pθ(ac)+pθ(c)=1.\sum_{a\in\mathcal V_0}p_\theta(a\mid c) +p_\theta(\dashv\mid c)=1.

To sample from the model, we begin with the empty context. We draw a token according to pθ()p_\theta(\,\cdot\mid\varnothing). If that token is \dashv, we stop. Otherwise we append it to the context and repeat. In this way the model may produce

x1,x2,,xT,,xiV0.x_1,x_2,\ldots,x_T,\dashv, \qquad x_i\in\mathcal V_0.

We call such a sequence a complete sentence. The corresponding sentence, with the stopping symbol suppressed, is the finite string (x1,,xT)V0(x_1,\ldots,x_T)\in\mathcal V_0^*.

The chain rule suggests assigning to this complete sentence the probability

qθ(x1,,xT,):=(i=1Tpθ(xix<i))pθ(x1,,xT).q_\theta(x_1,\ldots,x_T,\dashv) := \left( \prod_{i=1}^T p_\theta(x_i\mid x_{<i}) \right) p_\theta(\dashv\mid x_1,\ldots,x_T).

For T=0T=0, the empty product is 11, so this formula says

qθ()=pθ().q_\theta(\dashv)=p_\theta(\dashv\mid\varnothing).

There is a small normalization issue. Although each pθ(c)p_\theta(\,\cdot\mid c) is a probability distribution, it does not automatically follow that the probabilities of all finite sentences sum to 11. There could, in principle, be positive probability that the model continues producing ordinary tokens forever and never emits \dashv.

The following proposition makes this precise.

Proposition A.1. The numbers qθ(x1,,xT,)q_\theta(x_1,\ldots,x_T,\dashv) satisfy

T=0 x1,,xTV0qθ(x1,,xT,)1.\sum_{T=0}^{\infty} \ \sum_{x_1,\ldots,x_T\in\mathcal V_0} q_\theta(x_1,\ldots,x_T,\dashv) \leq 1.

More precisely,

T=0 x1,,xTV0qθ(x1,,xT,)=Pr(the model eventually emits ).\sum_{T=0}^{\infty} \ \sum_{x_1,\ldots,x_T\in\mathcal V_0} q_\theta(x_1,\ldots,x_T,\dashv) = \Pr(\text{the model eventually emits }\dashv).

Hence these probabilities sum to 11 if and only if the model emits \dashv with probability 11.

Proof

For T0T\geq0, let HTH_T be the event that the model produces exactly TT ordinary tokens and then emits \dashv. For a fixed sequence x1,,xTV0x_1,\ldots,x_T\in\mathcal V_0, the probability of producing

x1,,xT,x_1,\ldots,x_T,\dashv

is, by the chain rule,

qθ(x1,,xT,).q_\theta(x_1,\ldots,x_T,\dashv).

The possible strings (x1,,xT)(x_1,\ldots,x_T) are mutually exclusive, so

Pr(HT)=x1,,xTV0qθ(x1,,xT,).\Pr(H_T) = \sum_{x_1,\ldots,x_T\in\mathcal V_0} q_\theta(x_1,\ldots,x_T,\dashv).

The events H0,H1,H2,H_0,H_1,H_2,\ldots are also mutually exclusive, and their union is exactly the event that the model eventually emits \dashv. Therefore

Pr(the model eventually emits )=T=0Pr(HT)=T=0 x1,,xTV0qθ(x1,,xT,).\begin{aligned} \Pr(\text{the model eventually emits }\dashv) &= \sum_{T=0}^{\infty}\Pr(H_T)\\ &= \sum_{T=0}^{\infty} \ \sum_{x_1,\ldots,x_T\in\mathcal V_0} q_\theta(x_1,\ldots,x_T,\dashv). \end{aligned}

The left-hand side is a probability, so it is at most 11.

Finally, either the model eventually emits \dashv, or it continues forever without emitting \dashv. Thus

Pr(the model eventually emits )=1Pr(the model never emits ).\Pr(\text{the model eventually emits }\dashv) = 1-\Pr(\text{the model never emits }\dashv).

The displayed sum is therefore equal to 11 precisely when the latter probability is 00. \square

A collection of nonnegative numbers whose total is at most 11 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:

1T=0 x1,,xTV0qθ(x1,,xT,)=Pr(the model never emits ).1- \sum_{T=0}^{\infty} \ \sum_{x_1,\ldots,x_T\in\mathcal V_0} q_\theta(x_1,\ldots,x_T,\dashv) = \Pr(\text{the model never emits }\dashv).

For example, if the probabilities of all finite sentences sum to 0.970.97, the remaining 0.030.03 is exactly the probability that the model generates ordinary tokens forever.

When the probability of continuing forever is 00, we say that the sampling process halts almost surely. Here “almost surely” is standard probability terminology: it means “with probability 11.” In that case, appending \dashv gives a bijection

V0{complete sentences},(x1,,xT)(x1,,xT,),\mathcal V_0^* \longleftrightarrow \{\text{complete sentences}\}, \qquad (x_1,\ldots,x_T) \longleftrightarrow (x_1,\ldots,x_T,\dashv),

and qθq_\theta therefore gives an ordinary probability distribution on finite sentences in V0\mathcal V_0^*.

There is a simple sufficient condition which guarantees this normalization. Suppose there is some ε>0\varepsilon>0 such that

pθ(c)εp_\theta(\dashv\mid c)\geq\varepsilon

for every context cc that can arise before the model stops. At each step, the probability of producing another ordinary token is then at most 1ε1-\varepsilon. Consequently, the probability that the model produces at least TT ordinary tokens without stopping is at most

(1ε)T.(1-\varepsilon)^T.

Since

(1ε)T0as T,(1-\varepsilon)^T\longrightarrow0 \qquad\text{as }T\longrightarrow\infty,

the probability that the model continues forever is 00. Hence the model halts almost surely, and its probabilities on finite sentences sum to 11.


Exercises (paired with Step 1)

  1. ★ Extend Theorem 3.1 to a general nn-gram model, implement the bigram estimator, and confirm an average log loss (cross-entropy) of 2.4549 nats for add-one smoothing.
  2. Show that the Laplace-smoothed estimator (Definition 3.3) is the mean of the posterior obtained from a Dirichlet(α,,α)\operatorname{Dirichlet}(\alpha,\ldots,\alpha) prior on the simplex and the observed counts. Determine the limits as α\alpha\to\infty and α0+\alpha\to0^+.
  3. ★ Compute perplexity for the uniform, bigram, and trigram models, and verify Proposition 4.2 numerically.
  4. Sampling versus scoring. Construct a distribution on {a,b}T\{\texttt{a},\texttt{b}\}^T with excellent training perplexity but poor samples.
  5. 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.
  6. Context length and training loss. Prove that the training loss of the kkth-order MLE is non-increasing in kk, and explain why this does not establish better held-out performance.
  7. Prove that CE(p,q)\operatorname{CE}(p,q) is convex in qq and that DKL(pq)D_{\mathrm{KL}}(p\|q) is jointly convex in (p,q)(p,q).

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.