Next-Token Prediction
Text already contains examples of what follows what, giving us a training task without asking someone to label every sentence. A next-token model learns to predict each continuation using only the text available before it.
10 sections · 9 questions · 4 coding challenges
The arrow keys move between sections too.
Could Predicting the Next Symbol Teach Us About Language?
BOTIE
In his 1948 work on communication, Claude Shannon illustrated statistical approximations to English using progressively more structure in symbol and word sequences. This was not a modern language model, but it established a useful perspective: language can be studied through conditional probabilities and the uncertainty remaining about what comes next.
A next-token model turns that perspective into a training task. The earlier tokens are the input, and the following token supplies an observed target. Text therefore supplies many examples without someone labelling each sentence by hand. Predicting the target well requires useful regularities, but it does not by itself guarantee that a generated statement is true or that the model will follow an instruction.
Sources for this history
What Is a Language Model Actually Learning to Predict?
If we read The cat sat on the, we can suggest several words that might come next. We use the words already present to decide which continuations make sense. A language model turns that kind of continuation task into a numerical prediction.
We need three things: the text the model is allowed to read, a set of possible next tokens, and a way to compare its prediction with the token that actually followed. Repeated over many examples, that comparison provides a training signal.
Hide the continuation we want to predict
Start with a piece of existing text. Show the model a prefix and reserve the following token as the target. We do not need a person to label each next word; its position in the original text supplies the target.
Visible prefix
- the
- cat
Hidden next token
- sat
The loss makes a continuation task trainable
We will calculate the probability and loss at each target, then separate training from generating new text.
A large language model extends this setup with many parameters, many examples, and substantial computation. Those resources do not change what the next-token target means.
Explore the full example
Raise the assigned target logit while the other six vocabulary scores stay at zero. Compare the target probability, its negative log probability, and the derivative that would guide an update.
Calculating the example…
Part 1. Make Training Examples From Text
1. Turn a sequence into inputs and targets
A model learns from pairs, an input and the answer it should have given. For most tasks somebody has to write the answers. Text is unusual because it already contains them. Cover the last token of any stretch of text, and the covered token is the answer to the question of what comes next.
Before anything can be calculated, the text has to become numbers. This page’s vocabulary holds seven entries, <start>, the, cat, dog, sat, slept and <end>, numbered 0 to 6 in that order. The word the is token 1, cat is token 2, sat is token 4 and <end> is token 6.
A token ID identifies an entry in the vocabulary. An embedding gives that ID a vector; a transformer processes the vectors using available context. A final projection produces one logit, or unnormalized score, per vocabulary entry.
The training target at each position is the following token in the original text. The example uses explicit start and end tokens to show the boundaries. Real training pipelines also need policies for document boundaries, sequence packing, padding, and truncation.
Original sequence: <start> the cat sat <end>
Input positions: <start> the cat sat
Target positions: the cat sat <end>Read the two lower rows as columns and each column is one training example. At a given position the model may read every input token up to and including that column, and its target is the token written directly below.
| position | what the model may read | target | target ID |
|---|---|---|---|
| 1 | <start> | the | 1 |
| 2 | <start> the | cat | 2 |
| 3 | <start> the cat | sat | 4 |
| 4 | <start> the cat sat | <end> | 6 |
Five tokens give four examples. The start token is never a target, because nothing comes before it, and the end token is never an input, because nothing follows it.
Two things about this table matter for the rest of the lesson. A target never appears in its own input, so the model cannot answer by copying. And dog and slept are in the vocabulary without being in the sentence. The model still has to score them at every position, which is why each prediction is a row of seven scores and not a single yes or no about the target.
2. Learn from a target without claiming it is the only valid continuation
The target is the continuation that appeared in this example. Another example can have the same prefix and a different next token. Across data, the model is encouraged to assign probability according to the continuations it observes.
Suppose the data holds the cat sat in one example and the cat slept in another. After the cat, the first example says the answer was sat and the second says it was slept. A prediction that puts everything on sat is right about the first example and badly wrong about the second. A prediction that shares between sat and slept is partly right about both. Step 4 puts numbers on the two predictions, and the sharing one comes out well ahead. That is the sense in which the model is fitting the proportions in its data, and it is why the output is a distribution over the vocabulary and not one chosen token.
This is called self-supervised learning because the text supplies the target without a person labeling each position. It still uses a precise training target and a loss. Data selection, duplication, and coverage influence what the model learns.
The table in step 1 shows how little the supervision asks of anybody. It was produced by shifting the sentence one place. Nobody decided what the right continuation ought to be, which also means that whatever the text contains, mistakes and repetitions included, becomes a target.
Part 2. From Scores to a Training Signal
3. Calculate the probability of the observed token
Softmax exponentiates each logit and divides by the sum across the vocabulary. For the default table, the observed target has an assigned logit of one and all six alternatives have a logit of zero.
Target weight = exp(1)
Each alternative weight = exp(0) = 1
Total weight = exp(1) + 6
Target probability = exp(1) / (exp(1) + 6)
Token loss = −ln(Target probability)The default table, evaluated
The target weight exp(1) is about 2.7183, and the six alternatives contribute one each.
Target probability = 2.7183 / (2.7183 + 6) ≈ 0.3118
Each alternative = 1 / 8.7183 ≈ 0.1147
Token loss = −ln(0.3118) ≈ 1.1654Every scored position in the default table has the same assigned scores, so each shows the same probability and the same loss, and the mean scored token loss is 1.1654 as well. The slider moves the target logit while the alternatives stay at zero.
| assigned target logit | target probability | token loss |
|---|---|---|
| 0 | 0.1429 | 1.9459 |
| 1 | 0.3118 | 1.1654 |
| 2 | 0.5519 | 0.5944 |
| 4 | 0.9010 | 0.1043 |
At a logit of zero all seven entries tie at one seventh and the loss is ln 7. Raising the target logit raises its probability and lowers the loss, and the loss never reaches zero, because the alternatives keep a positive share.
The negative natural logarithm gives a small loss when the target is likely and a large loss when it is unlikely. This does not evaluate whether the sentence is true. It measures how well the distribution predicts the observed text.
4. Average over positions and differentiate
Let p be a vocabulary probability, y the target ID, and N the number of scored positions. The average loss gives each scored position equal weight. The derivative below applies to a logit at one scored position.
L = −(1 / N) Σₜ ln pₜ(yₜ)
∂L / ∂logitₜ,ⱼ = (pₜ(j) − 1[j = yₜ]) / NFor the target, the derivative is negative unless its probability is already one. Gradient descent therefore increases that score locally. In a real network, backpropagation carries this derivative through the vocabulary projection, transformer blocks, and embeddings. Shared parameters couple the effects across examples.
The derivative on the default table
The default table scores four positions, so N is four. At every position the target has a probability of 0.3118 and each of the six alternatives has 0.1147.
Target logit: (0.3118 − 1) / 4 ≈ −0.1721
Each alternative: (0.1147 − 0) / 4 ≈ 0.0287
Sum over the row: −0.1721 + (6 × 0.0287) ≈ 0The probabilities shown are rounded and the derivatives were calculated from the unrounded ones. A descent step moves each score against its derivative. The target’s derivative is negative, so the step raises the target score, and each alternative’s derivative is positive, so the same step lowers it. The seven derivatives in a row sum to zero because the seven probabilities sum to one, so whatever the target gains the alternatives give up between them.
| assigned target logit | target probability | derivative at the target logit |
|---|---|---|
| 0 | 0.1429 | −0.2143 |
| 1 | 0.3118 | −0.1721 |
| 2 | 0.5519 | −0.1120 |
| 4 | 0.9010 | −0.0248 |
The derivative shrinks toward zero as the target becomes likely. A position the model already predicts well asks for almost no change, and a position it predicts badly asks for the most.
Averaging over two continuations of one prefix
Return to the two examples from step 2, where the cat is followed by sat once and by slept once. That is two scored positions with the same prefix and different targets, and the average gives them equal weight. Compare a prediction that commits, with a logit of four on sat and zero on the other six entries, with a prediction that shares, with a logit of four on both sat and slept and zero on the other five.
| prediction | probability of sat | probability of slept | loss when sat followed | loss when slept followed | mean loss |
|---|---|---|---|---|---|
| commits to sat | 0.9010 | 0.0165 | 0.1043 | 4.1043 | 2.1043 |
| shares between the two | 0.4781 | 0.4781 | 0.7379 | 0.7379 | 0.7379 |
The same row of scores is used for both examples, because the model reads the same prefix in each.
Committing is cheap when it is right and very expensive when it is wrong, and over the two examples it averages 2.1043 against 0.7379 for sharing. The average loss therefore pulls the prediction toward the proportions in the data. No row of scores can do better on these two examples than a half each, which would cost 0.6931 on both.
Check yourself
Questions on Parts 1 and 2
Question 1 of 5
In the sequence start, the, cat, sat, end, what is the target at the position holding sat?
Part 3. What Changes When the Model Is Large?
5. Separate the objective from the scale
A large language model has a large learned parameter set and is trained on substantial language data. There is no universal parameter count at which a model becomes large. The next-token objective stays the same while model capacity, context length, data, and optimization become major design choices.
What stays the same is everything Part 2 calculated. Each position still gets one score per vocabulary entry, softmax still turns the scores into shares, and the loss is still the negative logarithm of the share given to the token that followed. What changes is where the scores come from. In the table on this page they were assigned, one number per cell, and each could be moved without disturbing the others. In a model they are computed from parameters, and the same parameters produce the scores at every position of every example.
The same loss on scores a network produced
The transformer block lesson built a small decoder whose parameters are fixed random values. Give it the four input tokens <start>, the, cat and sat and it returns seven scores at each position. Those rows can be scored against the same four targets exactly as the assigned table was.
| what the model may read | target | target probability | token loss |
|---|---|---|---|
| <start> | the | 0.0988 | 2.3145 |
| <start> the | cat | 0.2438 | 1.4114 |
| <start> the cat | sat | 0.0395 | 3.2310 |
| <start> the cat sat | <end> | 0.0588 | 2.8330 |
The mean scored token loss is 2.4475. Seven equal scores would cost 1.9459 at every position.
The untrained decoder does worse than a prediction that knows nothing. Its random parameters produce uneven scores, and the larger ones land on the wrong tokens. At the first position it gives sat a probability of 0.4586 when the token that followed was the. Nothing is broken here. This is a model before the objective has been used on it, and training is the work of bringing 2.4475 down.
Pretraining supplies broad statistical patterns. It does not automatically turn a continuation model into a reliable assistant. Supervised fine-tuning can teach response behavior; retrieval can provide source material at answer time. Neither makes evaluation unnecessary.
Keep in mind
A loss is read against the vocabulary it was measured over. Equal scores cost the logarithm of the vocabulary size at every position, which is ln 7, about 1.9459, for the seven entries here, and that starting point rises as the vocabulary grows. A loss of 1.9459 means knowing nothing over seven entries, and the same value over a larger vocabulary would mean the model had learned something.
6. Inspect the objective directly
The SDK example keeps the scores explicit. It calculates the mean loss, individual token losses, probability rows, and exact logit derivatives without fitting a language model.
import numpy as np
from oop_ml.numpy.modern import TokenCrossEntropy
logits = np.array([[1.0, 0.0, 0.0]])
targets = np.array([0])
result = TokenCrossEntropy().measure(logits, targets)
print(result.value)
print(result.gradient)During training, earlier input tokens come from the training sequence, so causal positions can be processed together. During generation, the model must use its own selected tokens as the growing context. That difference is the subject of the next lesson.
The first of those claims can be checked on the small decoder. One pass over the four input tokens returns four rows of scores. Running the decoder again on only the first three tokens gives a last row that agrees with the third row of the full pass, and the same holds for the other prefix lengths, to within rounding in the sixteenth decimal place. A position’s scores depend only on the tokens at or before it. So one pass over a training sequence does the work of four separate predictions, and the loss at every position can be calculated from that single pass.
The GPT-3 paper provides a concrete example of a large autoregressive language model and distinguishes prompting from gradient-based fine-tuning. Language Models are Few-Shot Learners.
Continue with Autoregressive Generation.
Check yourself
Questions on Part 3
Question 1 of 4
There is a parameter count above which a model counts as large.
Try it with Botie
Build with Botie
Write and run Python