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 → answerp−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.

pt=P(xt∣x1,…,xt−1)

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.

L=−1N∑t=1Nlnpt

perplexity
exp of the average loss L. It equals 1 divided by the geometric mean of the pt, and it is at least 1.

PPL=exp(L)=exp(−1N∑t=1Nlnpt)

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.

  1. 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.
  2. −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.
  3. 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.
  4. 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 is 1 ÷ (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 → answerp−ln p
1<start> → I0.21.609
2… I → drank0.12.303
3… drank → coffee0.60.511
4… coffee → this0.31.204
5… this → morning0.90.105
6… morning → .0.50.693
Sum6.425
  1. Average loss. 6.425 ÷ 6 ≈ 1.071.
  2. Perplexity. exp(1.071) ≈ 2.92. At each position the model is about as unsure as picking among 3 tokens.
  3. Compare. Guessing evenly over 20 tokens gives −ln(1/20) = ln 20 ≈ 2.996 at every position, an average of 2.996, and a perplexity of exp(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

PropertyIn plain wordsIn the lab
Loss is 0 or more, and 0 only at probability 1The loss is 0 only when the model is sure and right. Perplexity is then 1 and never goes lowerRaise 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.30.9 → 0.8 gives 2.92 → 2.98, 0.1 → 0.01 gives 2.92 → 4.28
An even guess has perplexity VGive 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 sameWith 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 comparedThe 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.).

Tuning to human preferences (RLHF) ① Instruction tuning goes in instruction–answer pairs changes the model's weights ② People pick answers goes in several answers changes nothing (picks are kept) ③ Scoring model goes in the people's picks changes the scoring model ④ Adjust with RL goes in scoring model's scores changes the model's weights
Steps after pre-training. In each box, the top line is the data that goes in and the bottom line is what changes in that step. ②–④ are tuning to human preferences (RLHF). In ③ what changes is not the LLM but a separate scoring model. Only the steps written above are drawn.

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

8. When to use which

Training methodGoodBadUse it for
Next-token prediction (decoder)Learns from plain text. Can write text exactly the way it learned. Every position adds to the lossEach position cannot see what comes after it. Generation is one token at a time, so long outputs take longerGeneration: chat, summaries, translation, writing code
Masked token prediction (encoder)Each token's summary uses context from both sidesCannot keep writing text. Only the hidden spots add to the lossClassification: sentiment, topic, finding names in text
Contrastive learningPulls 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 areNeeds paired data. Cannot write textEmbeddings: search, finding similar text, grouping (Embeddings)

Where it is used

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 hereWhat books call it
The first big round of trainingPre-training
Guessing the next tokenNext-token prediction, causal language modeling, autoregressive model
The text is the answer keySelf-supervised learning
Every token the model knowsVocabulary, size V
−ln of the probability given to the right tokenNegative log-likelihood (NLL), cross-entropy
How many tokens it is choosing betweenPerplexity (PPL)
Look only backwardCausal mask
Feed in the real earlier tokensTeacher forcing
Guess the hidden wordMasked language modeling (MLM)
Instruction tuningInstruction tuning, supervised fine-tuning (SFT)
Tuning to human preferencesReinforcement learning from human feedback (RLHF)
Pull pairs together, push others apartContrastive learning

Sources

← Embedding models: one vector per sentenceSoftmax and sampling →