First Principles of LLMs & RL · Article 08 · Previous article
Writing note: ChatGPT assisted with drafting, editing, translation, mathematical checks, and the original figure and animation sources. The numerical examples are constructed for this explanation.
In the previous article, we followed the vector at one position through attention, residual connections, and the FFN. Its numbers changed as it passed through the layers. At the end of the last layer, the model still had a vector.
Where do the words come from?
Suppose we give the model this input:
Please pass the
We expect it to continue, perhaps with salt. The network has produced a list of numbers. An output layer must use those numbers to score candidate tokens, then a selection rule must choose what comes next.
After choosing salt, the model needs to continue. Its input is now Please pass the salt. The first three words are still there, unchanged. Do we need to repeat all the calculations we just did for them?
We will follow those two steps: first produce a new token, then work out what the next round needs to compute.
1. From the final vector to the next token
Start with the position occupied by the.
After passing through all the Transformer blocks, the vector at this position has been influenced by Please pass. A complete model will usually apply one final normalization as well. Let h denote the vector ultimately passed to the output layer.
h belongs to the position of the, but it predicts the token that follows. When training this kind of continuation model, the prediction at a position is compared with the actual next token. When continuing a prompt, we need the prediction from its last position.
The output layer is also called the language model head, or LM head. Its task is specific: compute one score for each token in the vocabulary. In the output layer used here, there is no bias. Each candidate has a weight vector, and its dot product with h gives that candidate’s score. Placing these weight vectors in rows gives the output matrix.1
To make the calculation small enough to do by hand, use a vocabulary of just seven tokens:
Please, pass, the, salt, sugar, water, and ..
In this teaching example, each word and the period are separate tokens. We supply the output weights and the two final vectors below to illustrate the calculation. They are not measurements from a trained model.
Suppose the vector arriving at the output layer in the first round is:
\[h=\begin{bmatrix}1\\1\end{bmatrix}.\]Set the weights for salt to [1, 1]. Its score is:
Set the weights for water to [0, 0], giving a score of 0. Each other candidate uses its own weights in the same way. The full matrix is in the mathematical notes; here are the results:
| Candidate token | Score, also called a logit | Probability after Softmax |
|---|---|---|
Please | −2 | 1.14% |
pass | −2 | 1.14% |
the | −2 | 1.14% |
salt | 2 | 62.19% |
sugar | 1 | 22.88% |
water | 0 | 8.42% |
. | −1 | 3.10% |
Rounding can make the displayed probabilities sum to slightly more or less than 100%.
Scores can be negative, and they do not need to sum to 1. Softmax, which we met earlier in the series, turns these seven scores into seven probabilities: exponentiate each score, then divide by the sum of those exponentials. For example:
\[p(\text{salt}\mid\text{Please pass the}) =\frac{e^2}{3e^{-2}+e^2+e^1+e^0+e^{-1}} \approx0.6219.\]We now have a distribution. To produce text, we still need a rule for choosing a token.
Here we use the simplest rule, greedy decoding: choose the token with the highest probability at each step. The first choice is therefore salt. We could also sample from the distribution, giving candidates such as sugar a chance to be chosen. The model supplies the distribution; the generation procedure determines how to choose from it.
One distinction matters: 62.19% is the conditional probability the model assigns to salt given this prefix. It is not a 62.19% probability that the sentence is factually correct, nor a confidence score for a factual claim.
2. First process the three positions we already have
We started with the final vector h. Now go back and see how it is obtained.
The input tokens Please, pass, and the are all already known. The model obtains their initial representations and passes the three positions through its Transformer blocks. Position information enters the calculation in the way chosen by the model’s architecture.
This article uses causal attention: a position may read itself and earlier input positions, but not later ones.2
| Position | Input token | Positions this layer’s attention may read |
|---|---|---|
| 1 | Please | Please |
| 2 | pass | Please, pass |
| 3 | the | Please, pass, the |
This table describes what each position may read. It does not require the first position to finish its output before the second position begins computing within the same layer.
Attention within a layer reads the representations at that layer’s input. All three input representations are ready when the layer starts. Their Q, K, and V vectors can therefore be computed together, and each position can read from its allowed range. Position 2 does not need to wait for position 1 to finish its update in this layer.
Once this layer finishes, its updated representations enter the next layer. Positions can be processed together within a layer; the layers still depend on one another in sequence.
Figure 1: Read downward to follow the layers in sequence. Across a row, the three positions can be computed together. The connections show which positions attention may read; residual connections and the position-wise FFN are not drawn separately.
This pass through the known input prefix is called prefill. It prepares the model to generate a continuation. When using a KV cache, it also builds the prefix’s caches at each layer.
Mathematically, we could apply the output layer at every position after processing the prefix. But each position predicts the token that follows it. To continue the current sentence, we need only the distribution from the last position, occupied by the.
The user has already supplied pass and the. We do not need to replace them with predictions from earlier positions. Continuation begins at the end of the input.
Thus, the distribution for the first new token comes from the last position of prefill. That is the distribution we used to choose salt in the previous section.
3. Feed the chosen token back in
After choosing salt, the text is:
Please pass the salt
Only now does salt become the fourth input position. The model must obtain its initial representation, assign it the correct position, and pass it through the network to produce a final vector for predicting what follows.
Choosing salt and processing salt happen at different times. The first round predicts salt at the the position. The next round processes the new salt position.
To work through that second step, we supply the following final vector for position 4 in the same teaching example:
\[h'=\begin{bmatrix}-1\\1\end{bmatrix}.\]The output matrix stays the same. The weights for the period are [−2, 1], so its new score is:
salt still uses [1, 1], but its score is now 0. Applying Softmax over the same vocabulary gives the period a probability of about 87.87%, the highest of the seven. Greedy decoding therefore chooses the period.
We stop this demonstration at the period. Actual generation could continue: stopping depends on an end marker, or EOS token, a length limit, or another stopping condition. A period does not automatically end generation.
Choose a token, append it to the existing prefix, and predict the next one: this is the token-by-token decoding discussed here. GPT-2’s original generation code contains the same loop of taking the prediction from the last position, selecting a token, and feeding it into the next step.3
This also explains a difference between prefill and ordinary token-by-token decoding. All the tokens in the input prefix are known at the start. Future generated tokens have not yet been chosen. To make the next prediction conditional on salt, we first need to choose salt in the current step.
The model’s parameters stay fixed during these inference steps. What changes is the input prefix, along with the representations and probabilities computed from it.
A direct implementation would run the entire network on Please pass the, choose salt, and then run the entire network again on Please pass the salt.
This produces the second prediction. But it computes the first three positions again.
4. Keep the calculations that are still valid
Start with layer 1.
Before we append salt, the can read Please, pass, and itself. After we append salt, the causal mask still prevents the from reading position 4.
The three inputs it may read have not changed. Their positions and the model’s parameters have not changed either. With a deterministic network forward pass, the result at the in layer 1 therefore stays the same.
The same holds for Please and pass: the new token appears after them, outside the range they may read.
What about layer 2? Its inputs already contain context processed by layer 1. Does that make recomputation necessary?
Follow the dependencies again. When layer 2 processes the old positions, it reads the corresponding results from layer 1. We have just established that these results have not changed. The old positions in layer 2 still cannot read the later salt position, so their results also stay the same.
The argument repeats through the layers. The FFN and RMSNorm from the previous article act separately at each position, and residual addition also happens within one position. They introduce no extra path for information from a future position to travel backward.
Under these conditions, appending a token does not change the representations already computed for old positions at any layer. “Unchanged” compares the same old position at the same layer, before and after the append. A position’s representation still changes as it passes from one layer to the next.
We now need to identify which quantities from old positions attention uses when processing the new one.
These are the two quantities from Article 06: Keys are matched against the new position’s Query, and Values provide the content of the weighted sum. Old Queries were used to update old positions. The new position has its own Query. We therefore keep the old K and V vectors already computed at each layer. These stored results form the KV cache.4
Each layer has its own input representations and projection parameters, and its own K/V cache.5
We are reusing results computed for the same prefix. In a different preceding context, even the same the token could have different K/V vectors.
After processing the three input tokens, layer 1 stores the K/V vectors computed for their positions in layer 1. Layer 2 has a separate set, derived from representations updated by layer 1. These are different results and cannot replace one another.
Now let salt enter layer 1. We only need to compute this layer’s Q, K, and V for the new position. Its Query reads the three old Keys and its own new Key, producing four attention weights. Those weights are then used to sum the four Values.
Each head follows this process. Their results are combined and passed through the output projection. The new K and V are also added to this layer’s cache for later tokens. The full matrix calculation is in the mathematical notes.
The salt position then continues through this block’s residual updates and FFN before entering layer 2. Layer 2 computes its own Q, K, and V from the updated new-position representation and reads its own old cache. Only after passing through the final layer do we obtain the vector used to predict the period.
Figure 2: Each layer shows the reading operation for one head. Gray marks this layer’s existing K/V; orange marks what is newly computed for salt. Each layer uses a new Query to read its old cache and new K/V. The updated representation passes to the next layer.
We have reused the network calculations for old positions. The new position still passes through every layer. Old K/V can be reused; the attention weights assigned to them by the new Query must be computed again. A different position is now doing the reading.
Here is the timing of the whole process:
On small screens, scroll the table horizontally.
| Stage | Tokens actually fed into the network this round | Cached positions per layer after this round | Token chosen from this round’s output |
|---|---|---|---|
| Prefill | Please pass the | 3 | salt |
| First decode step | salt | 4 | . |
| If we continue | . | 5 | Next token |
Notice the first row: salt has been chosen, but the cache still contains only three positions. Its K/V vectors enter the caches layer by layer when the next round actually processes salt.
Caching does not discard the old context. That context still participates in the new position’s computation through the K/V vectors stored at each layer. Given the same prefix, positions, model parameters, and inference settings, this reuse gives the same mathematical result as recomputing the full prefix. Actual floating-point implementations may differ slightly.
A cost remains. Longer histories require more stored K/V. With the standard full-history attention used here, each new Query also needs to read more historical positions.
Prefill can combine many known positions into matrix operations. Token-by-token decoding updates just one new position at a time, but still reads the historical K/V. With long contexts, these data reads can become a substantial cost.6
The next article will ask how to store that history: if we do not want to keep every position’s full K/V, can we organize the past into a state that is continually updated and available for a new Query to read? This leads to Linear Attention, and to what such a change preserves and limits.
Mathematical notes
The same output matrix in both rounds
With the vocabulary ordered as Please, pass, the, salt, sugar, water, and ., the complete output matrix is:
Its seven rows and two columns map a two-dimensional input to seven scores. This output layer has no bias. The final representation at a position is a column vector, and its score vector is:
\[z=W_{\mathrm{out}}h.\]The two rounds give:
\[W_{\mathrm{out}} \begin{bmatrix}1\\1\end{bmatrix} =\begin{bmatrix}-2\\-2\\-2\\2\\1\\0\\-1\end{bmatrix}, \qquad W_{\mathrm{out}} \begin{bmatrix}-1\\1\end{bmatrix} =\begin{bmatrix}-2\\-2\\-2\\0\\-1\\0\\3\end{bmatrix}.\]The probability of the period in the second round is therefore:
\[p(\text{.}\mid\text{Please pass the salt}) =\frac{e^3}{3e^{-2}+e^0+e^{-1}+e^0+e^3} \approx0.8787.\]Computing attention for the new position with a cache
Return to the moment salt enters layer 1, and consider one head. Let q₄, k₄, and v₄ be the column vectors computed for the new position; dₖ is the dimension of the Queries and Keys. Arrange the readable Keys and Values as rows:
The first three rows come from this layer’s cache. The fourth has just been computed. The new position’s attention weights α and this head’s output a₄ are:
\[\alpha=\operatorname{softmax} \left(\frac{K_{1:4}q_4}{\sqrt{d_k}}\right), \qquad a_4=V_{1:4}^{\top}\alpha.\]Multiplying K by q₄ gives four scores. Softmax produces four weights, which are used to sum the four Values. Position 4 may read all four positions listed here, so there is no future position to mask in this expression.
Cache size, cumulative work, and the conditions for reuse
For standard multi-head attention, let B be the batch size, H the number of heads, T the number of processed positions, and dₕ the dimension of both the Keys and Values in each head. At each layer, the K cache and V cache each have shape:
\[K_{\mathrm{cache}},\ V_{\mathrm{cache}} \in\mathbb{R}^{B\times H\times T\times d_h}.\]For a single request, processing one new token adds one position to each layer’s K and V caches. If the model has L layers, the complete cache stores the following number of scalar values, ignoring additional implementation overhead:
\[2LBHTd_h.\]Cache storage therefore grows linearly with T. In a single head, the new Query is matched against T Keys, and the resulting weights read T Values. This work also grows with T.
Now add the reads across several steps. Let T₀ be the input prefix length, and let M count the single-token forward passes performed after prefill. Each pass reads the preceding history and the new position itself, so the numbers of positions read are:
\[T_0+1,\quad T_0+2,\quad\ldots,\quad T_0+M.\]Their sum is:
\[\sum_{j=1}^{M}(T_0+j) =MT_0+\frac{M(M+1)}{2}.\]With model size and batch size fixed, the cumulative work of standard full-history attention during these decode steps is:
\[\Theta(T_0M+M^2).\]For a fixed input prefix length, cumulative attention work thus includes a quadratic term as the number of decode steps grows. KV caching saves the work of recomputing old positions’ representations. Each new Query still has to read the history. This count covers attention during decoding; prefill is separate, and the expression is not a direct formula for elapsed time.
M counts forward passes. If the final output contains N tokens, prefill has already supplied the first one, so ordinarily only N−1 subsequent single-token forward passes are needed.
The reuse argument requires fixed model parameters; unchanged existing tokens, position indices, and associated position transformations; attention restricted to the current and preceding inputs; and no extra dependence on future positions through normalization, the FFN, or other operations. Random operations in the network’s forward pass, such as dropout, must be disabled. Token selection may still use random sampling: we are comparing computations for the same generated prefix. Changing an earlier token, or using a network that can read future positions, requires checking which cached results remain valid.
The verification script reproduces the output-head example and cache timing, and checks an independently constructed two-layer causal network. It compares full-prefix recomputation with incremental K/V caching; this is not a training experiment.
-
OpenAI, GPT-2’s original implementation,
src/model.py. GPT-2 shares parameters between its input embedding table and output layer, a choice called weight tying: the input looks up the vector for one token; the output uses these vectors to score candidate tokens. This is an architectural choice. The seven-token numerical example here is constructed, not a set of GPT-2 parameters or experimental results. ↩ -
Vaswani et al., Attention Is All You Need, Sections 3.1–3.4: the decoder’s causal mask, the offset between inputs and predictions, the position-wise FFN, and the vocabulary output layer. The argument that appending a token leaves old positions unchanged follows from the causal dependencies and inference conditions stated in this article. ↩
-
OpenAI, GPT-2’s original generation implementation,
src/sample.py: select a token from the final position’s logits and pass it into subsequent generation steps. This article uses greedy selection to make the example reproducible. ↩ -
Hugging Face Transformers, How caching works: K/V caches at each layer, computation for new positions, and cache updates. This article uses the cache shape for standard full-history MHA and does not cover other attention or cache strategies. ↩
-
In common RoPE implementations, the cache stores K after rotation for its position, together with the corresponding V. RoPE does not apply the same rotation to V. This does not mean that deeper-layer Values contain no positional or contextual information. Hugging Face’s Llama implementation applies RoPE to Q and K before updating the K/V cache. ↩
-
Dao et al., Flash-Decoding for long-context inference, PyTorch, 2023. The article discusses historical K/V reads and GPU parallelism during token-by-token inference. Actual latency also depends on batch size, hardware, and implementation; increasing history length alone does not establish that each step must take longer. ↩