Level 3 In-Depth AI · Transformers and Language Models
Language Modeling and Next-Token Prediction
A language model assigns a probability to every possible next token given the text so far. That one simple job, done well enough, turns out to require grammar, facts and a surprising amount of reasoning.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an hour to play with the code
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
This leads to
GPT and Decoder-Only ModelsThe full path from zero — 3 concepts before this one
- Probability Basics
- Python for AI
- Tokenization
- Language Modeling and Next-Token Prediction
Read them roughly in this order. See it on the concept map →
Why it matters
Every chatbot you have used is, at its core, a machine that answers one question over and over: given the text so far, what token comes next? It produces a probability for every token in its vocabulary, picks one, appends it to the text, and asks the question again. That is how ChatGPT writes an essay, how Claude writes code and how your phone suggests the next word.
A model that answers this question is called a language model. The job of training it on huge amounts of text to answer it well is next-token prediction. It sounds almost too simple to matter. Yet to predict the next word of "The capital of Australia is" you need a fact. To predict the next line of a proof you need some mathematics. To predict what a character in a novel says next you need some model of people. Large language models are what you get when you push this simple objective as far as compute and data allow (Pretraining Large Language Models, Scaling Laws).
This chapter builds the idea from counting words to the measure everyone uses to compare language models, perplexity, so that GPT and Decoder-Only Models and Build a GPT from Scratch have solid ground to stand on.
The intuition
Play a game with a friend. You read a sentence aloud one word at a time and, before each word, your friend guesses what comes next.
"The cat sat on the …" — your friend says "mat" with confidence. "I take my coffee with milk and …" — "sugar". "The first person to walk on the Moon was …" — "Neil Armstrong", if your friend knows some history.
Your friend is a language model. Notice three things:
- A good guesser doesn't name one word. They have a spread of beliefs: "mat" quite likely, "floor" possible, "sofa" less so, "volcano" almost never. A language model outputs exactly this: a probability distribution over every possible next token.
- Good guesses need knowledge. Grammar tells you a noun is coming, common sense rules out "volcano", and facts tell you "Armstrong".
- You can grade the guesser. If they gave the true next word a high probability, they understood the text well. If they were often surprised, they didn't. That grade is perplexity.
Key idea A language model is a function from "text so far" to "probability of each possible next token". Generate text by sampling from it repeatedly. Train it by making the true next token more probable.
How it works
The probability of a piece of text
Write a sentence as a sequence of tokens . We want its probability, . That is hard to estimate directly, because almost every sentence is new. Nobody has ever written your exact next email.
The chain rule of probability breaks it into manageable pieces. The probability of a sequence is the probability of the first token, times the probability of the second given the first, times the probability of the third given the first two, and so on:
The vertical bar means "given": is a conditional probability, the chance of when you already know and (Probability Basics). The ("pi") means "multiply all of these together", and is short for "all tokens before position ".
This is not an approximation. It is an exact identity. It means a model that can predict one next token given any prefix can assign a probability to any whole text, and can generate text by drawing one token at a time. Models that generate this way, each output feeding back in as input, are called autoregressive models.
n-gram models: just count
The oldest way to estimate is to count how often things follow each other in a big pile of text. The full history is too long to count, so we make the Markov assumption: only the last few tokens matter. An n-gram model looks at the previous tokens:
- A bigram model () uses one previous token: .
- A trigram model () uses two: .
The estimate is a simple ratio of counts. For a bigram:
Read it as: of all the times we saw the previous word, what fraction were followed by this word?
A worked example by hand
Here is a training corpus of three sentences. <s> marks the start of a sentence and </s> the end, so the model can learn how sentences begin and finish.
<s> the cat sat on the mat </s>
<s> the dog sat on the log </s>
<s> the cat saw the dog </s>
Count what follows each word:
| Previous word | What followed it (counts) | Total |
|---|---|---|
<s> |
the 3 | 3 |
| the | cat 2, dog 2, mat 1, log 1 | 6 |
| cat | sat 1, saw 1 | 2 |
| sat | on 2 | 2 |
| on | the 2 | 2 |
| dog | sat 1, </s> 1 |
2 |
| saw | the 1 | 1 |
| mat, log | </s> 1 |
1 each |
Now score the sentence "the cat sat on the log", which never appears in the corpus:
The model has generalised: it stitched together pieces it had seen to give a sensible probability to a new sentence. It has also exposed the big weakness of counting. Try "the dog saw the cat". The model has never seen "dog saw", so , and the whole sentence gets probability zero, even though it is perfectly good English.
Smoothing fixes the zeros by giving every possible continuation a little probability. The simplest version, add-k smoothing, pretends every word followed every context extra times:
where is the vocabulary size. Fancier schemes (Kneser–Ney smoothing, backing off to shorter contexts) powered speech recognisers and machine translation for decades.
The sparsity wall
Why not just use a long context, say the previous 20 words? Because the number of possible contexts explodes. With a 50,000-word vocabulary there are possible 20-word contexts, vastly more than any text collection could ever cover. Almost every long context you meet at test time was never seen in training, so its counts are all zero. n-gram models are stuck with short memories: in practice 3 to 5 words.
Neural language models break the wall. Instead of looking up exact contexts in a table, they map each token to a vector (Word Embeddings) and compute the prediction with a network. Similar contexts get similar vectors, so knowledge about "the dog sat" transfers to "the puppy sat". Recurrent networks (Recurrent Neural Networks, LSTMs and GRUs) and then Transformers (The Transformer, GPT and Decoder-Only Models) let the context grow to thousands and now millions of tokens.
Perplexity: grading a language model
To compare models we test them on text they did not train on and ask: how much probability did you give to what actually happened? Multiplying hundreds of small probabilities gives absurdly tiny numbers, so we work with logarithms and average per token. The average negative log-likelihood is
Each term is the model's "surprise" at the true token. If it gave the right token probability 1, the surprise is . If it gave it 0.01, the surprise is . This quantity is exactly the cross-entropy loss that neural language models minimise during training (Loss Functions, Entropy, Cross-Entropy and KL Divergence).
Perplexity turns it back into a friendlier number:
It has a lovely interpretation: perplexity is the number of equally likely choices the model is, on average, torn between. A model that guesses uniformly among tokens has perplexity exactly . A perplexity of 10 means the model is as uncertain as if it were picking among 10 equally likely tokens at every step. Lower is better.
For our "the cat sat on the log" sentence, the seven probabilities multiply to , so and the perplexity is . Most steps were certain (probability 1); the uncertainty came from two choices, after "the" (twice) and after "cat".
Note Perplexities are only comparable between models that use the same tokenizer and the same test text. A model with a bigger vocabulary predicts fewer, harder tokens. For a fair comparison across tokenizers, people report bits per byte or bits per character instead.
Why next-token prediction teaches so much
The training signal is simple, but minimising it on trillions of tokens of human writing forces the model to absorb whatever helps prediction. Grammar helps, so it learns grammar. Facts help ("Paris is the capital of …"), so it stores facts. Following the steps of an argument helps predict the conclusion, so it learns some of that too. Translation pairs, code with its comments and question-and-answer forums all appear in the training text, so a model that predicts them well can, when prompted, translate, write code and answer questions. That is why a pretrained "base model" can do so much before anyone teaches it to chat (Pretraining Large Language Models, Instruction Tuning and Chat Models).
The same simplicity is also the limitation. A language model learns what text is likely, not what is true. Where the two differ you get hallucinations.
In code
This character-level n-gram model trains on the documentation built into Python's own standard library, so it needs no download. It measures perplexity for to , then generates text.
import math, random, inspect, collections, json, re, string
from collections import Counter, defaultdict
# Training text: the documentation built into Python's own standard library
docs = [inspect.getdoc(obj) for mod in (collections, json, re, string, random, math)
for obj in [mod, *vars(mod).values()] if inspect.getdoc(obj)]
text = " ".join(" ".join(docs).lower().split()) # lowercase, collapse whitespace
split = int(0.9 * len(text))
train, test = text[:split], text[split:]
vocab = sorted(set(text))
V = len(vocab)
print(len(text), "characters,", V, "distinct")
def fit(n):
counts = defaultdict(Counter) # context (n-1 chars) -> next-char counts
for i in range(n - 1, len(train)):
counts[train[i - n + 1:i]][train[i]] += 1
return counts
def prob(counts, ctx, ch, k=0.01): # add-k smoothing: no zero probabilities
c = counts[ctx]
return (c[ch] + k) / (sum(c.values()) + k * V)
def perplexity(counts, n, data):
logp = sum(math.log(prob(counts, data[i - n + 1:i], data[i]))
for i in range(n - 1, len(data)))
return math.exp(-logp / (len(data) - n + 1))
for n in [1, 2, 3, 4, 5, 6]:
m = fit(n)
print(f"{n}-gram train ppl {perplexity(m, n, train):5.2f} test ppl {perplexity(m, n, test):5.2f}")
random.seed(0)
m, out = fit(4), "the "
for _ in range(120): # sample one character at a time
c = m[out[-3:]] # counts of what followed these 3 chars
out += random.choices(list(c), weights=list(c.values()))[0]
print(out)
# Output with Python 3.14 (the docstrings, and so the numbers, vary a little by version):
# 80738 characters, 67 distinct
# 1-gram train ppl 24.48 test ppl 22.45
# 2-gram train ppl 11.06 test ppl 13.35
# 3-gram train ppl 4.72 test ppl 8.20
# 4-gram train ppl 2.46 test ppl 6.13
# 5-gram train ppl 1.83 test ppl 6.08
# 6-gram train ppl 1.60 test ppl 6.94
# the caches will be dev/urange sigma. m the list encoder a dict(ites a data buffer receding[, examply matchesensitializable.
The two curves tell the story of this whole chapter. More context makes predictions sharper, until counting runs out of data. The 6-gram has nearly memorised its training text (perplexity 1.6) but does worse on new text than the 5-gram. That is Overfitting and the Bias–Variance Tradeoff, caused by sparsity. Neural models keep improving with longer context because they generalise between similar contexts instead of looking them up.
The sample is half English, half nonsense: it has learned spelling fragments ("encoder", "dict", "buffer") from a three-character window but has no idea what a sentence is about. Compare it with the output of the small Transformer in Build a GPT from Scratch.
Common pitfalls
- Comparing perplexities across tokenizers. A word-level perplexity, a character-level one and a GPT-2-token one are different units. Only compare like with like, or convert to bits per byte.
- Zero probabilities. Any unsmoothed count model assigns probability 0 to something it hasn't seen, and is minus infinity. One unseen word makes the perplexity infinite.
- Evaluating on training text. Perplexity on the training set rewards memorisation, as the 6-gram shows. Always measure on held-out text, and check that the test text isn't secretly in the training data (contamination).
- Confusing "likely" with "true" or "good". Lower perplexity means better prediction of the test text, not better answers to questions. A model trained on the internet predicts common misconceptions well.
Watch out Log base matters. With natural logarithms, cross-entropy is in nats and perplexity is . With base 2 it is in bits and perplexity is . PyTorch's
cross_entropyuses natural logs. Mixing the two gives perplexities that are wildly wrong.
Where it leads
- Word Embeddings and Recurrent Neural Networks show the first neural language models.
- Attention, Self-Attention and Multi-Head Attention and the The Transformer give models a context of thousands of tokens.
- GPT and Decoder-Only Models is a Transformer trained on exactly the next-token objective from this chapter, and Build a GPT from Scratch trains one on your laptop.
- Decoding: Temperature, Top-k and Top-p covers how to turn the predicted distribution into text: greedy choice, sampling, temperature, top-k and top-p.
- Pretraining Large Language Models and Scaling Laws show what happens when the training text is trillions of tokens. The loss on those curves is the same cross-entropy you met here.
- BERT and Encoder Models uses a different objective, filling in masked words using context on both sides, which suits understanding tasks rather than generation.
A bit of history
Claude Shannon founded information theory in 1948 and, in the same paper, generated "English-like" text from letter and word n-gram statistics. In 1951 he measured how predictable English is by having people guess the next letter of a text, essentially the guessing game from the intuition section. From the 1970s, n-gram language models built by Frederick Jelinek's group at IBM and others became the backbone of speech recognition and later statistical machine translation.
In 2003 Yoshua Bengio and colleagues published A Neural Probabilistic Language Model, which learned a vector for each word and predicted the next word with a neural network, escaping the sparsity wall. Tomáš Mikolov's recurrent neural network language models (2010) pushed perplexities down further, and in 2015 Andrej Karpathy's blog post on character-level RNNs showed the public how much a next-character predictor could pick up. From 2018 OpenAI's GPT series showed that a Transformer language model, scaled up, becomes a general-purpose tool. The objective never changed: predict the next token.
Try it
- By hand, using the bigram table, compute the probability of "the dog sat on the mat". Then compute its perplexity.
- In the code, change
k=0.01tok=1and rerun. What happens to the test perplexity of the 4- to 6-gram models, and why?- Generate text with
fit(2)andfit(6)(adjustout[-3:]to the matching context length). Which looks more like English, and which copies whole phrases from the documentation?Hint for 1: the steps are 3/3, 2/6, 1/2, 2/2, 2/2, 1/6, 1/1, giving 1/36 again, so the perplexity is again about 1.67.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Speech and Language Processing
The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
The Unreasonable Effectiveness of Recurrent Neural Networks
A famous, fun blog post showing what character-level language models learn from Shakespeare, Wikipedia and source code.
Intro to Large Language Models
A one-hour talk for a general audience on what LLMs are, how they are trained and where they are going.
A Neural Probabilistic Language Model
The first neural language model with learned word embeddings, the ancestor of every modern LLM.
Stanford CS224N: NLP with Deep Learning
Word vectors, RNNs, attention, Transformers and LLMs, with lecture videos on YouTube.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/language-modeling.md