A language model does one thing: given the tokens of a text so far, it gives a probability to every possible next token. Everything else in this roadmap, from attention to RLHF (reinforcement learning from human feedback), is a better way of computing that one distribution.
Example. After "the cat sat on the", an imaginary model might give "mat" probability 0.4, "floor" 0.2, "sofa" 0.1, and spread the remaining 0.3 over every other token of the vocabulary. The probabilities of all the tokens add up to 1.
This page builds the two oldest models that still teach the most, a counting model and a small neural one, and then shows how to turn their probabilities into text.
The chain rule of probability
A language model only predicts one token at a time, yet it gives a probability to whole texts. The link is the chain rule of probability: the probability of a sequence is the product of the next-token probabilities.
where:
- are the tokens of the text;
- , read "the probability of given the tokens before it", is the model's next-token prediction at position ;
- means "multiply together", for from 1 to .
Example. For the text "the cat sat": if , and , then .
This is not an approximation: it is just the definition of conditional probability, applied times. So a model that predicts the next token well models whole texts well, and training it means minimizing the cross-entropy of the previous section, averaged over every position.
Counting: the bigram model
The simplest model forgets everything except the last token: to predict it looks only at . This is a bigram model ("bi" for the two tokens involved). It is a table with one row per previous token and one column per next token, and it is built by counting.
- Count. For every pair of neighbours in the training text, add 1 to the cell (previous token, next token).
- Normalize. Divide each row by its total, so that every row adds up to 1.
where is the number of times token comes right after token , and the sum below counts every token that comes after . In words: of all the times we saw , the fraction followed by . This is the maximum-likelihood estimate: the table under which the training text is most probable.
Example. The text "a b a b a c", with vocabulary . Its pairs are a→b, b→a, a→b, b→a, a→c.
previous → a → b → c probabilities a 0 2 1 b 2 0 0 c 0 0 0 undefined The middle columns are the counts: how many times "a", "b" or "c" came next. Row "c" is , undefined: "c" is never followed by anything.
After "a", the model predicts "b" with probability and "c" with .
Smoothing: no zeros allowed
The problem is zeros. In the example, : the model is sure that "a a" never happens. If a test text contains "a a" even once, the probability of the whole text is 0 (the chain rule multiplies by 0) and its loss is infinite. And the row of "c" is not even defined, because "c" was never followed by anything.
Add- smoothing (called Laplace smoothing when ) pretends every pair was seen extra times:
where is the vocabulary size: is added to each of the cells of the row, so the total grows by and the row still adds up to 1.
Example. Same counts, , .
- Row a: counts become , total 6: probabilities . "a a" is now unlikely but possible.
- Row b: becomes , total 5: .
- Row c: becomes : uniform, . With no data, the model has no preference.
Perplexity
Models are compared by perplexity, , where is the mean negative log-likelihood per token, measured on text the model was not trained on. It reads as "the number of tokens the model is hesitating between, on average": a model that guesses uniformly among tokens has perplexity exactly , a perfect model has perplexity 1.
Example. The smoothed table on its own training text "a b a b a c": the five transitions get probabilities . The mean of is , so the perplexity is : the model hesitates between about 2 of the 3 tokens.
Why counting does not scale
Longer contexts help: a model that looks at the last 2 tokens (a trigram) knows that after "on the" comes a noun. But the table needs one row per possible context. With a vocabulary of tokens, a bigram table has billion cells, and a trigram table . Almost all of them are never observed in any training text, so the model has no information about most contexts it meets. This is the curse of dimensionality that pushed language modeling towards neural networks.
A neural language model
Bengio et al. (2003) replaced the table with a function that can generalize: if it has seen "the cat sat", it can say something sensible about "the dog sat", because it knows that "cat" and "dog" are similar. The model reads the last tokens and works in four steps:
- Embed. Look up each of the tokens in an embedding table of shape : one vector of numbers per token (section 4).
- Concatenate. Put the vectors side by side, oldest first, into one vector of length .
- Hidden layer. A linear layer followed by tanh: .
- Logits. Another linear layer gives one score per token of the vocabulary: . Softmax turns them into the next-token probabilities.
where:
- is the concatenation of the embeddings of the last tokens;
- and are the weights and biases of the two layers, and is the size of the hidden layer ;
- are the logits, numbers.
Example. tokens of context, embeddings of numbers, a hidden layer of , and .
- Shapes: has numbers, is , is .
- Parameters: million in , about in and , million in and : about million in total.
A table for the same context of 3 tokens would need cells (one row per context of 3 tokens, one column per next token).
The number of parameters grows linearly with instead of exponentially, and similar tokens get similar embeddings, so the model generalizes to contexts it has never seen. It still has a fixed window of tokens; attention (section 7) removes that limit.
From logits to text: sampling
A trained model gives logits for the next token. Turning them into text is a loop: turn the logits into probabilities, choose one token, append it to the text, and ask the model again. How to choose?
- Greedy decoding always picks the most likely token. It is deterministic, and tends to fall into repetitive loops.
- Sampling draws a token at random, each with its probability: a token with probability 0.3 is chosen 30% of the time. Before drawing, the distribution is usually reshaped, in one of the three ways below.
Temperature
Temperature divides the logits by a number before the softmax:
where is the probability of token (here is the temperature, not the length of the text).
- makes the differences between logits bigger, so the distribution is sharper: the favourite token gets even more probability. As it becomes greedy decoding.
- makes the differences smaller, so the distribution is flatter. As it becomes uniform.
- leaves the distribution unchanged.
Example. Logits :
temperature probabilities
Top-k and top-p
Even a good model gives a little probability to thousands of unlikely tokens (the tail of the distribution), and together they add up: sampling picks one of them now and then, and one bad token can derail the rest of the text. The two filters below cut the tail off before sampling.
Top-k sampling (used by Fan et al., 2018, for story generation) keeps only the most likely tokens and renormalizes them so they add up to 1. Its weakness: a fixed is too many when the model is confident, and too few when it is not.
Top-p (nucleus) sampling (Holtzman et al., 2020) keeps the smallest set of most likely tokens whose total probability reaches : a handful of tokens when the distribution is peaked, many when it is flat.
Example. Probabilities .
- Top-k with keeps the first two, and , and renormalizes them by their total : .
- Top-p with adds tokens from the most likely until the total reaches : , then (not yet), then (reached). It keeps three, renormalized by : about .
Holtzman et al. observe that maximizing likelihood at decoding time (greedy or beam search) gives bland, strangely repetitive text, and that the long tail of unlikely tokens is unreliable; sampling only from the "nucleus" avoids both problems.
In practice these filters are applied to the logits, by setting the removed tokens to : since , the same softmax and sampling code then works for all of them.
References
- C. E. Shannon, A Mathematical Theory of Communication, Bell System Technical Journal 27(3), 379–423, 1948. Includes the first n-gram approximations of English text.
- D. Jurafsky, J. H. Martin, Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models. Counting, perplexity and smoothing (section 3.6).
- Y. Bengio, R. Ducharme, P. Vincent, C. Jauvin, A Neural Probabilistic Language Model, JMLR 3, 1137–1155, 2003.
- A. Fan, M. Lewis, Y. Dauphin, Hierarchical Neural Story Generation, ACL, 2018. Top-k sampling.
- A. Holtzman, J. Buys, L. Du, M. Forbes, Y. Choi, The Curious Case of Neural Text Degeneration, ICLR, 2020. Nucleus (top-p) sampling.
- A. Karpathy, makemore: bigram and MLP character-level language models, step by step.