Skip to Content
Chapter 2

Language modeling: Predicting the next token

Tomas Reimers 14 minute read

In 1951, Claude Shannon  published a paper in which he asked people to guess a sentence one letter at a time, and used their guesses to measure the statistical structure of English. Buried in that experiment is the entire premise of this book: language has statistical structure, and predicting the next symbol is the way to capture it.

How do we get from reading digits to a machine that writes? The answer:

  1. We pose “produce language” as a prediction problem: given text so far, guess the next token. That makes it a classifier — the classifier from Chapter 1, with every possible next token (roughly: words and word-pieces, made precise mid-chapter) as the classes.
  2. The obvious approach, counting what followed what, works until it has to generalize — so words become learned vectors, where similar words can share what the model knows.
  3. The loss is the same cross-entropy from Chapter 1 — and here it picks up an alter ego: a model that predicts text well compresses it well.

The task: guess the next token

Play Shannon’s game yourself: “the cat sat on the ___”. You didn’t retrieve an answer; you produced a ranking — mat likely, sofa plausible, carburetor absurd. A language model is that ranking, made precise: a function that takes the text so far and returns a probability for every possible next token:

P(xt+1∣x1,x2,…,xt)P(\tip{the next token}{x_{t+1}} \mid \tip{everything so far — the context}{x_1, x_2, \ldots, x_t})

Look at what this is, in Chapter 1’s terms: a classifier. Input: the context. Output classes: every token in the vocabulary. Same logits (the raw per-class scores), same softmax (exponentiate and normalize into probabilities), same “we’re doing statistics, not logic” — just ~100,000 classes instead of Chapter 1’s ten digits:

The capital of France is▌
Paris
62.0%
the
10.0%
a
6.0%
located
5.0%
known
4.0%
one
3.0%
famous
2.5%
⋮ 99,993 more tokens, sharing the remaining 7.5%
A language model's entire output for one step: a probability for every token in the vocabulary. This is the same softmax from Chapter 1 — with ~100,000 classes instead of 10.

The model emits a probability distribution, every time. Something outside the model must decide what to do with it — take the top token, or sample from it (a decision Chapter 3 closes on). Generation is this classifier in a loop: predict a token, append it to the context, run again. One token at a time, no plan sitting in a buffer — any appearance of planning is implicit in the distribution at each step.

Why would such a humble objective produce systems that write code and answer questions? Because predicting the next token of arbitrary text, well, requires modeling whatever process produced the text. Predicting the next token of The capital of France is requires knowing facts. A half-finished function can’t be continued without a model of its author’s intent; the final chapter of a murder mystery, not without a memory of every clue planted in the previous ten. Pushed to a sufficiently low loss, prediction doesn’t approximate understanding — it demands it. (Whether it demands understanding in the same form humans have it is a genuinely open question; Chapter 6 is about the people prying the models open to check.)

Before neural networks: counting

Here’s the simplest language model you can build, and people built it for decades: count. Record, for every word, what followed it in the corpus and how often — a bigram model (pairs; count triples and it’s a trigram, n words and it’s an n-gram). Training is literally tallying. Below is a real one, trained on the eight sentences shown:

the cat sat on the mat . the dog sat on the rug . the cat ate the fish . the dog ate the bone . a cat and a dog sat on the mat . the fish was on the mat . a dog was on the rug . the cat was on the mat .
after "the":
mat
4× (29%)
cat
3× (21%)
dog
2× (14%)
rug
2× (14%)
fish
2× (14%)
bone
1× (7%)
the cat sat on the rug .
A real bigram model, "trained" on the corpus shown (counting is the training). Click a context word to see its next-word distribution; generate to sample from the model. The output is locally plausible and globally meaningless — each word knows only the word before it.

Generate a few samples and you’ll see both the magic and the ceiling. The magic: pure counting already produces locally-plausible English — this is the germ of everything in this book. The ceiling: every word knows only the single word before it, so the output wanders without meaning or memory.

