From Language Modeling to Next-Token Prediction
Language modeling estimates the probability of a text and uses the chain rule to split it into a product of "predict the next token given the prefix"; training uses cross-entropy, evaluation uses perplexity, and the causal mask hides future tokens.
After this page you will be able to
- Say what language modeling estimates, and use the chain rule to split the probability of a sentence into one prediction per token.
- Run a small bigram language model to see how a conditional probability is estimated from data.
- Write down the cross-entropy loss and perplexity, and say what they mean.
- Explain how teacher forcing and the causal mask turn one forward pass into T training signals.
- State the strengths and the limits of the next-token objective.
On this page
- What a language model is actually modeling
- The chain rule: turn a sentence probability into word-by-word prediction
- A runnable example: a bigram language model
- From n-grams to Transformers: how to estimate the conditional probability
- The training objective: cross-entropy
- Perplexity
- Teacher forcing and the causal mask: one forward pass, T training signals
- Other training objectives
- The power and limits of this objective
- Summary and exercises
- Quick self-check
- FAQ
What a language model is actually modeling
The question a language model answers is: given a piece of text, how likely is it? Formally, for a token sequence the model gives a probability .
Scoring a whole sentence directly is practically impossible: the number of possible sentences is astronomical, and almost none of them ever appeared in the training data. So the big problem has to be broken into many small ones.
The chain rule: turn a sentence probability into word-by-word prediction
The chain rule of probability says a joint probability can be split into a product of conditional probabilities:
Here stands for all the tokens before position . This decomposition is exact, with no approximation. It turns “judge a whole text” into “predict the next token at every position”, which is autoregressive language modeling: the current output depends on all earlier outputs.
So a language model only has to learn one thing:
Given a prefix , output a probability distribution over the vocabulary for the next token.
A runnable example: a bigram language model
The simplest implementation is the bigram model, which looks only at the previous word. Counting is enough to estimate the conditional probabilities. The code below demonstrates it on a tiny corpus:
import math
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the dog sat on the log .".split()
corpus += "the cat saw the dog .".split()
vocab = sorted(set(corpus))
V = len(vocab)
counts = defaultdict(Counter)
for prev, nxt in zip(corpus, corpus[1:]):
counts[prev][nxt] += 1
def prob(nxt: str, prev: str, k: float = 0.1) -> float:
"""P(next | prev) with add-k smoothing, so unseen pairs get p > 0."""
total = sum(counts[prev].values())
return (counts[prev][nxt] + k) / (total + k * V)
def perplexity(tokens: list[str]) -> float:
pairs = list(zip(tokens, tokens[1:]))
nll = -sum(math.log(prob(n, p)) for p, n in pairs) / len(pairs)
return math.exp(nll)
print("V =", V)
print("P(sat | cat) =", round(prob("sat", "cat"), 3))
print("P(mat | the) =", round(prob("mat", "the"), 3))
print("P(cat | the) =", round(prob("cat", "the"), 3))
natural = "the cat sat on the mat .".split()
shuffled = "mat the on . sat cat the".split()
print("perplexity (natural) =", round(perplexity(natural), 2))
print("perplexity (shuffled) =", round(perplexity(shuffled), 2))
Output:
V = 9
P(sat | cat) = 0.379
P(mat | the) = 0.159
P(cat | the) = 0.304
perplexity (natural) = 2.37
perplexity (shuffled) = 31.23
The widget below brings this bigram model into the browser: corpus, smoothing and the perplexity formula match the code line for line and recompute live — load the natural or shuffled preset, or click vocabulary words to build your own sentence, and watch the perplexity and P(next word | last word) react; push the smoothing k to 1 and watch the two perplexities approach each other.
The fluent sentence has a perplexity of only 2.37, and after shuffling the word order it jumps to 31.23. The model “knows” which continuations are more common, which is the plainest form of language modeling.
The problems with the bigram model are just as clear: looking at one word cannot capture long-range dependencies, and looking at more words (n-grams) makes the number of combinations explode, so most of them never occur and the estimates become unreliable.
From n-grams to Transformers: how to estimate the conditional probability
The whole history of language models is essentially an answer to a single question: how do we estimate better?
| Stage | Approach | Main limitation |
|---|---|---|
| n-gram | Count what follows a fixed-length prefix | Very short context window; sparse data; no generalization to similar words |
| Feed-forward neural LM | Represent words as vectors and predict the next word with a neural network | Fixed context length |
| RNN / LSTM | Compress a history of any length into a recurrent state | Hard to train in parallel; long-range information is easily lost |
| Transformer | Let the current position read the whole prefix directly through attention | Attention compute and cache cost grow with length |
The strength of neural networks is generalization: similar words get similar vectors, so after seeing “the cat sat on the mat” the model can still assign a reasonable probability to “the dog sat on the mat”. Counting methods cannot do that.
The training objective: cross-entropy
The model outputs a probability distribution over the vocabulary, and training should give the true next token a higher probability. For one sequence, the loss is the average negative log-likelihood across positions:
This is the cross-entropy loss (how it relates to entropy and KL divergence is covered in Information Theory Refresher). When the true token has probability 1 the loss is 0, and the lower the probability the larger the loss. A useful reference point: if the model treats all tokens of a vocabulary of size equally (a uniform distribution), the loss is . For that is about . The loss of a freshly initialized model starts near this number, and training is the process of driving it down.
Perplexity
Perplexity is the exponential of the cross-entropy:
It has an intuitive reading: on average the model behaves as if it were choosing among equally likely candidates. For a uniform distribution ; the bigram model above gets 2.37 on a fluent sentence, which means it hesitates between only two or three candidates at each step.
Perplexity is an average “per token”. With different tokenizers, the same text has a different number of tokens, so the perplexities are not comparable. To compare different models, use the tokenizer-independent bits-per-byte:
Teacher forcing and the causal mask: one forward pass, T training signals
During training we have the complete text, and the “correct answer” at each position is the token that follows it. So there is no need to compute token by token as in generation: feed the whole sequence into the model at once, let every position predict its next token at the same time, and average the losses over all positions. This is teacher forcing: when predicting token , the input is the true prefix, not a prefix generated by the model itself.
There is a trap, though: if position could see the content at position , prediction would turn into copying the answer. The fix is a causal mask in attention, so that position can only attend to positions :
After adding , softmax sets the weights of future positions to 0. As a result, the same computation is both parallel and strictly “left-only”. This is one of the key reasons Transformer training is more efficient than RNN training: one sequence of length yields training signals in one forward pass.
In code, remember the one-position shift: the output at position is paired with the label token .
import torch
import torch.nn.functional as F
def lm_loss(logits: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor:
"""logits: [batch, seq, vocab]; input_ids: [batch, seq]."""
# Position t predicts token t+1: drop the last logits and the first label
shifted_logits = logits[:, :-1, :]
shifted_labels = input_ids[:, 1:]
return F.cross_entropy(
shifted_logits.reshape(-1, shifted_logits.size(-1)),
shifted_labels.reshape(-1),
)
The widget below turns this section into a T x T table you can click: rows are the predicting positions, columns the positions they can read, and each cell holds the post-softmax weight (illustrative: uniform over the visible positions when the scores are equal). Click a row to see what it reads and what its label is, shorten the sentence and watch the number of training signals stay at T − 1, then switch the causal mask off and see every position read its own answer.
Other training objectives
“Predict the next token” is not the only choice, but it is the mainstream for today’s general-purpose LLMs:
| Objective | How it works | Representative models | Best for |
|---|---|---|---|
| Causal language modeling (CLM) | Predict the next token from the left context | GPT series, Llama, Qwen, DeepSeek | Generation, chat, general tasks |
| Masked language modeling (MLM) | Hide random tokens and recover them from both sides | BERT | Classification, retrieval, sequence labeling |
| Encoder-decoder | The encoder reads the input, the decoder generates the output token by token | T5 (paper breakdown), BART | Translation, summarization and other tasks with a clear input and output |
The main reason causal language modeling won is that the training objective matches how the model is used. What it learns in training is “keep writing”, and in use it also keeps writing, so there is no need for a different structure per task; its training signal is also dense, since every token is a supervised signal.
The power and limits of this objective
Why it is so effective. Minimizing cross-entropy is equivalent to maximizing the compression of the text: the more accurately the model predicts, the fewer bits it takes to encode the text. To compress internet-scale text well, a model has to learn grammar, facts, common sense, code structure and all sorts of reasoning patterns, which is why general abilities emerge from “predict the next word”. For more on this, see What Is a Large Language Model?.
What it cannot guarantee.
- Factuality. The objective rewards “continuations that look like the training text”, not “verified truths”. The consequences are worked out in Hallucination and Calibration.
- Training versus inference. In training the input is the true prefix, while at inference it is a prefix the model generated itself. Once an early deviation appears, later errors can compound, which is known as exposure bias.
- Alignment. Predicting the next word does not mean “answering according to the user’s intent”. That is exactly the problem post-training solves.
Summary and exercises
Key points of this page:
- A language model estimates and uses the chain rule to decompose it into a product of per-token conditional probabilities.
- The training objective is cross-entropy and the evaluation metric is perplexity; the two convert into each other through the exponential.
- The causal mask makes parallel training and “left-only” hold at the same time; in the implementation the labels are shifted by one position relative to the input.
- Causal language modeling is the mainstream objective of general-purpose LLMs because training and use are consistent.
Quick self-check
1. Writing the probability of a whole text as a product of per-token conditional probabilities: what kind of step is this?
- The chain rule, an exact decomposition with no approximation
- An approximation that assumes all tokens are independent
- An approximation that assumes each token depends only on the one before it
- Valid only during training; inference needs a different decomposition
The chain rule holds for any joint distribution. The approximation in a language model lies in how each conditional probability is estimated, not in the decomposition: a bigram model looks at the previous word only, while a Transformer lets every position read the whole prefix.
2. A model with a vocabulary of 50,000 has just been initialized and outputs a nearly uniform distribution. What is its per-token cross-entropy loss, roughly?
- About 0.5
- About 4.7
- About 10.82
- About 50,000
Under a uniform distribution every token has probability 1/V, so the loss is ln V, and ln 50000 ≈ 10.82 (4.7 is the base-10 logarithm, not the natural logarithm that cross-entropy uses). The matching perplexity is 50,000, exactly the vocabulary size.
3. Why can’t you compare the perplexity of two models that use different tokenizers?
- Because perplexity is only defined for English
- Because perplexity is an average per token, and the same text is cut into a different number of tokens, so the unit of the average differs
- Because perplexity changes with the number of parameters
- Because the tokenizer changes the loss function
To compare across tokenizers use a tokenizer-independent metric such as bits-per-byte: the total negative log-likelihood (base 2) divided by the number of bytes of the text.
4. What does the causal mask do?
- It adds −∞ to the attention scores of past positions so the model only attends to the current token
- It adds −∞ to the attention scores of future positions; after softmax their weights are 0, so each position sees only itself and the positions to its left
- It replaces a random subset of input tokens with a special mask symbol
- It ignores the tokens at the end of the sequence when computing the loss
With the causal mask, the whole sequence can be processed in one parallel forward pass, giving a prediction at every position, without peeking at the answers. The third option describes BERT’s masked language modeling; the names are similar but the roles differ.
5. When implementing the language-model loss you drop the logits of the last position and the label of the first position, shifting by one. Why?
- The output at position t predicts token t+1, so the logits at position t must be paired with token t+1
- The last position has no input, so nothing can be computed there
- The first token is always a special symbol and needs no prediction
- The loss goes down faster after the shift
The last position predicts the token after the end of the sequence, which has no label in the training data; the first token has no context, so no position predicts it. One is dropped on each side, leaving T−1 pairs.
6. What train/inference mismatch does teacher forcing cause?
- Training uses gradient descent and inference does not
- In training the input at each position is the true prefix, at inference it is the model’s own generated prefix, so early deviations can snowball
- Training can only predict one token at a time
- Inference must use a causal mask and training does not
The mismatch is called exposure bias. Training and inference both use the causal mask; the only difference is whether the prefix comes from real text or from the model’s own output.
Exercises:
- In the bigram model above, change the smoothing coefficient to and to , observe how the perplexity changes, and explain why.
- For a vocabulary size , compute the loss and perplexity of a uniform distribution.
- Build a causal mask with PyTorch, print the attention weights after
softmax, and verify that the entire upper triangle is 0.
Reference answers
-
Results for the same corpus and the same sentences, with the three smoothing coefficients (change
kin the code above to 1, 0.1 and 0.001):k Perplexity, natural sentence Perplexity, shuffled Probability of sat after cat 1 4.90 11.40 0.182 0.1 2.37 31.23 0.379 0.001 1.82 2149.99 0.498 The larger is, the flatter all probabilities become: seen combinations lose probability and unseen ones gain it. The natural sentence therefore gets a higher perplexity and the shuffled one a lower perplexity, so the model tells good from bad less sharply. The smaller is, the closer the estimate gets to plain counting: the natural sentence gets a lower perplexity, but unseen combinations are pushed to almost 0 probability and the shuffled sentence explodes to about 2150. The smoothing coefficient trades off “trust the counts” against “leave room for combinations never seen”.
-
Under a uniform distribution the loss is and the perplexity is exactly , the vocabulary size.
-
A reference implementation (all scores equal, so the weights are decided by the mask alone):
import torch T = 4 scores = torch.zeros(T, T) mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1) weights = torch.softmax(scores.masked_fill(mask, float("-inf")), dim=-1) print(weights) print("upper triangle all 0:", bool((weights[mask] == 0).all()))Output:
tensor([[1.0000, 0.0000, 0.0000, 0.0000], [0.5000, 0.5000, 0.0000, 0.0000], [0.3333, 0.3333, 0.3333, 0.0000], [0.2500, 0.2500, 0.2500, 0.2500]]) upper triangle all 0: TrueRow splits the weight evenly over the positions , and the weights of future positions are exactly 0.
Next, read Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table to see where tokens come from, or go straight to Attention Basics to see how a Transformer reads the context.
FAQ
- Is lower perplexity always better?
- On the same test data with the same tokenizer, lower perplexity means the text is less "surprising" to the model, which is usually better. But perplexity depends on tokenization, so models with different tokenizers cannot be compared directly; cross-model comparisons should use a tokenizer-independent metric such as bits-per-byte. Low perplexity also does not imply instruction following, factual accuracy or safety.
- Why can an LLM predict the next token at every position at the same time during training?
- Because training uses complete text, the "correct answer" at each position is simply the next token (teacher forcing). With a causal mask the model computes the predictions for all positions in parallel without peeking at the future, so a sequence of length T provides T-1 training signals in a single forward pass.
- How does next-token prediction differ from BERT's masked language modeling?
- Next-token prediction only lets the model see the left context, which suits generation naturally. BERT's masked language modeling hides random tokens and recovers them from both the left and right context, which suits understanding tasks better but cannot generate token by token. Today's mainstream general-purpose LLMs use the former.