2.3Next-token prediction: the core idea
Every LLM is trained on one deceptively simple task, guessing the next token. See it work in a tiny n-gram model, then see why doing it well requires so much more.
One question, asked over and over
Strip away the chat interface, the system prompts and the tool calls, and every GPT-style model does exactly one thing. You give it a sequence of tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit., and it answers one question: what comes next? Not with a single answer, but with a probability distributionProbability distributionAn assignment of probabilities to possible outcomes, summing to 1.: a number for every token in its vocabularyVocabularyThe fixed set of tokens a model knows, typically 32k–260k entries for modern LLMs., all adding up to 1.
Given The capital of France is, a good model might put 0.9 on Paris, a little on a and the, and almost nothing on banana. That’s next-token predictionNext-token predictionThe training objective of LLMs: given the text so far, output a probability distribution over the next token., and it is the entire training objective of a pretrained LLM. Everything impressive these models do, from translation to code to arithmetic, is learned in service of making that one guess better.
Your phone keyboard suggests the next word as you type. It looks at the last word or two, and offers the three most common continuations. Tap one, and it immediately suggests the word after that. Keep tapping and you get a sentence, usually a strange one.
The suggestion bar is the probability distribution. Tapping a suggestion is sampling a token, and tapping repeatedly is autoregressive generation. The phone’s limitation, only looking at the last couple of words, is exactly the weakness of the n-gram model below. An LLM is the same loop with a vastly better predictor that can look back over thousands of tokens.
The simplest language model: counting
Before neural networks, the standard way to predict the next word was to count. An n-gram modelN-gram modelA language model that predicts the next token from only the previous n−1 tokens, using counts from a corpus. looks only at the last tokens. To predict what follows the cat, a trigram model () finds every place the cat appears in its training text and tallies what came next. If the cat was followed by sat 4 times out of 20, then . Claude Shannon used exactly this idea in 1948 to generate increasingly English-looking text, decades before anyone had a GPU.
The demo below trains n-gram models on a tiny story about a cat, a dog, a boy and a girl (about 400 tokens). Training means counting, so it happens instantly in your browser.
Highlighted: the last 2 tokens, the only context a trigram model sees. Seen 19 times in the corpus.
Show the training corpus (400 tokens)
the cat sat on the mat . the dog sat on the rug . the cat saw the dog and the dog saw the cat . the cat was hungry , so the cat ate the fish . the dog was hungry , so the dog ate the bone . the cat was tired , so the cat slept on the mat . the dog was tired , so the dog slept by the door . a bird sat on the roof and sang a song . the cat watched the bird for a long time . the bird flew away when the cat jumped . the cat was sad and went back to the mat . the girl opened the door and the dog ran outside . the dog ran to the park and played with a ball . the boy threw the ball and the dog ran after the ball . the boy laughed and the girl laughed too . in the morning the sun was warm and the cat sat in the sun . in the evening the cat came inside . the girl gave the cat some milk . the cat drank the milk and sat on the girl . the boy gave the dog a bone . the dog took the bone to the garden and hid the bone under a tree . it was a quiet day in the little house . the cat slept , the dog slept , and the bird sang . when the rain came , the dog ran inside and the cat hid under the bed . the girl read a book to the boy . the book was about a cat who could fly . the boy said that the cat in the book was silly . the girl said that the cat in the book was brave . the next day the boy and the girl went to the park with the dog . the dog found a stick in the park and ran back to the boy . the boy threw the stick and the dog ran after the stick . at night the house was dark and quiet . the cat sat by the window and watched the moon . the dog slept by the door , the boy slept in his bed , and the girl dreamed about a cat who could fly .
Things to try:
- n = 1 (unigram). The prompt is ignored. The model predicts
thealmost a quarter of the time (23%) no matter what, because that’s how common it is. Generated text is word salad. - n = 2 (bigram). After
the, it predicts nouns; aftercat, verbs. Local grammar appears, but sentences wander because the model forgets everything except the last word. - n = 3 or 4. Generate 20 tokens a few times. The text gets much more fluent, and you’ll notice it often reproduces long stretches of the corpus word for word. With little data, a long context has usually been seen only once, so there is only one option. The entropy readout drops toward 0 bits.
- Type a word that isn’t in the corpus, like
the elephant. It is crossed out, and the model must back off to a shorter context. Count-based models have no idea that an elephant is anything like a dog.
Why counting doesn’t scale
The demo shows the n-gram dilemma. Short contexts generalize but ignore meaning; long contexts are fluent but have usually never been seen before. The number of possible contexts explodes: with a 50,000-token vocabulary there are possible three-token contexts, so almost any long context you can think of has zero counts, even in a trillion-token corpus.
The fix, proposed by Yoshua Bengio and colleagues in 2003, was a neural language model. Instead of looking up exact matches, it maps tokens to embeddings and computes the prediction with a network. Because elephant and dog have similar vectors, what the model learned about dogs partly transfers to elephants. Modern LLMs are the descendants of that idea, with far more data, far more parameters, and a much better architecture for reading long contexts, the Transformer.
What the network actually outputs
A neural language model doesn’t output probabilities directly. Its last layer produces one raw score per vocabulary entry, called logitsLogitsRaw, unnormalized scores a model outputs, one per class or token. Softmax turns them into probabilities.: for a 100,000-token vocabulary, 100,000 numbers. A softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. turns them into a distribution by exponentiating each score and dividing by the total, so higher logits get exponentially more probability and everything sums to 1.
The training loss for one position is then simply of the probability assigned to the token that actually came next. Put 0.9 on the right token and the loss is about 0.1; put 0.001 on it and the loss is about 6.9. A freshly initialized model that spreads probability evenly over GPT-2’s 50,257 tokens has a loss of per token. Watching that number fall, slowly, over trillions of tokens is what pretraining looks like from the inside.
Autoregression: how a predictor becomes a writer
A model that predicts one token can generate any amount of text with a simple loop:
- Feed in the prompt.
- Get the distribution over the next token.
- Pick a token from it (the most likely one, or a random draw weighted by probability).
- Append it to the sequence and go back to step 1.
This is autoregressiveAutoregressive generationGenerating one token at a time, appending each output to the input before predicting the next. generation: each output becomes part of the next input. It has consequences you can feel when using chatbots. Text streams out one token at a time because it is produced one token at a time. A model can’t go back and revise an earlier token; it can only continue. And a single unlucky pick early on can send everything after it down a different path. How exactly step 3 picks a token (temperature, top-k, top-p) is the topic of the sampling lesson.
Why good prediction requires understanding
“It just predicts the next word” sounds like a dismissal. Think about what perfect prediction would demand. To predict the next token of:
Tokyo is the capital ofyou need geography.3 × 17 =you need arithmetic.- a Python function halfway through, you need to know what the code is supposed to do.
- the last chapter of a detective novel, at
and the murderer was, you need to have followed the clues, the characters and their motives across hundreds of pages.
The training objective is simple, but the data is the whole written record of people explaining, arguing, calculating and storytelling. Any regularity in that data that helps lower the loss, from grammar to facts to reasoning patterns, is something the model is pushed to learn. That is the core bet behind pretrainingPretrainingThe first and largest training phase: next-token prediction on trillions of tokens of general text.. How much genuine “understanding” results is debated, but it is clear that next-token prediction at scale produces far more than autocomplete.
Base models and chat models
A model trained only on next-token prediction is called a base modelBase modelA language model after pretraining only: it continues text rather than following instructions. Chat models are base models with further post-training.. It is a brilliant mimic of documents, not an assistant. Ask a base model What is the capital of France? and it might continue with What is the capital of Germany? What is the capital of Spain?, because in its training data such a question is often part of a quiz list.
Chat models like ChatGPT, Claude or Llama-Instruct start as base models and then go through post-training: supervised fine-tuningSupervised fine-tuning (SFT)Training a pretrained model on curated (prompt, ideal response) examples to teach it to follow instructions. on example conversations, and reinforcement learning from human (or AI) preferences, such as RLHFRLHFReinforcement learning from human feedback: train a reward model on human preference comparisons, then optimize the LLM against it.. Under the hood, the chat model is still predicting the next token. The conversation is formatted as a document with special tokens marking who is speaking, and the model has learned that after <assistant> comes a helpful answer. Part 3 covers this in detail in SFT and instruction tuning.
The context window
Unlike an n-gram model, an LLM can condition on all previous tokens, up to a limit: its context windowContext windowThe maximum number of tokens a model can take into account at once, covering both prompt and output.. GPT-3 (2020) could see 2,048 tokens. Many current models handle 128,000 tokens, and some advertise a million or more. Everything the model “knows” about your conversation must fit in that window: your messages, its replies, any documents you pasted. Anything that falls outside is simply gone, which is why long chats eventually “forget” their beginning.
Bigger windows are expensive, because standard attention compares every token with every other token, so cost grows with the square of the length. The long-context lesson explains how models push this limit.
MATH CORNER · optionalThe language-modeling objective, worked by hand
The chain rule of probability lets us write the probability of any sequence as a product of next-token predictions:
A language model with parameters estimates each factor, . Training minimizes the average cross-entropyCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right. (negative log-likelihood) over the data:
An n-gram model truncates the history to the last tokens and estimates probabilities by counting:
Worked example. Train a bigram model on the corpus the cat sat . the cat ran . the dog sat .
| context | followed by | probabilities |
|---|---|---|
| the | cat ×2, dog ×1 | P(cat) = 2/3, P(dog) = 1/3 |
| cat | sat ×1, ran ×1 | 1/2 each |
| sat | . ×2 | P(.) = 1 |
| dog | sat ×1 | P(sat) = 1 |
Score the sentence the cat sat . (starting after the): . The average loss over its three predictions is nats per token.
The perplexityPerplexityThe exponential of the average cross-entropy per token. Roughly, how many equally likely options the model is choosing between at each step; lower is better. is : on average the model is as uncertain as if it were choosing between about 1.44 equally likely options.
Now score the dog ran .: because that pair never occurred, so the whole sentence gets probability 0 and infinite loss. That is the sparsity problem. Smoothing tricks patch it for n-grams; neural models avoid it by sharing knowledge between similar tokens.
In code
Counting bigrams takes four lines. Asking a real (small) neural model for its next-token distribution takes about ten:
from collections import Counter, defaultdict
tokens = "the cat sat . the cat ran . the dog sat .".split()
counts = defaultdict(Counter)
for a, b in zip(tokens, tokens[1:]):
counts[a][b] += 1
print({w: c / sum(counts["the"].values()) for w, c in counts["the"].items()})
# {'cat': 0.667, 'dog': 0.333}
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
ids = tok("The cat sat on the", return_tensors="pt").input_ids
with torch.no_grad():
logits = model(ids).logits[0, -1] # scores for the NEXT token
probs = logits.softmax(-1)
for p, i in zip(*probs.topk(5)):
print(repr(tok.decode(i)), round(float(p), 3))
- “The model plans the whole answer, then types it out.” Generation really is one token at a time; each token is chosen from a distribution computed from everything before it. Internal representations can anticipate what comes later, but there is no separate finished draft being revealed.
- “Next-token prediction just memorizes the training text.” Small n-gram models do, as the demo shows. Large neural models must generalize, because almost every long context they see is new; memorization of rare passages does happen, but it is not the main thing they do.
- “Chat models use a different objective.” They are still next-token predictors. Post-training changes which continuations they find likely, not the basic mechanism.
- “The context window is the model’s memory of everything it has seen.” It is only the text currently in front of it. Knowledge from training is stored in the weights; the conversation is stored only in the window and is lost once it scrolls out.
Check your understanding
Q1.What does a language model output at each step?
Q2.A trigram model has seen 'the dog' followed by 'ran' 6 times and 'sat' 2 times, and nothing else. What is P(sat | the dog)?
Q3.Why did the n-gram approach hit a wall?
Q4.You ask a base model (no post-training) 'What is the capital of France?'. What is a plausible output?
Q5.During training on a 1,000-token passage, how many next-token predictions does a Transformer make?
Further reading
- bookSpeech and Language Processing, Chapter 3: N-gram Language Models — Jurafsky & Martin's free textbook; the standard reference for n-grams, smoothing and perplexity.
- paperA Neural Probabilistic Language Model — Bengio et al. (2003): learned word embeddings plus a neural network beat counting.
- videoThe spelled-out intro to language modeling: building makemore — Andrej Karpathy builds a bigram model by counting, then by gradient descent.
- paperLanguage Models are Few-Shot Learners — The GPT-3 paper: what pure next-token prediction at scale can do.
- paperTraining language models to follow instructions with human feedback — The InstructGPT paper: how a base model is turned into an assistant.