The obvious fix is longer contexts — count what follows every pair, every triple, every ten-word window. Now watch it explode. With a 50,000-word vocabulary, a 10-word context has

∣V∣ n=50,00010≈1047\tip{vocabulary size}{|V|}^{\,\tip{context length}{n}} = 50{,}000^{10} \approx 10^{47}

possible rows in the table — about as many as there are atoms in Earth’s oceans. And no corpus can keep up. Be as ambitious as you like: take every page of the public internet, tens of trillions of words, the largest body of text our species has produced. That is still fewer than 101410^{14} examples to fill a 104710^{47}-row table. Almost every context you’ll ever encounter has never occurred before, anywhere — and the table simply has no entry for it.

The failure is deeper than size: counting can’t share. Having seen “the dog sat on the ___” a thousand times tells a counting model nothing about “the cat sat on the ___” — the contexts differ, so they’re different rows, full stop. Yet any English speaker knows those contexts are nearly the same. What we need is for similar words to have similar representations, so that evidence about one flows to the other. Chapter 1 gave us exactly one tool for learning useful representations under pressure of a loss — a neural network trained by gradient descent. We’ll need it, but first we have to decide what the atoms are.

Tokens: the atoms of an LLM

What should the unit of prediction be? Characters make sequences enormously long. Whole words can’t handle typos, code, or German compound nouns — the vocabulary is effectively unbounded. Every modern LLM uses the compromise in between: subword tokens, discovered by an algorithm called byte-pair encoding  (BPE) that is pure Chapter-1 spirit — don’t hand-design the units, learn them from data by counting. It works bottom-up. Start with the smallest possible vocabulary: individual characters (in practice raw bytes, so nothing is ever unrepresentable). Then repeat one move: count every adjacent pair of tokens in the corpus, and merge the most frequent pair into a single new token. Each merge grows the vocabulary by one, and frequent fragments assemble themselves:

low×5
lower×2
newest×6
widest×3
start: every word is just characters — vocabulary: single letters
Byte-pair encoding, trained live on a four-word corpus: at every step, the most frequent adjacent pair becomes a new token. Watch 'est', 'low', and 'new' — real subword units — assemble themselves out of raw characters, purely from counting.

Run until the vocabulary hits a target size (typically 50,000–250,000 merges), and the effect is elegant: common words (“the”, ” function”) end up as single tokens, rare words split into meaningful chunks — and anything can still be encoded, any typo, any language, any binary blob, because the original characters never left the vocabulary. The worst case is simply falling all the way back down to them. Here’s a real GPT-style tokenizer on a real sentence; the model never sees the letters, only the integer IDs:

The464
un555
reason20080
able540
effectiveness26280
of286
token11241
ization2734
A BPE tokenizer at work: common words survive whole, rarer ones split into reusable chunks. The model only ever sees the integer IDs.

Tokenization is also where much of LLMs’ weirdness originates:

  • Models see token IDs, not letters. “strawberry” may be one opaque token — the model has no direct access to its spelling, which is why counting its r’s is famously hard.
  • Numbers get chopped arbitrarily. 12345 might tokenize as 123 + 45 (boundaries that ignore place value, so the model never sees digit structure), which is part of why arithmetic is unnatural for these models.
  • Whitespace matters. function (with a leading space) and function are different tokens (different IDs, different learned vectors), and a completion that starts with the wrong one derails.
  • Non-English pays a tax. Text in less common languages splits into many more tokens per word — literally more expensive, in both context space and API dollars.

Karpathy has a two-hour video  building a GPT tokenizer from scratch, which he opens by noting that most “weird LLM behavior” traces back to tokenization. He’s right.

Embeddings: meaning as geometry

A token ID is just an integer — token 5,072 isn’t “closer” to token 5,073 in any meaningful sense. The model’s first act is to trade the integer for something it can compute with, and the mechanism could not be simpler. The model owns an embedding matrix:

