TL;DR
A language model is a probability distribution over sequences of text, split into small pieces called tokens. Because the probability of a whole sequence breaks into a chain of next-token predictions, the model only has to learn one thing: given the text so far, how likely is each possible next token. Trained to get those predictions right on a large amount of text, it can also generate new text by picking one token at a time.
Where you'll see it: the autocomplete on a phone keyboard, the chat assistants and code-completion tools built on large models, and the scoring step that ranks candidate transcriptions in speech recognition.
Intuition
Guessing the next word
Start with autocomplete. You type "the cat sat on the" and the phone offers "mat" or "couch", but not "elephant". Nobody gave it a grammar book. It learned from a large pile of text that after those words some continuations are common and others are rare. A language model is that guesser made precise: for any piece of text, it gives a probability to every possible next token, and those probabilities add up to 1.
Why bother with probabilities over whole texts? Because one object answers many questions. To decide which of two sentences is more natural, compare their probabilities. To produce a continuation, sample from the next-token probabilities. To check whether a speech recogniser's transcript makes sense, score it. Each question becomes arithmetic on the same thing.
The surprising part is how far this goes. Many tasks can be phrased as continuing a text. Translation becomes "Here is an English sentence and its French version:", and the model continues the text. This is why one model trained only on next-token prediction can do so many jobs. The behaviour of doing a new task from examples inside the prompt is called in-context learning.
Predict one token at a time
Predicting a whole sentence in one go is hopeless, because there are far too many possible sentences. Predicting one token given everything before it is a small, fixed kind of problem, and it repeats at every position. Each sentence in the training data supplies many such problems for free. The sentence "the cat sat on the mat" contains six of them, one at each position, and the model learns from all of them.
A token is a word or a piece of a word. Splitting text into tokens is covered in Subword Tokenization. From here on, "token" means one of these units.
Generation is the same prediction used in a loop:
flowchart LR A[Text so far] --> B[Model] B --> C[Probability for every next token] C --> D[Pick one token] D --> A
The model reads the text so far, produces a distribution over the next token, one token is chosen, the choice is appended, and the loop runs again.
The math
Sequences and the chain rule
Let be the finite vocabulary of tokens the model knows. A text is a sequence where each . A language model is a probability distribution over all such sequences.
Writing that joint distribution down directly is intractable. The chain rule of probability fixes this. It says any joint probability is a product of conditional probabilities. For three events, , because by the definition of conditional probability, and the same step applies again to the third event. In general
For the context is empty. This is an exact identity, not an approximation. So a language model is really a model of one thing: the next-token distribution for every possible context.
The model: logits and softmax
We write the model's next-token distribution as , where is the set of learned parameters. A neural model first reads the context into a vector . The architecture that does this can be a recurrent network, a Transformer, or something else. A final linear layer then gives one raw score per vocabulary token, called a logit:
The Softmax turns the logits into probabilities. The probability of token at position is
where is the logit for token and the sum runs over the whole vocabulary. Every output is positive and they sum to 1. Whatever the architecture, the model's output is this one distribution per position.
Training by maximum likelihood
Given a corpus of texts, we choose to make the data as probable as possible. This is maximum likelihood estimation. Under the chain rule, the probability of one text becomes a product, and the Logarithm of a product is a sum, so the log-likelihood is
Maximising this is the same as minimising the average negative log-likelihood, which is the loss we train on:
This is the cross-entropy loss with a one-hot target. At each position the target distribution puts all its weight on the token that actually came next. The cross-entropy then reduces to the negative log of the probability given to that token.
The loss only looks at the probability assigned to the correct token. Confident and right costs almost nothing. Confident and wrong costs a lot.
- loss = -ln p
Perplexity
The average loss is hard to read directly, so it is usually exponentiated into perplexity:
The second form follows from . Perplexity is the geometric mean of the inverse probabilities the model gave to the true tokens. A perplexity of means that, on average, the model is as uncertain as if it were choosing uniformly among equally likely tokens. Lower is better, and a perfect model scores 1.
Generation by sampling
To generate text, start from a prompt, compute the next-token distribution, draw one token from it, append that token, and repeat. Writing for "is drawn from", each step is .
Always taking the single most probable token is possible, but it tends to produce repetitive, dull text. Sampling spreads the choice across plausible tokens. A common control is temperature , which divides the logits before the softmax, so . Small sharpens the distribution toward the most likely token, and large flattens it.
Worked examples
Take the sentence "the cat sat", followed by an end-of-sentence token written EOS. Suppose a very simple model, where each probability depends only on the previous token, gives:
- , the probability that the sentence starts with "the".
- Joint probability by the chain rule: .
- Loss at each of the four positions, which is the negative natural log of each factor: , , , .
- Sum of the losses: . Average over predictions: nats.
- Perplexity: .
Interpretation: on this sentence the model is, on average, about as unsure as a choice among 1.6 equally likely tokens. The weakest prediction is the one after "the", where the model gives "cat" only 0.4.
The context is "the cat". The vocabulary has four tokens: sat, ran, mat, pizza. The network outputs the logits .
- Exponentiate each logit: , , , .
- Sum them: .
- Divide each by the sum: , , , . These add to 1.
- If the true next token is "sat", the loss is nats.
- If the true next token is "pizza", the loss is nats.
Interpretation: the surprising continuation costs about seven times as much as the expected one. A real vocabulary has tens of thousands of tokens, and the same softmax runs over all of them at every position.
Tradeoffs and failure modes
The strength of the approach is that the chain rule makes the problem exact, and one training objective (predict the next token) works on any text, with no labels needed. The weaknesses come from the same place. Predicting likely text is not the same as predicting true or useful text, so fluent falsehoods are a normal failure. Perplexity measures predictability, not meaning. Generation is random unless you fix the sampling, and it is slow because each token needs a full forward pass.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Little training text, many unseen word sequences | Counts are sparse, so unseen sequences get probability zero | A smoothed model, see N-gram Language Model |
| You need a reusable vector for each word | The next-token distribution is not a word representation | [[word-embedding |
| You only need a label, such as "complaint" or "praise" | Generating text is costly and can drift from the label | A classifier trained on that label |
| Dependencies stretch far back in the text | Early context is lost, and cost grows with length | A Transformer with a long context window, or retrieval of relevant text |
| You want to compare two models | Perplexity depends on tokenisation and vocabulary | Compare on the same tokenised text, or on downstream tasks |
| The output must be true | Fluent but false text can get high probability | Add retrieval or checking; do not rely on the language model alone |
History
The idea of predicting the next symbol of text is older than computers. In 1951 Claude Shannon estimated how well people guess the next letter of printed English, to measure how much information the language carries. In the 1970s and 1980s, speech recognition groups, including the group at IBM led by Frederick Jelinek, used n-gram models, which estimate next-word probabilities from counts over large amounts of text, to rank candidate word sequences. Those models were simple but needed huge tables.
In 2003 Yoshua Bengio and colleagues published a neural probabilistic language model. It replaced the counting tables with a neural network that learns a vector for each word. Because similar words get similar vectors, the model could give sensible probabilities to word combinations it had never seen. Recurrent networks and then transformers made the models stronger. The 2017 transformer paper and the GPT-3 paper in 2020 showed that scaling up the same next-token objective produces models that answer questions and follow instructions when prompted. This is why "language model" now usually means a large transformer trained on a very large text corpus.
It caught on because next-token prediction needs no labels. Any text is training data, so the supply of data stopped being the bottleneck.
Check yourself
QuestionWhy can the chain rule represent a distribution over whole sentences using only next-token probabilities, and is anything approximated?Show answer
The chain rule states that a joint probability equals the product of each token's probability given all earlier tokens. So the joint distribution over a sentence is exactly determined by the next-token distribution at every position. Nothing is approximated in the factorisation. Approximations only enter when the model's next-token distributions are themselves estimated, for example by a neural network or by limiting the context length.
QuestionThe model gives probability 0.25 to the correct next token at one position. What is the cross-entropy loss at that position, in nats? If the average loss over a whole text were exactly this value, what would the perplexity be?Show answer
The loss is nats. If the average loss equals this value, the perplexity is . The model is then as uncertain as a uniform choice among four tokens, which matches the probability 0.25 at every position.
QuestionWhat does the softmax guarantee about the numbers it outputs, and why does the language model need that guarantee?Show answer
Softmax guarantees that every output is strictly positive and that the outputs sum to 1 over the vocabulary. The model needs this because it outputs a valid probability distribution for the next token, and both the likelihood and the sampling step depend on that. Without the sum-to-1 property, the log-likelihood and the sampling distribution would not be well defined.
QuestionA team wants to flag customer emails that are complaints. They propose using the language model's perplexity on each email as the signal. Why is that a poor choice, and what would work better?Show answer
Perplexity measures how predictable an email is under the model. It does not measure what the email means. A complaint and a warm thank-you can both be fluent, ordinary English with similar perplexity, so the score cannot separate them. A better approach is a classifier trained on labelled complaint and non-complaint emails, or a language model prompted to answer the question, with its accuracy checked on a labelled sample before it is trusted.