A language model assigns probabilities to sequences of symbols. The model this book builds reads a name one character at a time and, after each character, gives a probability for every character that could come next. Multiplying those probabilities along a name gives the probability of the whole name, and training adjusts the model’s parameters to make the names in a list of real names probable.
This chapter sets up the probability behind that description and studies the simplest language model, in which the next character depends only on the current one. For that model the maximum-likelihood parameters have a closed form: they are relative frequencies of pairs, and we can compute them by counting. The same model written as a small neural network introduces embeddings, the vectors that represent tokens in every later model, and shows how a neural model shares information between tokens. The chapter ends with the problem that counting cannot solve, predicting from many earlier characters at once, which Chapter 10 takes up.
9.1 Tokens and vocabularies
A model computes with numbers and vectors, so text has to be cut into pieces from a fixed, finite list before the model can see it, and the model needs a way to tell where a piece of text starts and stops.
Take the name emma. Cut into characters it is \(\mathtt{e}, \mathtt{m}, \mathtt{m}, \mathtt{a}\). A model that reads it one character at a time must also learn which characters names start with and when a name ends, so we add a marker at both ends, written \(\diamond\): \[
(\diamond, \mathtt{e}, \mathtt{m}, \mathtt{m}, \mathtt{a}, \diamond).
\] The model reads this sequence from the left and, at each position, predicts the next symbol. From the leading \(\diamond\) it predicts the first letter \(\mathtt{e}\); from \(\diamond\,\mathtt{e}\) it predicts \(\mathtt{m}\); and from the whole name it predicts the closing \(\diamond\), which says that the name ends there. That is five predictions for a name of four letters. The first \(\diamond\) is never predicted; it only starts the sequence.
Definition 9.1 (Vocabulary and tokens) A vocabulary is a finite set \(V\) whose elements are called tokens; \(|V|\) is the number of tokens. A tokeniser turns a piece of text into a finite sequence of tokens. A character-level tokeniser makes each character a token. The boundary token\(\diamond\) is a token that marks the start and the end of a piece of text.
For names written in the 26 lower-case letters, the vocabulary is the 26 letters together with \(\diamond\), so \(|V| = 27\). A name of \(n\) letters becomes \(n + 2\) tokens and gives \(n + 1\) predictions.
Programs refer to tokens by number. The microgpt program that this book’s model follows (Karpathy 2026) numbers the letters \(\mathtt{a}, \dots, \mathtt{z}\) as \(0, \dots, 25\) and gives \(\diamond\) the number \(26\), so emma becomes \((26, 4, 12, 12, 0, 26)\). The numbers are labels. Nothing in a model may depend on \(\mathtt{b}\) having a number one larger than \(\mathtt{a}\), and Section 9.5 replaces each number by a vector that the model learns.
Character-level tokenisation keeps the vocabulary small. Large models for general text use tokens that are pieces of words, found by merging frequent pairs of symbols; GPT-2, for example, has a vocabulary of 50,257 tokens (Radford et al. 2019). Nothing in this chapter or the next depends on how the tokens were chosen.
The examples in this chapter use five names as a training corpus, the collection of text a model learns from: \[
\mathtt{anna}, \quad \mathtt{ava}, \quad \mathtt{emma}, \quad
\mathtt{eva}, \quad \mathtt{ada}.
\] To keep tables small, the examples use the vocabulary of the symbols that occur in these names, \(V = \{\diamond, \mathtt{a}, \mathtt{d}, \mathtt{e}, \mathtt{m}, \mathtt{n}, \mathtt{v}\}\), with \(|V| = 7\). The names have 17 letters between them, so they give \(17 + 5 = 22\) predictions.
9.2 The probability of a sequence
A language model gives a probability to a whole name by giving a probability to each prediction and multiplying. This section shows why multiplying is right. The tool is conditional probability, the probability of one event once we know that another has happened.
Choose one of the five corpus names at random, each with probability \(1/5\). The probability that the name starts with \(\mathtt{a}\) is \(3/5\) (anna, ava, ada). Once we know that it starts with \(\mathtt{a}\), only those three names remain, and one of them, ava, has \(\mathtt{v}\) second, so the probability of \(\mathtt{v}\) second is now \(1/3\). Multiplying gives \(\frac35\cdot\frac13 = \frac15\), which is the probability that the name begins av, counted directly: one name in five. The probability of the first two letters is the probability of the first, times the probability of the second given the first.
We work on a finite probability space (Definition 6.1), with random variables that take values in the vocabulary, as in Section 8.1. In the example, \(\Omega\) is the set of the five names, each with probability \(1/5\), and “starts with \(\mathtt{a}\)” is the event \(\{\mathtt{anna}, \mathtt{ava},
\mathtt{ada}\}\). The first letter \(X_1\) and the second letter \(X_2\) of the chosen name are random variables with values in the vocabulary. As in Definition 6.2, \(P(X_1 = x_1, \dots, X_t = x_t)\) is the probability of the event \(\{X_1 = x_1\}\cap\dots\cap\{X_t = x_t\}\) that all \(t\) statements hold.
Definition 9.2 (Conditional probability) Let \(A\) and \(B\) be events in a finite probability space with \(P(A) > 0\). The conditional probability of \(B\) given \(A\) is \[
P(B \mid A) = \frac{P(A\cap B)}{P(A)} .
\tag{9.1}\]
In words, \(P(B \mid A)\) is the probability of \(B\) when we keep only the outcomes in \(A\) and rescale their probabilities so that they sum to 1. In the example, \(A\) is “starts with \(\mathtt{a}\)”, \(B\) is “has \(\mathtt{v}\) second”, \(P(A\cap B) = 1/5\) and \(P(A) = 3/5\), so \(P(B\mid A) = 1/3\). Rearranged, Equation 9.1 says \(P(A\cap B) = P(A)\,P(B\mid A)\), and applying this once per position breaks the probability of a sequence into one factor per position.
Theorem 9.1 (Chain rule of probability) Let \(X_1, \dots, X_T\) be random variables on a finite probability space, with values in a vocabulary \(V\), and let \(x_1, \dots, x_T \in V\) satisfy \(P(X_1 = x_1, \dots, X_{T-1} = x_{T-1}) > 0\). Then \[
P(X_1 = x_1, \dots, X_T = x_T)
= \prod_{t=1}^{T} P(X_t = x_t \mid X_1 = x_1, \dots, X_{t-1} = x_{t-1}),
\tag{9.2}\] where the factor for \(t = 1\) is \(P(X_1 = x_1)\).
The probability of the whole sequence is the product, over the positions, of the probability of the token at that position given all the tokens before it.
Proof. Let \(A_0 = \Omega\) and, for \(t \ge 1\), \(A_t = \{X_1 = x_1\}\cap\dots\cap\{X_t = x_t\}\). Then \(A_t = A_{t-1}\cap\{X_t = x_t\}\), so \(A_t \subseteq A_{t-1}\), and the probabilities \(P(A_t)\) decrease as \(t\) grows. In particular \(P(A_{t-1}) \ge P(A_{T-1}) > 0\) for \(t = 1, \dots, T\), so every conditional probability in Equation 9.2 is defined. The factor for \(t\) is \(P(X_t = x_t \mid A_{t-1})\), and for \(t = 1\) this is \(P(X_1 = x_1 \mid \Omega) = P(X_1 = x_1)\) because \(P(\Omega) = 1\).
We prove by induction on \(t\) that \(P(A_t) = \prod_{s=1}^{t} P(X_s = x_s \mid A_{s-1})\) for \(t = 1, \dots, T\). For \(t = 1\) both sides are \(P(X_1 = x_1)\). If the statement holds for \(t - 1\), then by Equation 9.1, \[
P(A_t) = P(A_{t-1}\cap\{X_t = x_t\})
= P(A_{t-1})\,P(X_t = x_t \mid A_{t-1})
= \prod_{s=1}^{t} P(X_s = x_s \mid A_{s-1}) .
\] The case \(t = T\) is Equation 9.2.
If instead \(P(X_1 = x_1, \dots, X_{T-1} = x_{T-1}) = 0\), the left side of Equation 9.2 is \(0\) as well, because \(A_T \subseteq A_{T-1}\).
Example 9.1 In the example above, with \(X_1\) and \(X_2\) the first and second letters of a randomly chosen corpus name, \[
P(X_1 = \mathtt{a}, X_2 = \mathtt{v})
= P(X_1 = \mathtt{a})\,P(X_2 = \mathtt{v} \mid X_1 = \mathtt{a})
= \frac35\cdot\frac13 = \frac15 .
\] The theorem applies in the other order too: Exercise 9.2 conditions on the second letter first.
By Theorem 9.1, to give a probability to every sequence it is enough to give, for every possible beginning of a sequence, a probability distribution for the next token. That is how every model in this book is built.
Definition 9.3 (Language model) Let \(V\) be a vocabulary containing a boundary token \(\diamond\). A language model over \(V\) gives, for each finite sequence \((x_1, \dots, x_t)\) of tokens with \(x_1 = \diamond\), a probability distribution \(p(\,\cdot \mid x_1, \dots, x_t)\) on \(V\) for the next token. The sequence \((x_1, \dots, x_t)\) is the context. A document (a name, in our examples) is a finite sequence \(w = (w_1, \dots, w_n)\) of tokens other than \(\diamond\). It is wrapped as \(x = (x_1, \dots, x_{n+2}) = (\diamond, w_1, \dots, w_n, \diamond)\) and receives the probability \[
P(w) = \prod_{t=1}^{n+1} p(x_{t+1} \mid x_1, \dots, x_t) .
\tag{9.3}\]
Position \(t\) of the wrapped sequence holds the token \(x_t\), and the prediction made at position \(t\) is the distribution of \(x_{t+1}\), so positions and predictions are both numbered \(t = 1, \dots, n + 1\). Positions are numbered the same way in Chapter 10 and Chapter 11.
The product has one factor for each of the \(n + 1\) predictions: the probability that the model gives to the token that actually comes next, given everything before it. For emma the five factors are \[
p(\mathtt{e}\mid\diamond),\quad
p(\mathtt{m}\mid\diamond\,\mathtt{e}),\quad
p(\mathtt{m}\mid\diamond\,\mathtt{e}\,\mathtt{m}),\quad
p(\mathtt{a}\mid\diamond\,\mathtt{e}\,\mathtt{m}\,\mathtt{m}),\quad
p(\diamond\mid\diamond\,\mathtt{e}\,\mathtt{m}\,\mathtt{m}\,\mathtt{a}),
\] one for each prediction listed in Section 9.1. The model’s distributions play the part of the conditional probabilities in the chain rule (Equation 9.2). A model generates a document by the same route: start from \(\diamond\), draw a token from \(p(\,\cdot \mid \diamond)\), append it, draw the next token from the distribution for the longer context, and stop when it draws \(\diamond\). Exercise 9.6 shows that, under a mild condition, the probabilities of all documents sum to 1.
9.3 Bigram models
The simplest useful language model forgets everything but the latest token. To see what such a model should predict, look at what follows \(\mathtt{a}\) in the corpus. The wrapped names contain eight pairs that start with \(\mathtt{a}\): five times \(\mathtt{a}\) ends a name, and \(\mathtt{d}\), \(\mathtt{n}\) and \(\mathtt{v}\) each follow it once. A natural guess for the probability that \(\mathtt{a}\) is followed by the boundary token is \(5/8\), and \(1/8\) for each of the three letters. This section shows that the guess is the maximum-likelihood estimate. Shannon (1948) used models of this kind, built from frequencies of letter pairs in English, to generate imitations of English text.
Definition 9.4 (Bigram model) A bigram model is a language model whose next-token distribution depends only on the last token of the context: \(p(b \mid x_1, \dots, x_t) = p(b \mid x_t)\). It is given by \(|V|^2\) numbers \(p(b \mid a)\), the transition probabilities, with \[
p(b \mid a) \ge 0, \qquad \sum_{b\in V} p(b \mid a) = 1
\quad\text{for every } a \in V .
\]
The number \(p(b\mid a)\) is the probability that token \(b\) comes next when the current token is \(a\), and the conditions say that, for each current token, these probabilities form a distribution. Arranged as a \(|V|\times|V|\)transition matrix, row \(a\) lists the probabilities of the possible next tokens after \(a\), column \(b\) lists the probabilities of reaching \(b\) from each token, and each row sums to 1. A sequence in which each token is drawn from a distribution that depends only on the token before is called a Markov chain. Because each row sums to 1, the transition matrix sends the all-ones vector to itself: 1 is an eigenvalue with eigenvector \((1, \dots, 1)^\top\).
To fit a bigram model to data we choose the transition probabilities that make the data most probable. Write \(n_{ab}\) for the number of times token \(b\) follows token \(a\) in the corpus, counting the pairs in every wrapped name, and \(n_a = \sum_b n_{ab}\) for the number of pairs that start with \(a\). By Equation 9.3, the probability of one name is a product with one factor \(p(b \mid a)\) for each of its pairs. The names are treated as independent, so the probability of the corpus is the product over all names. Chapter 8 calls the probability that a model gives to the observed data, viewed as a function of the model’s parameters with the data held fixed, the likelihood (Definition 8.1). There the observations were independent draws from one distribution; here each factor is a transition probability, but the idea is the same. Gathering equal factors, the likelihood of the bigram model is \[
\mathcal{L}(p) = \prod_{a, b\in V} p(b \mid a)^{n_{ab}} ,
\] in which each transition probability appears once for every time its pair occurs. Maximising the likelihood is the same as maximising its logarithm, the log-likelihood \[
\ln\mathcal{L}(p) = \sum_{a, b\in V} n_{ab}\ln p(b\mid a) ,
\tag{9.4}\] where \(p\) stands for the whole table of transition probabilities, terms with \(n_{ab} = 0\) count as \(0\), and \(\ln\mathcal{L}(p) = -\infty\) if \(p(b\mid a) = 0\) for a pair with \(n_{ab} > 0\).
Counting the pairs takes a few lines of code. Here the boundary token is written as a full stop, and each line of output lists what followed one token.
names = ["anna", "ava", "emma", "eva", "ada"]counts = {}for name in names: tokens = ["."] +list(name) + ["."]for a, b inzip(tokens, tokens[1:]): counts[a, b] = counts.get((a, b), 0) +1for a insorted({a for a, _ in counts}):print(a, {b: n for (x, b), n insorted(counts.items()) if x == a})
. {'a': 3, 'e': 2}
a {'.': 5, 'd': 1, 'n': 1, 'v': 1}
d {'a': 1}
e {'m': 1, 'v': 1}
m {'a': 1, 'm': 1}
n {'a': 1, 'n': 1}
v {'a': 2}
The same counts form the matrix in Table 9.1. Row \(a\) lists what followed \(a\), the entry in column \(b\) is \(n_{ab}\), and the last column is the row total \(n_a\).
Table 9.1: Pair counts \(n_{ab}\) for the five names: row \(a\) is the earlier token, column \(b\) the later one.
\(a \backslash b\)
\(\diamond\)
\(\mathtt{a}\)
\(\mathtt{d}\)
\(\mathtt{e}\)
\(\mathtt{m}\)
\(\mathtt{n}\)
\(\mathtt{v}\)
\(n_a\)
\(\diamond\)
0
3
0
2
0
0
0
5
\(\mathtt{a}\)
5
0
1
0
0
1
1
8
\(\mathtt{d}\)
0
1
0
0
0
0
0
1
\(\mathtt{e}\)
0
0
0
0
1
0
1
2
\(\mathtt{m}\)
0
1
0
0
1
0
0
2
\(\mathtt{n}\)
0
1
0
0
0
1
0
2
\(\mathtt{v}\)
0
2
0
0
0
0
0
2
The maximiser of Equation 9.4 comes from Theorem 8.2: for observations treated as independent draws from one distribution on a finite set, the likelihood is largest at the relative frequencies of the observations and nowhere else. A bigram model holds one such distribution for each current token, and the theorem applies to one row of the transition matrix at a time.
Theorem 9.2 (Maximum likelihood for a bigram model) Let \(n_{ab}\) be the pair counts of a corpus over a vocabulary \(V\), and \(n_a = \sum_b n_{ab}\). A bigram model \(p\) over \(V\) maximises the log-likelihood Equation 9.4 if and only if \[
p(b \mid a) = \frac{n_{ab}}{n_a}
\quad\text{for every } a \text{ with } n_a > 0 \text{ and every } b .
\] Rows with \(n_a = 0\) can be any probability distributions.
The best transition probabilities are the relative frequencies of each row: the fraction of the pairs starting with \(a\) that continue with \(b\).
Proof. The likelihood is a product over rows, \(\mathcal{L}(p) = \prod_a\mathcal{L}_a(p)\) with \(\mathcal{L}_a(p) = \prod_b p(b\mid a)^{n_{ab}}\), so \(\ln\mathcal{L}(p) = \sum_a\ln\mathcal{L}_a(p)\), and \(\mathcal{L}_a\) depends only on row \(a\) of \(p\). The constraints of Definition 9.4 also act on each row separately. So \(p\) maximises \(\ln\mathcal{L}\) exactly when each row maximises its own \(\ln\mathcal{L}_a\). If \(n_a = 0\) then \(\mathcal{L}_a = 1\) whatever the row is. If \(n_a > 0\), take as observations the \(n_a\) tokens that follow \(a\) in the corpus, of which \(n_{ab}\) equal \(b\). Then \(\mathcal{L}_a(p)\) is their likelihood under the distribution \(p(\,\cdot\mid a)\), so by Theorem 8.2 it is largest exactly when \(p(b\mid a) = n_{ab}/n_a\) for every \(b\), and since \(\ln\) is increasing, so is \(\ln\mathcal{L}_a\).
Fitting the model needs no optimisation, only counting. The rows sum to 1 because \(\sum_b n_{ab} = n_a\).
Example 9.2 Dividing each row of Table 9.1 by its total gives the maximum-likelihood model. Its non-zero entries are \[
\begin{aligned}
&p(\mathtt{a}\mid\diamond) = \tfrac35, \quad p(\mathtt{e}\mid\diamond) = \tfrac25, \quad
p(\diamond\mid\mathtt{a}) = \tfrac58,\\
&p(\mathtt{d}\mid\mathtt{a}) = p(\mathtt{n}\mid\mathtt{a}) = p(\mathtt{v}\mid\mathtt{a}) = \tfrac18,
\quad p(\mathtt{a}\mid\mathtt{d}) = p(\mathtt{a}\mid\mathtt{v}) = 1,\\
&p(\mathtt{m}\mid\mathtt{e}) = p(\mathtt{v}\mid\mathtt{e}) = p(\mathtt{a}\mid\mathtt{m})
= p(\mathtt{m}\mid\mathtt{m}) = p(\mathtt{a}\mid\mathtt{n}) = p(\mathtt{n}\mid\mathtt{n}) = \tfrac12 .
\end{aligned}
\] Row \(\mathtt{a}\) is the guess made at the start of this section. The name eva has probability \(p(\mathtt{e}\mid\diamond)\,p(\mathtt{v}\mid\mathtt{e})\,p(\mathtt{a}\mid\mathtt{v})\,p(\diamond\mid\mathtt{a})
= \frac25\cdot\frac12\cdot1\cdot\frac58 = \frac18\). The model also gives positive probability to names it has not seen: ana has probability \(\frac35\cdot\frac18\cdot\frac12\cdot\frac58 = \frac{3}{128}\). Its pairs an and na both occur in anna, and the model recombines them.
Zero counts and smoothing
The maximum-likelihood model gives probability \(0\) to every pair it has not seen. The name dana is plausible, but no name in the corpus starts with \(\mathtt{d}\), so \(p(\mathtt{d}\mid\diamond) = 0\) and the model gives dana probability \(0\). A model that rules out every unseen pair fits the training names well and new names badly.
The simplest repair is add-one (or Laplace) smoothing: pretend that every pair occurred once more than it did, \[
p(b \mid a) = \frac{n_{ab} + 1}{n_a + |V|} .
\tag{9.5}\] The numerator adds one to each count; the denominator adds \(|V|\), one for each possible next token, so each row still sums to 1. Every probability is now positive, and Exercise 9.4 shows that Equation 9.5 is the maximum-likelihood model for the corpus with one extra copy of each of the \(|V|^2\) pairs. With \(|V| = 7\), the smoothed model gives \(p(\mathtt{d}\mid\diamond) = 1/12\) and \[
P(\mathtt{dana}) = \frac{1}{12}\cdot\frac{2}{8}\cdot\frac{2}{15}\cdot\frac{2}{9}\cdot\frac{6}{15}
= \frac{1}{4050} .
\] The price is a worse fit to the training data, measured in the next section. Add-one smoothing moves a lot of probability to unseen pairs when the counts are small, and practical systems use better methods; Chen and Goodman (1999) compare many of them.
9.4 Loss and perplexity
To compare models we need one number that says how well a model predicts a text. The probability of the whole text will not do, because it shrinks as the text gets longer. Under the model of Example 9.2, eva has probability \(1/8\) and anna has \(3/256\), partly because anna needs five predictions and eva four. The four predictions for eva have probabilities \(\frac25, \frac12, 1, \frac58\), and their geometric mean, the fourth root of their product, is \((1/8)^{1/4} \approx 0.595\). For anna the geometric mean of the five probabilities is \((3/256)^{1/5} \approx 0.411\). Per prediction, the model finds eva easier. The reciprocal of the geometric mean, \(8^{1/4} \approx 1.68\) for eva, reads as a number of choices: the model is as uncertain, on average, as if it were choosing among \(1.68\) equally likely tokens at each step. Taking logarithms turns the geometric mean into an ordinary average, which is easier to compute and to differentiate.
Definition 9.5 (Loss and perplexity) Suppose a model makes \(N\) predictions on a text and gives probability \(p_i > 0\) to the token that actually comes next at prediction \(i\). Its loss on the text is the average negative log-likelihood \[
L = -\frac1N\sum_{i=1}^{N}\ln p_i ,
\tag{9.6}\] and its perplexity is \[
\operatorname{PPL} = e^{L} = \Bigl(\prod_{i=1}^{N} p_i\Bigr)^{-1/N} .
\tag{9.7}\]
The loss is the average, over the predictions, of how surprised the model is by the correct token (\(-\ln p_i\) is \(0\) when \(p_i = 1\) and grows as \(p_i\) falls), and the perplexity is the reciprocal of the geometric mean of the \(p_i\). The loss \(L\) is the average negative log-likelihood of Equation 8.1, the loss that every model in the book uses, and training minimises it. For a bigram model on a corpus with pair counts \(n_{ab}\), the loss is \(-\ln\mathcal{L}(p)/N\), with \(N = \sum_{a,b} n_{ab}\) and \(\ln\mathcal{L}\) from Equation 9.4, so minimising the loss and maximising the likelihood are the same problem.
The loss is also an average of cross-entropies. The cross-entropy of a distribution \(q\) relative to a distribution \(r\) on \(V\) is \(H(r, q) = -\sum_{v\in V} r(v)\ln q(v)\) (Definition 8.3), the average of \(-\ln q\) when outcomes are drawn from \(r\). For a token \(a\) with \(n_a > 0\), let \(\hat r_a(b) = n_{ab}/n_a\) be the observed frequency of \(b\) after \(a\). Grouping the predictions by the current token, \[
L = -\frac1N\sum_{a, b\in V} n_{ab}\ln p(b\mid a)
= \sum_{a:\, n_a > 0}\frac{n_a}{N}\,H\bigl(\hat r_a,\ p(\,\cdot\mid a)\bigr) .
\] In words, the loss averages, over the current tokens and weighted by how often each occurs, the cross-entropy of the model’s prediction relative to the frequencies observed after that token.
The next result makes the reading of perplexity as a number of choices exact.
Theorem 9.3 (The uniform model) Let \(V\) be a vocabulary. A model that gives every token of \(V\) probability \(1/|V|\) at every prediction has loss \(\ln|V|\) and perplexity \(|V|\) on every text.
Proof. Every \(p_i\) is \(1/|V|\), so \(L = -\frac1N\cdot N\ln(1/|V|) = \ln|V|\) and \(e^L = |V|\).
For the 27-token vocabulary of names, the uniform model has loss \(\ln 27 \approx 3.30\), the value that Example 8.5 found for a single prediction. This is where training starts. The book’s model starts from small random weights, so its first predictions are close to uniform: Example 8.5 estimates its expected loss at the start as about 3.35, and the loss on the first training step of microgpt is about 3.37 (Karpathy 2026). A model that has learned nothing has a loss near 3.30, and every improvement shows as a loss below that.
Example 9.3 On the 22 predictions of the training corpus, the maximum-likelihood model of Example 9.2 has log-likelihood \[
\ln\mathcal{L}(p) = 3\ln\tfrac35 + 2\ln\tfrac25 + 5\ln\tfrac58 + 3\ln\tfrac18 + 6\ln\tfrac12
\approx -16.11 ,
\] one term for each non-zero entry of Table 9.1, grouped by equal probabilities. So its loss is \(16.11/22 \approx 0.732\) and its perplexity is \(e^{0.732} \approx 2.08\). The uniform model over the 7 tokens has loss \(\ln 7 \approx 1.95\) and perplexity 7. The add-one smoothed model has loss about \(1.33\) and perplexity about \(3.79\) on the training names: worse than the maximum-likelihood model there, as Theorem 9.2 guarantees. On the new name dana, with 5 predictions, the maximum-likelihood model has infinite loss, and the smoothed model has loss \(\ln(4050)/5 \approx 1.66\) and perplexity \(4050^{1/5} \approx 5.27\).
9.5 Embeddings and a neural bigram model
A table of transition probabilities treats every token as unrelated to every other: what the corpus says about \(\mathtt{a}\) tells the table nothing about \(\mathtt{e}\). Neural language models instead give each token a vector, compute the probabilities from the vectors, and so let tokens with similar vectors receive similar predictions. The first step is to turn a token into a vector.
Number the tokens \(1, 2, 3\) and attach to each a row of the matrix \[
E = \begin{pmatrix} 1 & 0\\ 2 & -1\\ 0 & 3\end{pmatrix} ,
\] so that token 2 has the vector \((2, -1)\). Writing token 2 as the standard basis vector \(\mathbf{e}_2 = (0, 1, 0)^\top\) of \(\mathbb{R}^3\) turns the lookup into a matrix product: \(E^\top\mathbf{e}_2\) is the combination of the columns of \(E^\top\) with weights \(0, 1, 0\), which is column 2 of \(E^\top\), the vector \((2, -1)^\top\).
Definition 9.6 (One-hot vector and embedding) Number the tokens of a vocabulary \(V\) as \(1, \dots, |V|\). The one-hot vector of token \(a\), as in Section 8.6, is the standard basis vector \(\mathbf{e}_a\) of \(\mathbb{R}^{|V|}\). An embedding matrix of width \(d\) is a \(|V|\times d\) matrix \(E\), and the embedding of token \(a\) is \[
\mathbf{u}_a = E^\top\mathbf{e}_a \in \mathbb{R}^d ,
\] the \(a\)th row of \(E\) written as a column.
Row \(a\) of \(E\) is the vector of token \(a\), and column \(j\) holds the \(j\)th component of every token’s vector. Multiplying by a one-hot vector picks out one row, so programs store \(E\) and look up row \(a\) directly instead of forming a product.
The book’s model has an embedding matrix with \(|V| = 27\) rows and width \(d = 16\). An embedding alone predicts nothing. The smallest neural language model maps the embedding of the current token to one score for each possible next token, and turns the scores into probabilities with the softmax function of Definition 8.5, \(\operatorname{softmax}(\mathbf{z})_i = e^{z_i}/\sum_j e^{z_j}\), which turns any vector into positive numbers that sum to 1. Continue the example with a second \(3\times2\) matrix \(W\), with rows \((1, 0)\), \((0, 1)\) and \((1, 1)\). After token 2, the scores are \(W\mathbf{u}_2 = (2, -1, 1)\), one for each token that could come next, and softmax turns them into the probabilities \[
\frac{(e^{2}, e^{-1}, e^{1})}{e^{2} + e^{-1} + e^{1}} \approx (0.705, 0.035, 0.259) .
\]
Definition 9.7 (Neural bigram model) Let \(V\) be a vocabulary and \(E\), \(W\) be \(|V|\times d\) matrices. The neural bigram model with parameters \(E\), \(W\) is the bigram model with transition probabilities \[
p(\,\cdot \mid a) = \operatorname{softmax}(\mathbf{z}_a),
\qquad \mathbf{z}_a = W\mathbf{u}_a = WE^\top\mathbf{e}_a .
\] The vector \(\mathbf{z}_a \in \mathbb{R}^{|V|}\) holds the logits (the scores that go into the softmax, as in Definition 8.5) for the token after \(a\). The \(|V|\times|V|\) matrix \(Z = WE^\top\) is the logit matrix.
Entry \((b, a)\) of \(Z\) is the logit of \(b\) as the next token after \(a\): column \(a\) of \(Z\) is \(\mathbf{z}_a\), the scores used after \(a\), and row \(b\) holds the scores that token \(b\) receives after each possible current token. Row \(b\) of \(W\) is the vector that the embedding of the current token is compared with, by a dot product, to score \(b\).
The book’s model ends the same way: a \(27\times16\) output matrix turns a 16-dimensional vector into 27 logits. In between, the full model replaces \(\mathbf{u}_a\) by a vector that depends on the whole context, which is what Chapter 10 and Chapter 11 build.
What can such a model represent? Its probabilities come out of a softmax, so they are never zero, and the logit matrix is a product through a \(d\)-dimensional space, which limits its rank, the dimension of the space spanned by its columns.
Theorem 9.4 (What a neural bigram model can represent) Let \(V\) be a vocabulary and \(d \ge 1\).
Every neural bigram model with \(|V|\times d\) parameter matrices is a bigram model whose transition probabilities are all positive.
Every logit matrix \(Z = WE^\top\) with \(E\) and \(W\) of size \(|V|\times d\) has rank at most \(d\).
If \(d = |V|\), every bigram model over \(V\) whose transition probabilities are all positive is a neural bigram model: take \(E = I\) and let \(W\) have entries \(w_{ba} = \ln p(b \mid a)\).
Proof.
Softmax outputs are positive and sum to 1, so each \(p(\,\cdot\mid a)\) is a probability distribution with positive entries.
Each column of \(Z = WE^\top\) is \(W\) times a vector, so it is a combination of the \(d\) columns of \(W\). The column space of \(Z\) lies in a space spanned by \(d\) vectors, so its dimension is at most \(d\).
With \(E = I\), \(\mathbf{u}_a = \mathbf{e}_a\) and \(\mathbf{z}_a\) is column \(a\) of \(W\), whose entries are \(\ln p(b \mid a)\). Then \[
\operatorname{softmax}(\mathbf{z}_a)_b
= \frac{e^{\ln p(b\mid a)}}{\sum_{c} e^{\ln p(c\mid a)}}
= \frac{p(b\mid a)}{\sum_c p(c\mid a)} = p(b \mid a) .
\]
So with \(d = |V|\) the neural bigram model can represent every bigram model except those with zero entries, and those it can approach by letting logits tend to \(-\infty\). Training it by gradient descent on the loss of Definition 9.5 leads to the same place as counting.
Corollary 9.1 Let \(V\) be a vocabulary, \(d = |V|\), and let \(L(E, W)\) be the loss of the neural bigram model with parameters \(E\), \(W\) on a corpus with pair counts \(n_{ab}\) and row totals \(n_a\).
If every \(n_{ab}\) is positive, the minimum of \(L\) is attained, and \((E, W)\) attains it exactly when the model’s transition probabilities are the relative frequencies \(n_{ab}/n_a\).
If \(n_{ab} = 0\) for some pair with \(n_a > 0\), then \(L\) has no minimum: its infimum is the loss of the relative frequencies, and no \((E, W)\) attains it.
Proof. Write \(f(b\mid a) = n_{ab}/n_a\) for the relative frequencies and \(L^*\) for their loss. By Theorem 9.2, every bigram model has loss at least \(L^*\), and a model has loss \(L^*\) only if it agrees with \(f\) on every row with \(n_a > 0\).
Every \(n_a\) is positive, so every row is determined. The frequencies are positive, so by part (c) of Theorem 9.4 some \((E, W)\) gives them, with loss \(L^*\), and any \((E, W)\) with loss \(L^*\) gives them.
By part (a) of Theorem 9.4, no neural bigram model agrees with \(f\), because \(f\) has a zero entry in a row with \(n_a > 0\). So \(L > L^*\) everywhere. For \(0 < \delta < 1\), the model \(p_\delta = (1-\delta)f + \delta/|V|\) (with \(f\) extended by uniform rows where \(n_a = 0\)) has positive entries, so it is a neural bigram model. Each term of its loss with \(n_{ab} > 0\) has \(f(b\mid a) > 0\), and \(\ln p_\delta(b\mid a) \to \ln f(b\mid a)\) as \(\delta \to 0\) because \(\ln\) is continuous at positive numbers. So the loss of \(p_\delta\) tends to \(L^*\).
In case (b), the models \(p_\delta\) approach the infimum as the probabilities of unseen pairs tend to \(0\). A softmax entry satisfies \(e^{z_b}/\sum_c e^{z_c} \ge e^{z_b - \max_c z_c}/|V|\), so it can tend to \(0\) only if its logit falls without bound below the largest logit in its column, and then some entries of \(E\) or \(W\) grow without bound. Gradient descent behaves this way: on the five names, with \(d = |V| = 7\), it keeps lowering the loss towards the infimum while the weights keep growing.
How a neural model shares information
The two models differ in what one training example changes. In a count table, an occurrence of the pair \((a, b)\) changes row \(a\) and nothing else, so the predictions after a rare token rest on that token’s few occurrences alone. In the neural model the matrix \(W\) is used in every row, so a gradient step taken for one pair changes predictions after other tokens too. The next lemma says by how much.
Lemma 9.1 Consider a neural bigram model with parameters \(E\), \(W\), and let \(\ell = -\ln p(b \mid a)\) be the loss of one occurrence of the pair \((a, b)\). Write \(\mathbf{p} = p(\,\cdot\mid a)\). Then \[
\frac{\partial\ell}{\partial W} = (\mathbf{p} - \mathbf{e}_b)\,\mathbf{u}_a^\top ,
\] where \(\partial\ell/\partial W\) is the matrix of partial derivatives \(\partial\ell/\partial w_{ij}\). After a gradient step \(W \leftarrow W - \eta\,\partial\ell/\partial W\) with learning rate \(\eta > 0\) and \(E\) held fixed, the logits after any token \(c\) change by \[
-\eta\,(\mathbf{u}_a\cdot\mathbf{u}_c)\,(\mathbf{p} - \mathbf{e}_b) .
\]
The gradient is an outer product: row \(i\) is the embedding \(\mathbf{u}_a\) scaled by \(p_i - [i = b]\), where \([i = b]\) is \(1\) if \(i = b\) and \(0\) otherwise. The step lowers the logit of the observed token \(b\) relative to the others after \(a\), and moves the logits after \(c\) in the same pattern, scaled by the dot product of the two embeddings.
Proof. By Theorem 8.5, \(\partial\ell/\partial z_i = p_i - [i = b]\), the \(i\)th entry of \(\mathbf{p} - \mathbf{e}_b\), where \(\mathbf{z} = W\mathbf{u}_a\). Since \(z_i = \sum_j w_{ij}u_{a,j}\), the weight \(w_{ij}\) affects only \(z_i\), with \(\partial z_i/\partial w_{ij} = u_{a,j}\). By the chain rule, \(\partial\ell/\partial w_{ij} = (p_i - [i = b])\,u_{a,j}\), which is entry \((i, j)\) of \((\mathbf{p} - \mathbf{e}_b)\mathbf{u}_a^\top\). The new logits after \(c\) are \[
\Bigl(W - \eta(\mathbf{p} - \mathbf{e}_b)\mathbf{u}_a^\top\Bigr)\mathbf{u}_c
= W\mathbf{u}_c - \eta\,(\mathbf{u}_a^\top\mathbf{u}_c)(\mathbf{p} - \mathbf{e}_b) .
\]
So a step taken for an occurrence of \(a\) also moves the predictions after every token \(c\) whose embedding is not perpendicular to \(\mathbf{u}_a\). When \(d < |V|\) this cannot be avoided. Vectors \(\mathbf{u}_1, \dots, \mathbf{u}_m\) are linearly independent if the only combination \(\sum_i\lambda_i\mathbf{u}_i\) equal to \(\mathbf{0}\) has every \(\lambda_i = 0\), and \(\mathbb{R}^d\) contains at most \(d\) linearly independent vectors. Non-zero vectors that are pairwise perpendicular are linearly independent: if \(\sum_i\lambda_i\mathbf{u}_i = \mathbf{0}\), taking the dot product with \(\mathbf{u}_j\) gives \(\lambda_j\|\mathbf{u}_j\|^2 = 0\). So if the \(|V|\) embeddings are non-zero, some two of them have a non-zero dot product.
This is the precise sense in which a neural model with small embeddings shares information between tokens. If training gives similar embeddings to tokens that are followed by similar tokens, then evidence about one helps the predictions after the other. Nothing proved here says that training does this, or that sharing lowers the loss on names outside the training data; that depends on the data and on the training run. Bengio et al. (2003) proposed learned embeddings for word-level language models with this argument, and reported on two text corpora that their models improved on the best \(n\)-gram models of the time. The neural model is not smaller than the table for bigrams: with \(|V| = 27\) and \(d = 16\) it has \(2\cdot27\cdot16 = 864\) parameters, against \(27\cdot26 = 702\) free numbers in a table (each row of 27 probabilities has one fewer free number, because it must sum to 1). The saving in parameters appears with longer contexts.
9.6 Longer contexts
A bigram model cannot know that emm is likely to continue with \(\mathtt{a}\), because it sees only the last \(\mathtt{m}\), and after a single \(\mathtt{m}\) the corpus has \(\mathtt{a}\) and \(\mathtt{m}\) equally often. The obvious extension conditions on more tokens.
Definition 9.8 (\(n\)-gram model) Let \(n \ge 2\). An \(n\)-gram model is a language model whose next-token distribution depends only on the last \(n - 1\) tokens of the context, with the context padded by \(\diamond\) at the start when it is shorter.
A bigram model is the case \(n = 2\). An \(n\)-gram model is a table with one row for each possible sequence of \(n - 1\) tokens and one entry in each row for each next token, so it has \(|V|^{n-1}\) rows and \(|V|^n\) entries. Its maximum-likelihood estimate is again given by relative frequencies, by the proof of Theorem 9.2 with rows indexed by contexts. The table grows exponentially with the context length: with \(|V| = 27\), a trigram (\(n = 3\)) model has \(27^2 = 729\) rows, a 4-gram model \(27^3 = 19{,}683\) rows, and a model that conditions on 16 tokens, the context length of the book’s model, has \(27^{16} \approx 7.98\times10^{22}\) rows.
The data cannot fill such a table. Each prediction in the training data adds a count to one row, so a corpus with \(N\) predictions gives counts to at most \(N\) rows. The names data of microgpt has 32,033 names (Karpathy 2026), and the model makes at most 16 predictions per name, so there are at most \(32{,}033\times16 = 512{,}528\) predictions. Even for the 4-gram model, a corpus of 1000 predictions leaves more than 94% of the rows empty (Exercise 9.9), and for a 16-token context the fraction of rows that receive any count at all is below \(10^{-17}\). A row without counts is a context about which the table knows nothing, and smoothing can only spread probability evenly over its entries.
Neural models avoid this growth by computing the distribution from the context instead of looking it up. Bengio et al. (2003) concatenated the embeddings of the last \(n - 1\) tokens and passed them through a small network, so the number of parameters grows linearly with \(n\). That model still has a fixed window, and each position in the window has its own weights. The book’s model forms, at each position, a weighted average of vectors computed from all the earlier tokens, with weights that the tokens themselves determine, and it uses the same parameters for every context length up to 16. That operation is attention, the subject of Chapter 10.
9.7 Notes and further reading
Section 3 of Shannon (1948) builds a series of approximations to English from letter and word frequencies, including letter-pair (bigram) models, and treats them as Markov processes. Jurafsky and Martin (2026, ch. 3) cover \(n\)-gram models, perplexity and smoothing at greater length, and Chen and Goodman (1999) compare smoothing methods on large corpora. The neural language model with learned embeddings is due to Bengio et al. (2003). Radford et al. (2019) describe GPT-2, a large model that factorises the probability of text with the chain rule as in Definition 9.3 and is evaluated by perplexity. Karpathy (2026) describes the small model that this book rebuilds, including its tokeniser and training data.
9.8 Exercises
Exercise 9.1
Write the name ada as a sequence of microgpt token numbers.
Show that a corpus of \(m\) names with \(M\) letters in total gives \(M + m\) predictions, and check this against the five names of Section 9.1.
Exercise 9.2 Choose one of the five corpus names uniformly at random, and let \(X_1\) and \(X_2\) be its first and second letters. Compute \(P(X_2 = \mathtt{v})\) and \(P(X_1 = \mathtt{a}\mid X_2 = \mathtt{v})\), and check that \(P(X_2 = \mathtt{v})\,P(X_1 = \mathtt{a}\mid X_2 = \mathtt{v})\) equals \(P(X_1 = \mathtt{a}, X_2 = \mathtt{v})\) from Example 9.1.
Exercise 9.3 Using the maximum-likelihood model of Example 9.2, compute the probabilities of anna and emma. Which name in the corpus has the largest probability under the model?
Exercise 9.4
Show that each row of the add-one model Equation 9.5 sums to 1.
Show that Equation 9.5 is the maximum-likelihood bigram model for the counts \(n_{ab} + 1\).
Compute \(p(\diamond\mid\mathtt{a})\) in the add-one model of Section 9.3 and compare it with the maximum-likelihood value \(5/8\).
Exercise 9.5
Show that the perplexity of Definition 9.5 is at least 1, with equality exactly when every \(p_i = 1\).
Model A has loss \(0.1\) lower than model B on the same text. Find the ratio of their perplexities.
Exercise 9.6 Consider a bigram model with \(p(\diamond\mid a) \ge \varepsilon\) for every \(a\in V\), where \(0 < \varepsilon \le 1\), and generate names as described after Definition 9.3. For \(k \ge 0\) let \(r_k\) be the probability that the first \(k\) tokens generated are all letters (so \(r_0 = 1\)), and let \(q_k\) be the total probability of all names with exactly \(k\) letters.
Show that \(r_{k+1} = r_k - q_k\) and \(r_{k+1} \le (1-\varepsilon)r_k\).
Deduce that the probabilities of all names sum to 1.
Exercise 9.7 Let \(|V| = 2\) and \(d = 1\). Show that every bigram model with positive transition probabilities is a neural bigram model. (Hint: with two tokens, the softmax depends only on the difference of the two logits.)
Exercise 9.8 In the setting of Lemma 9.1, show that \(\partial\ell/\partial E = \mathbf{e}_a\bigl(W^\top(\mathbf{p} - \mathbf{e}_b)\bigr)^\top\), so that a gradient step on \(E\) changes only the embedding of \(a\).
Exercise 9.9 A corpus gives \(N\) predictions. Show that at most \(N\) rows of an \(n\)-gram table have a non-zero count. For \(|V| = 27\), \(n = 4\) and \(N = 1000\), find a lower bound for the fraction of rows with no counts.
Bengio, Yoshua, Réjean Ducharme, Pascal Vincent, and Christian Jauvin. 2003. “A Neural Probabilistic Language Model.”Journal of Machine Learning Research 3: 1137–55. https://www.jmlr.org/papers/v3/bengio03a.html.
Chen, Stanley F., and Joshua Goodman. 1999. “An Empirical Study of Smoothing Techniques for Language Modeling.”Computer Speech & Language 13 (4): 359–93. https://doi.org/10.1006/csla.1999.0128.