Techniquecore
Causal language modeling
Also called next-token prediction, autoregressive language modeling.
Train a network to predict each token from the tokens before it, with a triangular attention mask so no position sees the future.
Causal language modeling trains a network to give, at every position of a text, a probability distribution over the next token given only the tokens before it. By the chain rule, , so a model of these next-token distributions is a full language model, and one that can generate text by sampling one token at a time. The loss is the cross-entropy of the true next tokens, which is the negative log-likelihood of the text. In a transformer decoder, a triangular mask in attention stops each position from seeing later positions, so one forward pass over a sequence of tokens gives all predictions at once. This is the training objective of GPT and of most large language models.
In plain words
Cover a text with a card and slide the card to the right one word at a time. At each step, guess the next word from what you can see. The model learns by making these guesses on a very large amount of text and being scored by how much probability it gave to the word that really came next.
A model trained this way can write: guess a word, add it to the text, and guess again.
In training, all the guesses for one text are made at the same time. Each position is blocked from looking at the words to its right, so no guess can copy the answer.
When it applies
- Any model that must generate text left to right: chat models, code completion, translation decoders, speech recognition decoders.
- Pre-training on raw text with no labels: every token is a target, so there are about as many training signals as tokens.
- Scoring text: the summed log-probability of a sentence gives its likelihood, and the mean loss gives its perplexity.
- When a bidirectional representation of a fixed input is the goal, as in classification of sentences, masked language modeling uses context from both sides and is often a better fit.
The template
Given a text and a model with parameters that outputs logits at each position:
- Shift. The input is and the target at position is .
- Mask. In every self-attention layer, add to the score of query and key the mask if and if , before the softmax.
- Predict. .
- Loss. The mean cross-entropy
averaged over a batch and minimized by backpropagation and a gradient method such as Adam. 5. Generate. At test time, feed the tokens so far, pick the next token from by greedy decoding, sampling or beam search, append it and repeat. A key-value cache keeps the keys and values of past positions so each step processes one new token.
Feeding the true tokens as input in step 1, and not the model's own guesses, is teacher forcing.
The mask gives valid conditionals (theorem). With the mask in every attention layer, and all other layers acting on each position alone, the output at position depends only on . By induction on the layers: the input at depends on alone; a position-wise layer keeps the set of inputs it depends on; and masked attention at mixes only positions , each of which depends on . So is a function of , a proper conditional, and the summed loss is exactly .
The minimizer is the true conditional (theorem). For a fixed context , the expected loss over distributions equals the entropy of plus the Kullback-Leibler divergence , which is zero only at . So with enough capacity and data, minimizing the loss recovers the next-token distribution of the source, and the lowest possible mean loss is its entropy rate.
Classic examples
A three-word step. A model with vocabulary outputs the logits . The softmax gives . If the true next token is the loss is nats; if it is the loss is .
Perplexity of a short text. A model gives the four true next tokens of a text the probabilities . The losses are 1, 2, 3 and 3 bits, with mean 2.25 bits nats, and the perplexity is : the model is as unsure as a uniform choice among about 4.76 tokens.
N-gram models. An n-gram language model is a causal language model that keeps only the last tokens of the context and estimates the conditionals by counting, with smoothing for unseen n-grams.
Neural language models. The neural probabilistic language model of Bengio and colleagues learned the conditionals with word embeddings and a fixed window; the recurrent language model used the whole prefix through a hidden state.
GPT. GPT pre-trains a decoder-only transformer with this objective on raw text and then adapts it to tasks. Larger models of this kind show in-context learning, and their loss follows neural scaling laws in model size, data and compute (a measurement).
Human prediction. Shannon estimated the entropy of English by asking people to guess the next letter of a text, the same task with a person as the model.
Variations
- Prefix language modeling. The first part of the input is seen with full attention, and only the rest is predicted with the causal mask. It mixes an encoder over the prefix with a decoder.
- Fill in the middle. Cut a document into prefix, middle and suffix, move the middle to the end with marker tokens, and train with the plain causal objective. The model can then fill a gap given text on both sides, as Bavarian and colleagues showed for code and text.
- Packing. Short documents are joined with a separator token into sequences of fixed length to avoid padding. The attention mask may also be cut at document boundaries.
- Other causal models. The objective does not need attention: recurrent networks and selective state space models are causal by construction.
- Label smoothing. Mixing the one-hot target with a uniform distribution, as in label smoothing, was used in the original transformer for translation.
Pitfalls
- Off-by-one shift. Predicting from a position that already sees gives a near-zero loss and a useless model. Check that the target at position is and that the mask allows only.
- Leaks through other paths. A bidirectional layer, a normalization over the time axis, or a convolution that is not causal lets the future into position even with a correct attention mask.
- Loss on padding. Padding positions must be left out of the loss and of the mean; otherwise short sequences change the scale of the loss.
- Comparing perplexities. Perplexity per token depends on the tokenizer. Compare models with different subword tokenizations by bits per character or per byte instead.
- Exposure bias. In training the model always sees true prefixes, but in generation it sees its own outputs, and early errors can push it to contexts it never saw; see exposure bias.
- Not a bidirectional encoder. The representation at position knows nothing of the words after , which hurts tasks such as tagging the first word of a sentence.
Exercises
- Prove by induction on the layers that, with the causal mask, the output at position of a transformer decoder does not depend on .
- Show that and conclude that the expected loss is minimized at .
- A model gives the true tokens of a text of 5 tokens the probabilities . Compute the mean loss in bits and the perplexity.
- Show that a bigram model is a causal language model whose conditionals depend on alone, and write its maximum-likelihood estimate.
- With a key-value cache, count the attention operations needed to generate tokens after a prompt of tokens, and compare with running the full model again at every step.
References
- Bengio et al. 2003, the factorization of the joint probability into next-word conditionals and the training by log-likelihood
- Vaswani et al. 2017, Section 3.2.3 (masking the illegal connections in the decoder by setting them to minus infinity before the softmax)
- Radford et al. 2018, the unsupervised pre-training objective with a decoder-only transformer, followed by supervised fine-tuning
- Bavarian et al. 2022, the transformation that moves a middle span to the end, so a causal model learns to fill in text
- Shannon 1951, the estimate of the entropy of English from the next-letter predictions of people
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C12QAQ Edit this page History Report an error Markdown