E∈R∣V∣×d\tip{the embedding matrix}{E} \in \mathbb{R}^{\tip{one row per token in the vocabulary}{|V|} \times \tip{the embedding dimension — a few thousand in a frontier model}{d}}

To embed token 5,072, take row 5,072 of EE. That’s the whole operation: a table lookup. (If you prefer Chapter 1’s vocabulary: write the token as a one-hot vector and multiply it by EE; a lookup is a matrix multiply by a one-hot.) And the rows of EE are parameters like any others: initialized to random numbers, and nudged by backpropagation (every time a token appears in training, the gradient flows into its row), exactly the loop from Chapter 1.

To see what the numbers in a row could mean, run a thought experiment. Suppose the vocabulary were nothing but city names, and we hand-picked d=3d = 3: let the first dimension encode coast (−1 west, +1 east), the second size, the third warmth. Then:

coastsizewarmth
Los Angeles−10.90.8
San Francisco−10.60.5
Boston+10.60.3
New York+10.90.6

Each city is now a point whose coordinates are its properties — and the geometry starts doing work for free. Subtract San Francisco from Los Angeles and you get [0, 0.3, 0.3]: “same coast, but bigger and warmer.” Add that to Boston: [+1, 0.9, 0.6] — a large, warm-ish, east-coast city. That’s New York, to the decimal: LA−SF+Boston≈NYC\textbf{LA} - \textbf{SF} + \textbf{Boston} \approx \textbf{NYC}. When coordinates encode properties, directions encode relationships, and analogy becomes arithmetic.

Nobody hand-picks the dimensions of a real model, of course. They’re learned, there are thousands of them, and they’re rarely this legible (Chapter 6 is about the people trying to read them anyway). But the principle survives contact with reality — it showed up, unasked-for, in real learned spaces. The famous demonstration is word2vec  (2013), which showed that learned embedding spaces encode exactly these structures — similarity as closeness, relationships as directions. (word2vec learned one vector per word; modern models learn one per token, and whole words are simply where the geometry is easiest to see.)

capital of+ royalmanwomankingqueenfranceparisitalyromecatdogkittenpuppy
An embedding space, projected to two dimensions (illustrative — the real thing has thousands). Similar words cluster, and directions carry relationships: the france→paris arrow and the italy→rome arrow are parallel, which is what makes king − man + woman land near queen.

The vector from france to paris is nearly parallel to the one from italy to rome (a learned “capital of” direction nobody asked for), and the “maleness→royalty” arrows line up the same way, which is why king−man+woman\textbf{king} - \textbf{man} + \textbf{woman} lands near queen\textbf{queen}: the cities trick, discovered rather than designed.

And this is what rescues us from counting’s sharing problem. Under the pressure of next-token prediction, the cheapest way for the model to handle “cat” and “dog” (which appear in nearly identical contexts) is to give them nearly identical vectors, so all the machinery downstream of the embedding handles both for the price of one. Similarity is the economical solution gradient descent keeps finding. Evidence about dog-sentences now genuinely transfers to cat-sentences, because to the rest of the network they look almost alike.

The embedding space is the model’s universal interface. A neural network operates on exactly one data type — vectors — and embeddings are the adapters that convert the outside world into it. Words become vectors here; in Chapter 5, image patches and audio frames will arrive through their own encoders as vectors of the same kind. Once something is in the space, “semantically similar” means “geometrically close,” and the same downstream machinery can process it no matter what it originally was. This one idea also powers every semantic-search and retrieval product you’ve used, and it’s the foundation the transformer builds on in the next chapter.

The same loss — and its alter ego

The predictor and the embeddings train at once, because everything we’ve assembled is one function: the embedding matrix is the first layer, then comes a network that reads the context’s vectors (picture Chapter 1’s multi-layer perceptron, stacked layers of matrix-multiply-plus-nonlinearity, for now; replacing it is the next chapter’s job), then an output layer producing a logit per vocabulary token. Backpropagation doesn’t distinguish between these parts. The chain rule walks from the loss back through the output layer, through the network, and on into the embedding rows of whichever tokens appeared in the context: one backward sweep, every parameter nudged by the same gradient. Embeddings are simply the layer nearest the input. (Historically word2vec did train embeddings as a standalone artifact; modern models get them as a side effect of the main objective.)

