How LLMs are trained: predicting the next token
An LLM is made by practicing one thing a huge number of times: read text from the start and guess the very next token. Change the probability the model gives to each right answer, and watch the number training pushes down (the loss) and the number used to compare models (perplexity) move.
Short answer. The first big round of training (pre-training) is guessing the next token of real text. The right answer is the next token already written in the text, so nobody has to label anything. At each position, the probability p the model gave to the right token becomes a loss −ln p, and training lowers the average of those losses. Put that average under exp and you get perplexity: roughly, "how many tokens is it choosing between at each position?"
| # | Tokens so far → answer | p | −ln p |
|---|---|---|---|
| Average loss | |||
| Perplexity exp(average loss) | |||
Drag a bar up or down, or type in the table (0.01 to 1). This is a small toy version. There is no real model: you set the probabilities by hand, and we pretend the vocabulary (every token the model knows) has only 20 tokens. A real LLM has a much bigger vocabulary, and the model computes the probabilities itself. The tokens here are simply whole words (real splitting is on Tokenization). The orange number under each bar is that position's loss. The purple dashed line is 1/V, what an even guess gives.
Try this. ① With the starting values, the average loss is 1.07 and the perplexity is 2.92. ② Press "Model that guesses evenly (V = 20)". Every bar drops to the purple line (0.05), every −ln p is 3, the average loss is 3, and the perplexity is exactly 20. ③ Go back to "Starting values" and lower position 5, "morning" (0.9), to 0.8: the perplexity only rises to 2.98. Lower position 2, "drank" (0.1), to 0.01 instead: it jumps to 4.28. ④ Raise position 2 to 1 and you get 1.99. Raise every bar to 1: loss 0, perplexity 1.
Definitions
The text below explains with pictures and labs. These are the textbook definitions. x1, …, xN is the sequence of tokens in a text, pt is the probability the model gave to the right token at position t, and ln is the natural log.
- next-token prediction
- The task of giving every token in the vocabulary a probability of being the next token, given the tokens before it. The right answer is the next token that actually appears in the text, and the probability given to that token is pt.
- pre-training
- The first big round of training, which learns next-token prediction from a very large amount of unlabeled text. Nobody marks the answers; they come from the data itself, so it is a kind of self-supervised learning.
- cross-entropy loss
- The average, over all positions, of −ln of the probability given to the right token. It is cross-entropy when there is only one right answer, and it equals the average negative log-likelihood. Pre-training makes this L smaller.
- perplexity
- exp of the average loss L. It equals 1 divided by the geometric mean of the pt, and it is at least 1.
- teacher forcing
- During training, feeding each position the earlier tokens of the real text, not the tokens the model produced. Together with the causal mask, this lets the model compute the next-token predictions for all positions at once.
- supervised fine-tuning (SFT)
- A step that trains a pre-trained model further on pairs of "instruction and good answer" written by people, using the same next-token prediction loss.
1. Pre-training: the text is the answer key
To an LLM, text is a row of tokens (words or pieces of words). Given the tokens so far, the model gives a probability to every token in its vocabulary. After "I drank", maybe "coffee" gets 0.6, "tea" gets 0.2, and so on, adding up to 1. Training adjusts these numbers so that the token that really comes next in the text gets a higher probability.
The key point: nobody labels the answers. The "next token" is already in the text, so a pile of plain, unmarked text (web pages, books, code and so on) is both the questions and the answers. Learning where the data supplies its own answers is called self-supervised learning. This first big round of training is pre-training.
The loss at each position is −ln of the probability p given to the right token. That is the same as cross-entropy when there is exactly one right answer. The other tokens' probabilities do not appear in the loss directly, but the probabilities add up to 1, so raising the right one pushes the rest down.
2. How the formula is built
Change the bars in the lab above and this picture and its numbers change too. The orange highlight in the formula is the piece added in this step.
- The probability of the right token,
pₜ. t is the position number. The starting values are 0.2, 0.1, 0.6, 0.3, 0.9, 0.5. −ln pₜat each position. A sure, right guess (p = 1) gives 0, and the lower the model rated the right token, the bigger it gets. The probability of the whole sentence is all the p's multiplied together. ln turns that product into a sum, so each position adds its own part. The minus sign makes the loss a number of 0 or more.- The average,
L = (1/N) Σ −ln pₜ. N is the number of positions (6 here). An average, not a sum, so texts of different lengths can be compared. Training lowers this L with gradient descent. - Put it under exp:
PPL = exp(L). This undoes the ln and brings the number back to the scale of probabilities.exp(−L)is the geometric mean of the p's, so perplexity is1 ÷ (geometric mean of the p's). A model that gives the right token probability 1/k at every position has perplexity exactly k, so you read perplexity as "like picking evenly among k tokens at each position".
Try this. With the starting values, go to step ④: L = 1.07, the dashed line 1/PPL = 0.34, and PPL = 2.92. While on ④, press "Model that guesses evenly" above: the bars and the dashed line all sit at 0.05 and PPL = 20.
3. Work it out by hand
Follow the math with the lab's starting values. ln is the logarithm with base e (about 2.718).
| # | Tokens so far → answer | p | −ln p |
|---|---|---|---|
| 1 | <start> → I | 0.2 | 1.609 |
| 2 | … I → drank | 0.1 | 2.303 |
| 3 | … drank → coffee | 0.6 | 0.511 |
| 4 | … coffee → this | 0.3 | 1.204 |
| 5 | … this → morning | 0.9 | 0.105 |
| 6 | … morning → . | 0.5 | 0.693 |
| Sum | 6.425 | ||
- Average loss.
6.425 ÷ 6 ≈ 1.071. - Perplexity.
exp(1.071) ≈ 2.92. At each position the model is about as unsure as picking among 3 tokens. - Compare. Guessing evenly over 20 tokens gives
−ln(1/20) = ln 20 ≈ 2.996at every position, an average of 2.996, and a perplexity ofexp(2.996) ≈ 20. The model with the starting values is far less unsure than an even guess.
4. Look only backward, learn every position at once
Training does not feed a sentence in one position at a time. The whole sentence goes in once, and the model guesses the next token at every position at the same time. The input and the answers are the same text, shifted by one.
input: <start> I drank coffee this morning
answer: I drank coffee this morning .
But with everything fed in at once, the "drank" position could just look ahead and copy "coffee". So inside attention, each position may only look at itself and the positions before it. The scores for later positions are set to −∞, so after softmax their weight is 0. This is the causal mask (the decoder in the Transformer).
The input holds the real earlier tokens of the text, not the model's own earlier guesses. This is called teacher forcing. No position has to wait for an earlier guess, so together with the mask, every position can be computed at once. When the trained model writes new text there is no real next text, so it picks one token, adds it to the end of the input, and runs again, over and over.
The same sentence, side by side: during training (left) and when the trained model writes text (right). A pass is one run of the model. Box borders show where a token came from: green the real text, purple a token the model gave, gray the start mark. The orange arrows are the loss at each position. This lab does not run a model. The generated tokens are set in advance too (the same sentence as the lab above).
5. Key properties
| Property | In plain words | In the lab |
|---|---|---|
| Loss is 0 or more, and 0 only at probability 1 | The loss is 0 only when the model is sure and right. Perplexity is then 1 and never goes lower | Raise every bar to 1 |
| Low probabilities make the loss grow fast | −ln is steep near 0. When a probability gets 10 times smaller, that position's loss grows by ln 10 ≈ 2.3 | 0.9 → 0.8 gives 2.92 → 2.98, 0.1 → 0.01 gives 2.92 → 4.28 |
| An even guess has perplexity V | Give each of V tokens the same 1/V and perplexity is exactly V. Rate the right token lower than that and it goes above V | "Model that guesses evenly", bars below the purple line |
| Changing the log base keeps perplexity the same | With a base-2 log, the loss becomes a different number (in bits), but 2 raised to that average gives the same perplexity | |
| Different tokenizers cannot be compared | The same text split a different way has a different number of positions and a different vocabulary, so perplexity means something else |
6. Steps after pre-training
A model with only pre-training is a "continue the text" machine. Asked a question, it may write more questions like it instead of answering. So two more steps usually follow (source: Ouyang et al.).
- Instruction tuning. More of the same next-token guessing, on pairs of an instruction and a good answer written by people.
- Tuning to human preferences. People compare several answers to the same instruction and pick the better ones. Training then raises the probability of answers people preferred. A common way is to train a scoring model on those picks and then adjust the LLM with reinforcement learning (RLHF).
Choosing how to train a model further on your own data (change all of it, or only a small part) is covered on Transfer learning and LoRA.
7. Encoder models and decoder models
- Decoder: guess the next token. The method on this page. It looks only backward and guesses what comes next, so it can keep writing text exactly the way it learned. LLMs that write text are built this way.
- Encoder: guess the hidden word. A few input tokens are replaced with
[MASK]and the model guesses the originals (BERT, see sources). There is no look-ahead mask, so it sees both sides of each hidden spot. That gives a good summary of the whole sentence, used for sorting text into groups and for search. In exchange, it is not suited to writing text one token at a time from the left, and only the hidden spots produce a loss.
8. When to use which
| Training method | Good | Bad | Use it for |
|---|---|---|---|
| Next-token prediction (decoder) | Learns from plain text. Can write text exactly the way it learned. Every position adds to the loss | Each position cannot see what comes after it. Generation is one token at a time, so long outputs take longer | Generation: chat, summaries, translation, writing code |
| Masked token prediction (encoder) | Each token's summary uses context from both sides | Cannot keep writing text. Only the hidden spots add to the loss | Classification: sentiment, topic, finding names in text |
| Contrastive learning | Pulls pairs together (two sentences with the same meaning, a question and its answer) and pushes non-pairs apart, so one vector can measure how similar things are | Needs paired data. Cannot write text | Embeddings: search, finding similar text, grouping (Embeddings) |
Where it is used
- Reading a training curve. Check that the average loss goes down during training. If the loss on held-out validation text starts going up, that is overfitting.
- Comparing models. On the same test text with the same tokenizer, lower perplexity means better next-token guesses.
- Finding surprises. Positions with a large −ln p are tokens the model did not expect.
- Generation. Pick the next token from the learned probabilities, one at a time, to write text (Sampling).
Frequently asked
If nobody labels the answers, how does it learn?
The text is the answer key. Show the model the start of a text and ask for the very next token, and the right token is already written in the text. So it can learn from huge amounts of text that nobody marked up. This is called self-supervised learning.
Is a model with lower perplexity better?
You can only compare numbers measured on the same test text with the same tokenizer. A different way of splitting text into tokens changes the number of tokens and the vocabulary, so the number means something else. Perplexity also only tells you how well the model guesses the next token. Whether it follows instructions or tells the truth has to be tested separately.
Does training run the model once per token?
No. The whole sentence goes in once and the model guesses the next token at every position at the same time. The mask stops each position from seeing the tokens after it, so it cannot peek at the answer. Only when it writes new text (generation) does it produce one token at a time.
Words
| Plain words used here | What books call it |
|---|---|
| The first big round of training | Pre-training |
| Guessing the next token | Next-token prediction, causal language modeling, autoregressive model |
| The text is the answer key | Self-supervised learning |
| Every token the model knows | Vocabulary, size V |
| −ln of the probability given to the right token | Negative log-likelihood (NLL), cross-entropy |
| How many tokens it is choosing between | Perplexity (PPL) |
| Look only backward | Causal mask |
| Feed in the real earlier tokens | Teacher forcing |
| Guess the hidden word | Masked language modeling (MLM) |
| Instruction tuning | Instruction tuning, supervised fine-tuning (SFT) |
| Tuning to human preferences | Reinforcement learning from human feedback (RLHF) |
| Pull pairs together, push others apart | Contrastive learning |
Sources
- Ashish Vaswani et al., Attention Is All You Need, arXiv:1706.03762. The decoder mask that sets later positions to −∞.
- Jacob Devlin et al., BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, arXiv:1810.04805. Masked token prediction and context from both sides.
- Long Ouyang et al., Training language models to follow instructions with human feedback, arXiv:2203.02155. Instruction tuning and tuning to human preferences.
- Dan Jurafsky, James H. Martin, Speech and Language Processing (3rd edition draft). Perplexity of language models, teacher forcing.
← Embedding models: one vector per sentenceSoftmax and sampling →