Sub topic 1
What a Language Model Does: Predicting the Next Token
Prerequisites
This chapter assumes you can read basic Python and know what a vector is. It also assumes you have a basic idea of a probability distribution: a list of non-negative numbers that sum to 1. You do not need to know how neural networks or transformers work. Later chapters cover those.
By the end of this chapter you should be able to:
- State what a language model computes.
- Write the chain rule that turns next-token prediction into a model of whole sequences.
- Build and query a tiny model by counting.
- Explain why real models need something stronger than counting.
The core idea
A language model is a function that takes some text and returns a probability for each possible next piece of text. The pieces are called tokens. A token is a unit such as a word, part of a word, or a punctuation mark. The next chapter covers how text is split into tokens. For now, treat each token as one item from a fixed list called the vocabulary.
Suppose the input is The cat sat on the. A language model returns a distribution over the vocabulary. It might give mat a probability of 0.31, floor 0.12, sofa 0.08, and a very small value to every other token. The probabilities across the whole vocabulary sum to 1.
Everything else in a large language model (LLM) serves this one task. Chat, summarization, translation, and code generation all arise from repeating it: predict one token, append it to the text, and predict again.
Conditional probability and the chain rule
Write a text as a sequence of tokens x1, x2, ..., xn. A language model estimates the probability of a token given all the tokens before it:
P(xt | x1, ..., x_(t-1))
This is a conditional probability. It reads "the probability of token t, given the earlier tokens."
The chain rule of probability says you can express the probability of a whole sequence as a product of these conditionals:
P(x1, ..., xn) = P(x1) × P(x2 | x1) × P(x3 | x1, x2) × ... × P(xn | x1, ..., x_(n-1))
This identity is exact. It does not assume anything about language. That is why next-token prediction is a complete way to model text. A model that gets every conditional right also gets the probability of every possible sequence right.
Two consequences follow:
- Scoring. You can ask how likely a given sentence is by multiplying the conditionals. In practice you add log probabilities instead, because a product of many small numbers underflows floating-point arithmetic.
- Generation. You can produce new text by sampling from the conditionals one step at a time. This is called autoregressive generation, meaning each output is fed back as input.
The model reads left to right. A token never conditions on tokens that come after it. This is the "causal" structure that later chapters implement with a mask inside self-attention.
Context
The tokens a model conditions on are its context, also called the prompt when you supply them. In the formula above, the context for position t is every earlier token. Real models can only look back a fixed number of tokens, called the context window. Counting models are weaker still: they look back only a few tokens. That limit is the first thing to understand about the model we build next.
A model built by counting
The simplest language model is a bigram model. It conditions only on the single previous token. You estimate each probability by counting how often one token follows another in a training text, then dividing by the total count for the previous token.
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the cat ate . the dog sat on the rug .".split()
counts = defaultdict(Counter)
for prev, nxt in zip(corpus, corpus[1:]):
counts[prev][nxt] += 1
def next_distribution(prev):
total = sum(counts[prev].values())
return {tok: c / total for tok, c in counts[prev].items()}
print(next_distribution("the"))
print(next_distribution("sat"))Running this prints:
{'cat': 0.4, 'mat': 0.2, 'dog': 0.2, 'rug': 0.2}
{'on': 1.0}After the, the token cat appeared in 2 of 5 cases, so it gets 0.4. After sat, the only continuation seen was on, so it gets probability 1.0.
This is a real language model. It maps a context (here, one token) to a distribution over the next token. It also shows the weaknesses that motivate the rest of the tutorial.
Weakness 1: short memory
A bigram model ignores everything before the last token. You can extend it to n-grams by conditioning on the last n-1 tokens. The number of possible contexts grows exponentially with n. With a vocabulary of 50,000 tokens there are 2.5 billion possible two-token contexts and 125 trillion possible three-token contexts. Almost all of them never appear in any training text.
Weakness 2: zero counts
If a context or continuation was never seen, the count is zero. The model then assigns probability 0 to a perfectly reasonable sentence. Try next_distribution("elephant"). The context has no counts, so total is 0 and the function divides by zero.
Smoothing techniques add small pseudo-counts to avoid zeros. They patch the symptom, not the cause.
Weakness 3: no generalization
A counting model treats cat and dog as unrelated symbols. Seeing "the cat sat on the mat" tells it nothing about "the dog sat on the mat". Neural language models fix this by representing tokens as vectors, so that similar tokens get similar representations and share what they learn. That is the subject of the embeddings chapter.
Generating text from a distribution
Once you have next-token distributions, you can generate text by sampling. The loop below extends the bigram model above. It reuses counts and corpus from the previous block.
import random
def generate(start, length, seed=0):
rng = random.Random(seed)
out = [start]
for _ in range(length):
options = counts[out[-1]]
if not options:
break
tokens = list(options.keys())
weights = list(options.values())
out.append(rng.choices(tokens, weights=weights)[0])
return " ".join(out)
print(generate("the", 8))Each step looks up the distribution for the last token, samples one continuation in proportion to its count, and appends it. The loop stops early if the last token never had a successor in the corpus. The output is locally plausible (the cat sat on the rug .) but has no global plan. A bigram model cannot track a subject across a sentence.
Sampling is only one way to pick the next token. Always taking the most probable token is another. A later chapter covers these decoding choices, including temperature and top-k.
How good is a model? Log-likelihood and perplexity
To compare language models, measure how much probability each assigns to text it was not trained on. The standard quantity is the average negative log-likelihood per token:
NLL = -(1/n) × Σ log P(xt | x1, ..., x_(t-1))
Lower is better. A model that assigns probability 1 to every actual next token has NLL 0. A model that assigns a tiny probability to a token that really occurs gets a large penalty. This is the same cross-entropy loss that pretraining minimizes, which a later chapter covers in detail.
Perplexity is the exponential of NLL:
perplexity = exp(NLL)
You can read perplexity as the effective number of equally likely choices the model is torn between at each step. A uniform model over a 50,000-token vocabulary has perplexity 50,000. A model with perplexity 20 is, on average, as uncertain as if it were choosing among 20 equally likely tokens.
import math
def perplexity(probs_of_actual_tokens):
nll = -sum(math.log(p) for p in probs_of_actual_tokens) / len(probs_of_actual_tokens)
return math.exp(nll)
print(perplexity([0.25, 0.25, 0.25, 0.25]))
print(perplexity([0.9, 0.8, 0.95, 0.7]))The first call prints 4.0 (up to floating-point rounding): the model was always choosing among four equally likely options. The second prints about 1.2, because the model put high probability on each token that actually occurred.
Perplexity depends on the tokenizer. Two models with different vocabularies split the same text into different numbers of tokens, so their perplexities are not directly comparable.
Common errors
- Confusing the vocabulary with the training text. The vocabulary is the fixed list of possible tokens. The training text is the data used to estimate probabilities.
- Treating the output as a single answer. The model outputs a full distribution. Which token you take from it is a separate decision.
- Forgetting the order.
P(cat | the)is not the same asP(the | cat). Conditioning direction matters. - Multiplying many probabilities directly. Use log probabilities to avoid underflow.
- Assuming a model that predicts well "understands". Low perplexity says the model assigns high probability to real text. It does not by itself say how the model reaches that result or whether its statements are true.
Summary of the working model
| Concept | Meaning |
|---|---|
| Token | One item from the fixed vocabulary |
| Context | The earlier tokens the prediction depends on |
| Language model | A function from context to a distribution over the next token |
| Chain rule | Sequence probability equals the product of next-token conditionals |
| Autoregressive generation | Sample a token, append it, repeat |
| Perplexity | Exponential of average negative log-likelihood per token |
An LLM is this same function, with the counting table replaced by a neural network. The network reads a long context, represents tokens as vectors, and produces the distribution. The remaining chapters build that network piece by piece.
Exercise
Using the corpus in the bigram example, what is P(on | sat), and why does the sentence "the cat sat on the sofa ." get probability 0 under the bigram model?
Show answer
P(on | sat) = 1.0, because sat is followed by on both times it appears. The sentence gets probability 0 because sofa never appears in the corpus, so the count for ("the", "sofa") is 0. The product of conditionals therefore contains a factor of 0. Smoothing or a model that generalizes across similar tokens avoids this.
Exercise
A model assigns probabilities 0.5, 0.25, 0.125, and 0.125 to the four tokens that actually occurred in a test sentence. Compute its perplexity.
Show answer
NLL = -(ln 0.5 + ln 0.25 + ln 0.125 + ln 0.125) / 4 = (0.693 + 1.386 + 2.079 + 2.079) / 4 = 1.5596. Perplexity = exp(1.5596) ≈ 4.76. The model is about as uncertain as if it chose among roughly 4.8 equally likely tokens at each step.
Exercise
Why is the chain rule a complete way to model text, and why do we sum log probabilities instead of multiplying probabilities?
Show answer
The chain rule is an exact identity, so a model with correct next-token conditionals gives the correct probability for any whole sequence. We sum log probabilities because multiplying many numbers below 1 produces values too small for floating-point numbers, which underflow to 0. Logs turn the product into a sum and keep the values in a safe range.