◆ AI All-in-One

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
↗ Plan a path here

Read first

TokenizationProbability Basics

This leads to

GPT and Decoder-Only Models
The full path from zero — 3 concepts before this one
  1. Probability Basics
  2. Python for AI
  3. Tokenization
  4. 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:

  1. 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.
  2. Good guesses need knowledge. Grammar tells you a noun is coming, common sense rules out "volcano", and facts tell you "Armstrong".
  3. 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 w1,w2,…,wTw_1, w_2, \dots, w_T. We want its probability, P(w1,w2,…,wT)P(w_1, w_2, \dots, w_T). 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:

P(w1,…,wT)=P(w1) P(w2∣w1) P(w3∣w1,w2)⋯P(wT∣w1,…,wT−1)=∏t=1TP(wt∣w<t)P(w_1, \dots, w_T) = P(w_1)\, P(w_2 \mid w_1)\, P(w_3 \mid w_1, w_2) \cdots P(w_T \mid w_1, \dots, w_{T-1}) = \prod_{t=1}^{T} P(w_t \mid w_{<t})

The vertical bar ∣\mid means "given": P(w3∣w1,w2)P(w_3 \mid w_1, w_2) is a conditional probability, the chance of w3w_3 when you already know w1w_1 and w2w_2 (Probability Basics). The ∏\prod ("pi") means "multiply all of these together", and w<tw_{<t} is short for "all tokens before position tt".

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 P(wt∣w<t)P(w_t \mid w_{<t}) 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 n−1n-1 tokens:

  • A bigram model (n=2n = 2) uses one previous token: P(wt∣wt−1)P(w_t \mid w_{t-1}).
  • A trigram model (n=3n = 3) uses two: P(wt∣wt−2,wt−1)P(w_t \mid w_{t-2}, w_{t-1}).

The estimate is a simple ratio of counts. For a bigram:

P(wt∣wt−1)=count(wt−1 wt)count(wt−1)P(w_t \mid w_{t-1}) = \frac{\text{count}(w_{t-1}\, w_t)}{\text{count}(w_{t-1})}

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:

P=33⏟the∣<s>×26⏟cat∣the×12⏟sat∣cat×22⏟on∣sat×22⏟the∣on×16⏟log∣the×11⏟</s>∣log=136≈0.028P = \underbrace{\tfrac{3}{3}}_{\text{the}\mid\text{<s>}} \times \underbrace{\tfrac{2}{6}}_{\text{cat}\mid\text{the}} \times \underbrace{\tfrac{1}{2}}_{\text{sat}\mid\text{cat}} \times \underbrace{\tfrac{2}{2}}_{\text{on}\mid\text{sat}} \times \underbrace{\tfrac{2}{2}}_{\text{the}\mid\text{on}} \times \underbrace{\tfrac{1}{6}}_{\text{log}\mid\text{the}} \times \underbrace{\tfrac{1}{1}}_{\text{</s>}\mid\text{log}} = \frac{1}{36} \approx 0.028
Scoring a sentence one token at a time (bigram model from the 3-sentence corpus) <s> the cat sat on the log </s> 3/3 2/6 1/2 2/2 2/2 1/6 1/1 Each arrow is P(next | previous). Multiply them all: P = 1 × 2/6 × 1/2 × 1 × 1 × 1/6 × 1 = 1/36 ≈ 0.028 This exact sentence never appears in the corpus, yet it gets a sensible probability. Zoom in: the model's guess for the token after "the" cat 2/6 dog 2/6 mat 1/6 log 1/6 Counts after "the" in the corpus: cat 2, dog 2, mat 1, log 1 (total 6) Probabilities sum to 1: a language model always outputs a full distribution over the vocabulary, not a single answer.
Fig. 1 The chain rule in action. Each arrow carries the bigram probability of the next token given the previous one, and the sentence's probability is their product. Below, the full distribution the model predicts after "the".

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 P(saw∣dog)=0/2=0P(\text{saw} \mid \text{dog}) = 0/2 = 0, 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 kk extra times:

P(wt∣wt−1)=count(wt−1 wt)+kcount(wt−1)+k VP(w_t \mid w_{t-1}) = \frac{\text{count}(w_{t-1}\, w_t) + k}{\text{count}(w_{t-1}) + k\,V}

where VV 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 50,0002050{,}000^{20} 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

L=−1T∑t=1Tlog⁡P(wt∣w<t)L = -\frac{1}{T} \sum_{t=1}^{T} \log P(w_t \mid w_{<t})

Each term is the model's "surprise" at the true token. If it gave the right token probability 1, the surprise is −log⁡1=0-\log 1 = 0. If it gave it 0.01, the surprise is −log⁡0.01≈4.6-\log 0.01 \approx 4.6. 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:

perplexity=eL\text{perplexity} = e^{L}

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 VV tokens has perplexity exactly VV. 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 1/361/36, so L=−17ln⁡136=3.587≈0.51L = -\frac{1}{7}\ln\frac{1}{36} = \frac{3.58}{7} \approx 0.51 and the perplexity is e0.51≈1.67e^{0.51} \approx 1.67. 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 n=1n = 1 to 66, 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.
0 5 10 15 20 25 1 2 3 4 5 6 n (context = previous n − 1 characters) perplexity (lower is better) training text held-out text more context helps… …until most long contexts were never seen in training
Fig. 2 Perplexity of character n-gram models from the code above. On the training text, longer contexts always help. On held-out text the gains stop around n = 5 and then reverse, because most long contexts were never seen in training.

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 log⁡0\log 0 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 eLe^{L}. With base 2 it is in bits and perplexity is 2L2^{L}. PyTorch's cross_entropy uses natural logs. Mixing the two gives perplexities that are wildly wrong.

Where it leads

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

  1. By hand, using the bigram table, compute the probability of "the dog sat on the mat". Then compute its perplexity.
  2. In the code, change k=0.01 to k=1 and rerun. What happens to the test perplexity of the 4- to 6-gram models, and why?
  3. Generate text with fit(2) and fit(6) (adjust out[-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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A bigram model was trained on a small corpus that never contains the pair "dog saw". Without smoothing, what probability does it give the perfectly good sentence "the dog saw the cat"?

  2. A language model reports a perplexity of 10 on a held-out text. What does that mean in plain terms?

  3. Character n-gram models from n = 1 to 6 are trained. Training perplexity keeps falling, but test perplexity is worse for the 6-gram than for the 5-gram. Why?

  4. Model A has perplexity 12 using a word-level vocabulary; model B has perplexity 30 using a GPT-2 tokenizer, on the same text. What can you conclude?

  5. Why does the chain rule of probability matter so much for language models?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Speech and Language Processing

Dan Jurafsky & James H. Martin · Intermediate · Free

The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

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.

Video

Intro to Large Language Models

Andrej Karpathy · 2023 · Beginner · Free

A one-hour talk for a general audience on what LLMs are, how they are trained and where they are going.

Paper

A Neural Probabilistic Language Model

Bengio, Ducharme, Vincent & Jauvin · 2003 · Advanced · Free

The first neural language model with learned word embeddings, the ancestor of every modern LLM.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/language-modeling.md