how does a gpt learn ?
begin with one unfinished sentence
Consider the short unfinished sentence
It looks simple to us because we read it almost in a single go. A language model does not begin with that understanding. It does not receive the sentence as meaning; it receives a sequence of token IDs.
A tokenizer first breaks the text into tokens and maps each token to an integer. The model then turns those integers into vectors, lets the vectors exchange information under a rule that hides the future, and asks the same question at every position:
That one question connects the forward pass, the loss, backpropagation, and text generation. The aim of this blog is to follow that thread from beginning to end.
We will use a deliberately small example so that every object, equation, and shape remains visible.
build a tiny vocabulary
Assume the vocabulary contains the following seven tokens:
A vocabulary is like a dictionary: it maps each token to a unique integer ID. For this example, let
The vocabulary size is therefore
The IDs are only labels. Token ID (2) is not mathematically closer to token ID (3) than it is to token ID (6). The model must learn useful vector representations for these IDs.
For the main example, let the model dimension be
This means that the model represents every token position using a vector with four real-valued components.
Real language models use much larger vocabularies, sequence lengths, and model dimensions, but the same equations and tensor shapes still apply.
one sentence creates five prediction positions
Suppose the training text contains
Using our token-ID map, the sentence becomes
The sentence contains six tokens:
To create a next-token target, every input position needs a token immediately after it. The final token has no later token inside this six-token example, so the six tokens create five prediction positions:
The input sequence contains the first five tokens, and the target sequence contains the final five tokens:
More precisely,
where
For this example,
At position , the target is the token one position to the right:
where denotes the original six-token sequence. Equivalently,
The text creates its own labels. No separate answer file is required: the token after each prefix becomes the correct target for that prefix.
In words, the five training relationships are
Using token IDs, the same relationships are
These are not five independent word-pair examples. They are five causal views of one sequence.
pass the whole sequence through the model at once
During training, the entire input sequence
is passed through the Transformer in one forward pass.
The model is causal, so the representation at each position may use only that position and the positions before it. It may not use any future position. The whole sequence is physically present in the input matrix, but every row has a different visibility pattern.
A simple binary visibility matrix makes this clear:
Here,
A means that position is allowed to use position (j), while a means that position is hidden from it.
With token labels and targets attached, the same structure is
The first output position can use only the and predicts cat. The second can use the cat and predicts sat. The final position can use the full input prefix the cat sat on the and predicts mat.
The model therefore performs all five prefix predictions together:
The matrix (C) is only a conceptual visibility matrix. The actual Transformer uses an additive causal mask inside attention, which we will write explicitly later.
turn token ids into vectors
The model cannot do useful geometry directly with arbitrary integer IDs, so it stores a learned embedding matrix
With (V=7) and (d=4),
Each row belongs to one vocabulary token, and each row contains four learned real numbers. For illustration, imagine
These numbers are illustrative. In a real model, they are learned during training.
Looking up the rows indexed by
gives
Its shape is
There is one row for every token position and one column for every learned feature. The rows have not been merged into one sentence vector. The model carries all five positions at the same time.
The token the occurs twice, so its raw token-embedding row appears twice. The model must still distinguish the first occurrence from the second. Position information is therefore added or otherwise introduced.
In a simple additive description,
where
Because both matrices have the same shape,
and therefore
Position information changes the values, not the shape. Modern models may use learned positions, sinusoidal positions, rotary position embeddings, or relative-position methods. The central fact remains the same: there is one -dimensional state for each of the (N) positions.
one sequence, many changing viewpoints
The hidden-state shape stays the same through the Transformer.
If enters block , then the block returns another matrix with the same shape:
A common pre-normalization block can be written schematically as
Exact normalization details vary across architectures, but every residual addition requires matching shapes. Both the attention branch and the feature-processing branch therefore return matrices.
If the shape does not change, what does change?
The meaning carried by each row changes.
At the beginning, a row mostly represents one token at one position. After many Transformer blocks, the same row can represent that token together with information gathered from its permitted prefix.
After blocks, let
Conceptually, the rows are allowed to encode
The vectors do not literally contain those strings. This notation describes the information each row is permitted to depend on.
how the future stays hidden
If all five positions are present in the same matrix, why can the row for cat not look ahead and copy information from sat?
This is the purpose of causal self-attention.
For one attention head, start with
The model forms queries, keys, and values:
where
The symbol (V_{!a}) denotes the attention-value matrix. It is different from the vocabulary size (V).
The projected matrices have shape
A useful interpretation is
- each query row describes what the current position is looking for;
- each key row describes what a position can be matched by;
- each value row contains the information that position can contribute.
All pairwise attention scores are computed together:
The shape calculation is
so
Entry (S_{t,j}) measures how strongly position (t) matches position (j) before masking and normalization.
The additive causal mask is
For five positions,
The attention weights are computed row by row:
Because
every forbidden future position receives exactly zero attention weight. The resulting pattern is
where every (*) is a nonnegative value and every row sums to (1).
The attention output is
For row (t),
The upper limit is (t), not (N). Future positions do not appear in the sum. This is the precise mathematical statement that the future is hidden.
The sequence length does not grow inside the forward pass. The model already has a fixed (N\times N) attention grid. What changes from row to row is the amount of context that is visible.
In short,
Real Transformers use multiple heads, allowing different relationships to be represented in parallel. After the heads are joined and projected, the output returns to shape (N\times d).
from hidden states to next-token probabilities
After the final Transformer block, we have
Each row must now become a score for every vocabulary token. The model uses an output projection
and usually a bias
For each position,
Applying the same projection to all rows gives
where the bias is broadcast across the (N) rows.
The shape calculation is
With (N=5), (d=4), and (V=7),
so
There are five input positions, and every position receives seven vocabulary scores.
Suppose the logits are
with columns ordered as
A logit is an unrestricted real-valued score. Softmax converts each row into a probability distribution:
Softmax is applied separately to every row, so
For the logits above, the approximate probability matrix is
The bold entries are the probabilities assigned to the correct next tokens:
The network has produced five different next-token distributions in one pass. Row (1) answers “what follows the?” Row (5) answers “what follows the cat sat on the?”
During generation, only the newest row is needed. During training, every row has a known target, so every row can contribute to the loss.
why cross-entropy is the right loss
At position (t), let
be the model's predicted distribution over the vocabulary.
Let (y_t) be the correct token ID, and let (q_t) be its one-hot target distribution:
The categorical cross-entropy is
Because every incorrect entry of (q_t) is zero, all terms disappear except the correct one:
This gives a simple interpretation:
A high probability for the correct token gives a small loss:
A low probability gives a large loss:
Some reference values make the scale intuitive:
The function (-\log p) decreases continuously as (p) increases. Therefore, for a one-hot target, minimizing cross-entropy is exactly the same as pushing the probability of the correct token upward.
There is also a sequence-level reason for the logarithm.
The causal model assigns the correct continuation the probability
This is the chain rule of probability. The capital pi notation is a compact way to write the same product. If the original sequence is
then
Here,
Taking the negative logarithm turns the product into a sum:
Therefore,
This is the key intuitive proof.
The model is not being trained on unrelated word pairs. Maximizing the probability of the entire correct continuation is equivalent to minimizing the sum of its next-token cross-entropies.
The mean training loss is usually
Dividing by (N) changes the scale but not the best model parameters for a fixed sequence length. It also makes losses and gradient magnitudes more comparable across examples containing different numbers of valid target tokens.
For the five correct probabilities above,
The per-token loss vector is
The mean is
The product of the five correct probabilities is approximately
and indeed,
Dividing by five gives the same mean:
For a more general target distribution (q), cross-entropy also has the identity
Because
cross-entropy is minimized when the predicted distribution (p) matches the target distribution (q). For ordinary next-token training, (q) is one-hot, so this reduces to assigning as much probability as possible to the correct token.
In practice, software computes cross-entropy directly from logits using a numerically stable log-softmax operation:
This is algebraically equal to (-\log p_{t,y_t}), but it avoids numerical problems caused by explicitly exponentiating very large or very small values.
how one scalar changes every weight
The scalar loss was produced through a chain of differentiable operations:
Every learnable parameter that influenced the logits also influenced the loss. Autograd records these operations and applies the chain rule backward through the graph.
For a parameter (\theta_i), the gradient
answers the local question
Softmax cross-entropy has a particularly clear gradient. If (e_{y_t}) is the one-hot vector for the correct token, then
For the correct token,
which is negative unless the correct probability is already (1). Gradient descent subtracts the gradient, so it tends to increase the correct token's logit.
For an incorrect token (v),
Gradient descent therefore tends to decrease that incorrect logit. An incorrect token that received more probability receives a stronger downward correction.
All positions use the same model parameters. If
then differentiation is linear:
This is why the model does not need one backward pass per token. We compute all token losses, reduce them to one scalar, and call backward once. The resulting gradient already contains the contribution from every supervised position.
A basic gradient-descent update is
where (\eta) is the learning rate.
Modern optimizers such as Adam use additional state and rescaling, but the central action is the same: change the parameters in a direction expected to reduce future loss.
One training step is therefore
Repeated over many sequences, this process changes the embedding table, attention projections, MLP weights, normalization parameters, and output projection so that correct continuations receive more probability.
why training is parallel but generation is sequential
Training and generation use the same causal next-token model, but they use its output differently.
during training
The correct continuation is already known.
For the input
the shifted target is
The causal mask prevents each row from seeing future input tokens, while the target sequence provides the correct answer for every output row. All five positions can therefore be trained together:
This is commonly called teacher forcing: every position receives the true earlier tokens from the dataset rather than earlier tokens sampled from the model.
during generation
Suppose the prompt is
A forward pass produces one logit row per prompt position:
The first row predicts what follows the, but the prompt already contains cat. Only the final row predicts the next unseen token. Generation therefore uses
The next token may be chosen greedily,
or sampled from a temperature-scaled distribution,
where is the temperature.
If the model chooses sat, it appends that token:
The process then repeats:
Generation is sequential because the next prediction depends on the token just generated:
Before exists, it cannot be part of the context used to produce .
A key-value cache can reuse attention keys and values computed for earlier tokens, making generation much faster. It does not remove the one-new-token-at-a-time dependency.
beginning and end tokens
The main example treats the first the as given context and predicts the five tokens after it.
To assign a probability to the first token too, place before the sentence. To teach the model when to stop, place after it:
Then the input and target could be
This version has seven prediction positions. It includes both
and
The earlier example is still correct; it simply studies the continuation after the initial the and stops at mat.
attention masks and loss masks are different
A causal attention mask answers
A loss mask answers
These are different operations.
For ordinary language-model pretraining, most real token positions contribute to the loss. Padding positions are normally excluded.
In supervised fine-tuning, the entire prompt and response may enter the model, while only response positions contribute directly to the loss. If marks supervised positions, then
A prompt token with is still present and can influence later answer states through attention. It is merely excluded from the final loss average.
the whole picture without the clutter
For one sequence, the complete path is
followed by
With a batch of sequences, a head count of , and a common stored sequence length ,
If marks valid supervised targets, the batch loss is
The central facts are now compact:
The model keeps one hidden row per token position:
The whole input is processed at once, but causal masking hides future columns from every row:
Every final hidden row becomes a complete vocabulary distribution:
The target sequence is the original sequence shifted by one token:
Token cross-entropies are the additive pieces of one continuation-level negative log-probability:
- One backward pass includes the learning signal from every supervised position:
- Training uses every valid output row because every target is known. Generation uses the newest row because only the next unseen token matters.
As one story, the process is very orderly. The model keeps one evolving vector for every position. Each vector may gather information only from its past. Each final vector proposes a distribution over what should come next. The correct next tokens are scored with cross-entropy, the token losses become one scalar, and that scalar sends a learning signal backward through the entire network.