2 Foundations 2 / 6
  1. In this chapter
  2. Python and tensor shapes
  3. From Language Modeling to Next-Token Prediction
  4. Neural Network Basics
  5. Information Theory Refresher
  6. Tokenizers and Embeddings
  7. Optimizers and Training Stability
All chapters →

Chapter 2 · Foundations 2.2

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.

Beginner 13 min read Updated Companion code ↓

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
  1. What a language model is actually modeling
  2. The chain rule: turn a sentence probability into word-by-word prediction
  3. A runnable example: a bigram language model
  4. From n-grams to Transformers: how to estimate the conditional probability
  5. The training objective: cross-entropy
  6. Perplexity
  7. Teacher forcing and the causal mask: one forward pass, T training signals
  8. Other training objectives
  9. The power and limits of this objective
  10. Summary and exercises
  11. Quick self-check
  12. 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 x1,x2,…,xTx_1, x_2, \dots, x_T the model gives a probability P(x1,x2,…,xT)P(x_1, x_2, \dots, x_T).

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:

P(x1,…,xT)=P(x1) P(x2∣x1) P(x3∣x1,x2)⋯P(xT∣x<T)=∏t=1TP(xt∣x<t)P(x_1, \dots, x_T) = P(x_1)\,P(x_2 \mid x_1)\,P(x_3 \mid x_1, x_2)\cdots P(x_T \mid x_{<T}) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

Here x<tx_{<t} stands for all the tokens before position tt. 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 x<tx_{<t}, output a probability distribution P(⋅∣x<t)P(\cdot \mid x_{<t}) 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 P(xt∣x<t)P(x_t \mid x_{<t}) better?

StageApproachMain limitation
n-gramCount what follows a fixed-length prefixVery short context window; sparse data; no generalization to similar words
Feed-forward neural LMRepresent words as vectors and predict the next word with a neural networkFixed context length
RNN / LSTMCompress a history of any length into a recurrent stateHard to train in parallel; long-range information is easily lost
TransformerLet the current position read the whole prefix directly through attentionAttention 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:

L(θ)=−1T∑t=1Tlog⁡pθ(xt∣x<t)\mathcal{L}(\theta) = -\frac{1}{T} \sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t})

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 VV equally (a uniform distribution), the loss is ln⁡V\ln V. For V=50,000V = 50{,}000 that is about 10.8210.82. 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:

PPL=exp⁡(L)\mathrm{PPL} = \exp(\mathcal{L})

It has an intuitive reading: on average the model behaves as if it were choosing among PPL\mathrm{PPL} equally likely candidates. For a uniform distribution PPL=V\mathrm{PPL} = V; 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 cannot be compared across tokenizers

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:

BPB=∑t−log⁡2p(xt∣x<t)number of bytes in the text\mathrm{BPB} = \frac{\sum_t -\log_2 p(x_t \mid x_{<t})}{\text{number of bytes in the text}}

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 t+1t+1, the input is the true prefix, not a prefix generated by the model itself.

There is a trap, though: if position tt could see the content at position t+1t+1, prediction would turn into copying the answer. The fix is a causal mask in attention, so that position ii can only attend to positions j≤ij \le i:

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V,Mij={0j≤i−∞j>i\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}} + M\right)V,\qquad M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases}

After adding −∞-\infty, 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 TT yields T−1T-1 training signals in one forward pass.

In code, remember the one-position shift: the output at position tt is paired with the label token t+1t+1.

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:

ObjectiveHow it worksRepresentative modelsBest for
Causal language modeling (CLM)Predict the next token from the left contextGPT series, Llama, Qwen, DeepSeekGeneration, chat, general tasks
Masked language modeling (MLM)Hide random tokens and recover them from both sidesBERTClassification, retrieval, sequence labeling
Encoder-decoderThe encoder reads the input, the decoder generates the output token by tokenT5 (paper breakdown), BARTTranslation, 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:

  1. A language model estimates P(x1,…,xT)P(x_1,\dots,x_T) and uses the chain rule to decompose it into a product of per-token conditional probabilities.
  2. The training objective is cross-entropy and the evaluation metric is perplexity; the two convert into each other through the exponential.
  3. 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.
  4. 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:

  1. In the bigram model above, change the smoothing coefficient kk to 11 and to 0.0010.001, observe how the perplexity changes, and explain why.
  2. For a vocabulary size V=32,000V = 32{,}000, compute the loss and perplexity of a uniform distribution.
  3. Build a 4×44 \times 4 causal mask with PyTorch, print the attention weights after softmax, and verify that the entire upper triangle is 0.
Reference answers
  1. Results for the same corpus and the same sentences, with the three smoothing coefficients (change k in the code above to 1, 0.1 and 0.001):

    kPerplexity, natural sentencePerplexity, shuffledProbability of sat after cat
    14.9011.400.182
    0.12.3731.230.379
    0.0011.822149.990.498

    The larger kk 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 kk 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”.

  2. Under a uniform distribution the loss is ln⁡32000≈10.37\ln 32000 \approx 10.37 and the perplexity is exactly 32,00032{,}000, the vocabulary size.

  3. 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: True

    Row ii splits the weight evenly over the positions j≤ij \le i, 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.