And the loss driving it all, you already know. The vocabulary plays the role of the 10 digits. The target is the correct next token, written one-hot (Chapter 1’s format: all zeros, a single 1 at the right index). The loss is the negative logprob of the truth: cross-entropy, verbatim from Chapter 1. Nothing about the loss changes between MNIST (Chapter 1’s hand-labeled digits) and a frontier LLM except the number of classes. And text has a gift those hand-labeled digits never had: the labels are free. Every position in every sentence on the internet is a training example: the context is the input, and the next token, already sitting right there, is the label. No annotators required; the internet labels itself.

Averaged per token, the loss has an interpretable cousin. Perplexity is its exponential:

PPL=eLˉ\mathrm{PPL} = e^{\tip{the average cross-entropy per token}{\bar{L}}}

and it means: the model is, on average, as uncertain as if it were choosing uniformly among PPL\mathrm{PPL} options at every token. (The equivalence is exact: a uniform guess among NN options scores an average loss of ln⁡N\ln N, so eLˉe^{\bar{L}} recovers NN.)

Make that concrete with three texts and one model. Measured on “one two three four five six seven eight,” the continuation is locked after a couple of tokens: nearly all the probability lands on the right answer, almost no loss, perplexity ≈ 1. An ordinary sentence (“I stopped at the store to pick up some ___”) keeps a handful of continuations genuinely live (milk, bread, eggs, things, groceries…), so the model spreads its bets; good models land around perplexity 10 on typical English (an order-of-magnitude figure: roughly ten plausible tokens per step). Shuffle those same ordinary words into random order and context predicts nothing: every token is a surprise, and perplexity climbs into the hundreds or thousands. Same model each time: perplexity measures the match between a model and a text, which is why it works as a score for either one.

One term you’ll meet constantly: pre-training is the industry’s name for exactly this phase — training the next-token predictor on raw text (Chapter 7 explains the prefix). When a pre-training paper brags about a loss curve, the y-axis is cross-entropy, which is just log-perplexity: the same measurement on a different scale.

The alter ego: a language model is a compressor

Chapter 1 left an IOU: the logprob of a token is, in base 2, the number of bits an optimal code needs to encode that token given the model’s beliefs. A scheme called arithmetic coding  makes this literal: feed it any probability distribution over next tokens and it encodes text at almost exactly −log⁡2p-\log_2 p bits per token — confident correct predictions cost fractions of a bit, surprises cost many.

So “minimize average cross-entropy” and “compress the training data as hard as possible” are the same objective, not analogous — identical. A better language model is, mechanically, a better file compressor for text, and vice versa. This equivalence is why researchers sometimes describe pre-training as “compressing the internet” (Chapter 7 takes this framing literally), and why the long-running Hutter Prize  treats compressing Wikipedia as an AI benchmark: to compress text optimally, you must model everything that makes it predictable — grammar, facts, style, the works.

A paragraph of history: the RNN era

Between roughly 2014 and 2018, the dominant neural language models were recurrent neural networks (RNNs): read text one token at a time, maintaining a running “hidden state” vector summarizing everything so far. Karpathy’s 2015 post The Unreasonable Effectiveness of Recurrent Neural Networks  captures the era’s excitement — and reading its celebrated samples today is a useful calibration for how far things have come.

RNNs had two fatal flaws. Squeezing an arbitrarily long past into one fixed-size vector meant long-range information got crushed — the model forgot. And processing tokens sequentially meant training couldn’t be parallelized: token 1,000 couldn’t be processed until tokens 1 through 999 had been, no matter how many chips you owned. The architecture that fixed both problems at once — and in doing so, inherited the earth — is the next chapter.

Further reading

Last updated on