Inside an attention head: from embeddings to next-token predictions
Large language models (LLMs) generate text by predicting what comes next from the text they have already received. Many are built on the transformer architecture, which processes token representations through a stack of transformer blocks. A key component of each block is the attention mechanism: it mixes information from the current token and earlier tokens to enrich the current token’s representation with context. Different tokens can receive different mixtures, depending on which tokens they draw information from, and in what proportions.
Before attention can mix information between tokens, the model needs a numerical representation of each one. It retrieves a learned vector, or list of numbers, called an embedding for each token. Our word embeddings and word2vec article introduces this idea. The token bank, for example, starts with the same embedding in river bank and savings bank. Attention can then mix in information from river or savings, helping the representation at bank reflect the meaning relevant to that phrase.
Distinguishing meanings of bank is just one simple use of context. Across successive layers, attention heads can use increasingly rich representations to pick up more complex relationships: connecting a pronoun to the person it refers to, relating words across a long sentence, or recognizing a pattern established earlier in the text. The information they gather helps the model predict what comes next.
In this article, we’ll study a small example of this by constructing one attention head for the prefix keep this in. We’ll trace how information from keep reaches the representation at in, the final input position, and increases the probability of mind as the next token. Starting with the token embeddings, we’ll work through the calculation to the next-token probabilities, choosing the model’s weights by hand to keep every step small enough to inspect.
Learning what to represent and what to read
In our feature-detectors article, we represented a whole message using three word counts: claim, prize, and meeting. Each coordinate carried a different piece of information about the message. The dot product provides a mechanism for reading information from the vector: it multiplies each coordinate by a corresponding weight and adds the results, allowing a neuron to respond to a particular combination of features.
The input vector described the message; the reader’s weights determined which information affected its response. That made the reader a feature detector for a particular combination of words. Changing its weights would make it respond to a different combination of the same input coordinates.
A transformer processes text as tokens: words, word fragments, or punctuation. Each token has an integer ID that selects a row in an embedding table. That row is a learned vector of numbers—the token’s embedding—and supplies its starting representation at each position where it occurs. In our small examples, each word will be one token.
The same idea of reading features from a vector now applies to individual tokens. Instead of counting words across a whole sentence, an embedding represents information about one token—its identity, meanings, and patterns of use. A dot product can read combinations of that information, just as it read combinations of word counts. The difference is that, instead of us assigning a meaning to each coordinate, training shapes how information is encoded across the embedding.
In the message example, the input coordinates came from a fixed counting rule. Training could change the detector’s weights, but it could not change how many times a word appeared in a message. With embeddings, the numbers representing a token can themselves be model parameters: training can change both what the representation encodes and how the detector reads it.
Peter Bloem’s explanation illustrates this with movie recommendations. We could manually describe movies by attributes such as romance and action, and users by how much they like those attributes. A dot product would measure their compatibility. Instead, we can make both the movie vectors and the user vectors learnable, adjusting them so their dot products fit observed preferences. The model learns useful representations without being given a meaning for every coordinate.
For our token reader, the two adjustable parts are:
| Learnable part | What it controls |
|---|---|
| Embedding table | The vector retrieved for each token |
| Reader weights | The combination of embedding coordinates that produces a response |
An attention head uses several kinds of readers, each with a different job. Some produce signals for matching tokens, while others extract the information to pass between them. We organize their weights into projection matrices, which transform each token’s embedding into the query, key, and value vectors used by the head.
These matrices act as feature extractors. They extract information for two tasks: deciding which tokens to read from and determining what they contribute. The resulting signals form the query, key, and value vectors. When we compare a query with a key, the key acts as an input vector carrying features, and the query acts as a feature detector: their dot product measures how strongly those features match what the query is looking for. The value vector contains information extracted from the source token, which attention can then mix into the receiving token’s representation.
Although this may sound abstract, in this article we’ll make it concrete by building these matrices step by step and following how their outputs help predict the next word.
Reading the skip-trigram pattern
Before we work through the mechanics, let’s look at the skip-trigram pattern that will guide our worked example. The pattern has the form [A … B → C], where A is an earlier input token, B is the current token, and C is the next token to predict. The dots show that other tokens can appear between A and B, while C follows immediately after B. This pattern gives us a convenient way to trace how an attention head reads information from an earlier token and uses it to help predict the next word.
The table below shows several skip-trigram patterns alongside sentences illustrating how they appear in context. The first three patterns come from inspecting the learned weights of small attention-only transformers, as described in the skip-trigram analysis. The last is our phrase example for the walkthrough. Token whitespace in the research examples is simplified for readability, and the arrow points to the token to predict next.
| Skip-trigram | Example |
|---|---|
| perfect … are → perfect | The venue is perfect, and the decorations are perfect too. |
| perfect … looks → super | The fit is perfect, and the jacket looks super. |
| large … contains → small | The large box contains small toys. |
| keep … in → mind | Please keep this in mind. |
In this article, we’ll focus on keep … in → mind. The model sees the prefix keep this in and must predict the next word, mind. Here, in plays the role of B: the current input token whose updated representation we read to predict C.
When a causal language model processes an input, it builds a contextual representation at every token position. Each position can use its own token and earlier tokens, and its final representation can be read to predict the token immediately after it. For the sequence keep this in mind, the first three prediction targets are:
| Position being read | Context available at that position | Next-token target |
|---|---|---|
keep | keep | this |
this | keep this | in |
in | keep this in | mind |
To continue the supplied prefix keep this in, we use the final position, in, because its prediction concerns the word after the whole prefix. Our walkthrough therefore follows how attention updates that row. Attention at in can mix information from keep, this, and in itself; it cannot read the missing mind that we want to predict. The diagram below highlights this chosen row and shows four coordinates per token, matching our small model. There is no fourth input row yet: mind is the continuation target.
The updated vector is a contextual representation of in, built from its learned embedding and information from the surrounding context. It is a temporary result of processing this input; it does not replace the embedding stored for in in the model’s learned table. The vector still belongs to the in position, but it now carries information used to predict what follows the whole prefix keep this in. Once the next token has been selected, the model can discard this final vector.
The following diagram shows where the information goes: in reads from the earlier keep, and information from keep contributes to the representation at in. The vocabulary readout then turns that updated representation into next-token scores.
The diagram isolates the contribution from keep, although the other input tokens can also contribute to the attention mixture. We’ll calculate how much information comes from each position and how it affects the prediction.
The smallest model we need
Our starting model has one attention layer with one head. We will follow the same progression as in our earlier walkthrough: work through the input encoding by hand, choose simple weights ourselves, and calculate the prediction step by step.
The diagram above shows our toy model, from input token IDs to next-token probabilities and the training loss. It selects the final position for the continuation task we are studying; the attention layer updates every input position. The diagram below previews the path through its attention head that we’ll explore throughout the article: queries and keys determine attention weights, those weights mix the values, and the output projection turns the mixture into an update at in. The model adds that update to the original representation before the vocabulary readout.
For the calculation below, we’ll manually choose the entries in the attention head’s query, key, value, and output projection matrices: , , , and . We’ll also choose the token embeddings and vocabulary readout weights so we can calculate the complete prediction ourselves. We’ll use four coordinates per token representation, one coordinate per query and key, and two coordinates per value. These small dimensions let us display every matrix.
For now, focus on how these stages connect; the later diagrams and worked calculations will explain each stage in detail. We’ll first introduce the three vectors and focus on computing attention weights: how the query at in is compared with the available keys, and how softmax turns the resulting scores into attention weights. Together with the query and key projections, this forms the QK (query–key) circuit, the part of the head that determines its attention pattern.
What information we gather at the final position
Let’s first see how attention combines information from the input tokens into an updated representation for prediction. Given keep this in, we want to understand what information from the context helps the model predict mind. At each position, the model starts with that token’s embedding and updates it with information from the available context. We’ll follow the update at in, whose representation is used to predict the continuation of our prefix.
To read that contextual information, the attention mechanism builds three vectors from each token’s current representation: a query, a key, and a value. The following schematic shows each token’s representation in keep this in alongside its associated query, key, and value.
These vectors are produced by applying learned projection matrices to each token’s representation. We can think of these projection matrices as feature extractors: each computes combinations of the input coordinates, producing signals for matching (queries and keys) or information to pass along (values). For our current purpose, we don’t need to understand those calculations yet; we only need to understand the roles of the Q, K, and V vectors.
To do that, let’s start with in, the last token in keep this in. To decide which tokens to read from, the query at in acts as a feature detector over the available keys. Each key carries signals extracted from a source token’s representation and plays the role of the input vector in our feature-detector example, while the query supplies the reader’s weights. The same reader evaluates each available key: their dot product produces a matching score. Here, the reader’s weights—the query—are themselves computed from in’s representation.
The same query is compared with the key supplied by each preceding token, as well as in’s own key. The resulting scores are converted into attention weights, which determine how strongly each token’s value contributes to the representation at the final position.
The query stays the same across all three comparisons; the source key changes. Each comparison produces a score, and softmax converts the three scores together into attention weights. We’ll calculate the numbers below.
Each source also supplies a value vector: the information it contributes to the mixture. The attention weight scales that source’s whole value vector, and the head adds the weighted values together. Its output projection maps this mixture into an update at in.
We chose two coordinates per value vector for this toy model to keep the arithmetic small while showing how one attention weight scales multiple coordinates together. Each cell represents one coordinate, and the same weight multiplies both. The output projection then maps the two-coordinate mixture into a four-coordinate update, matching the width of our token representations. This update is added to the starting representation at in.
Every token position uses the same attention mechanism. What we’ve described for in also happens at keep and this: each position produces its own query, key, and value using the same projection weights. Its query is compared with the available keys, and the resulting attention weights determine the mixture of values used to update its representation. In our causal model, keep can read only from itself, this can read from keep and itself, and in can read from all three positions.
The computation we’ve just traced forms the attention part of a transformer block. After attention adds its update, the block processes the resulting representations with an MLP (multilayer perceptron), a feed-forward network that often has more learned parameters than the attention component. It processes each position’s representation independently, using nonlinear transformations to compute a further update.
These evolving representations are carried through the model in the residual stream: one vector per token position, which attention and MLP components read from and write updates back to through addition. At each position, the final representation is the result of these successive updates and supplies information for predicting the token immediately after that position. Our residual-connections article explains this view of the residual stream in more detail.
In the diagram below, , , and denote the token representations before attention, after attention, and after the MLP, respectively.
Attention and the MLP are separate sublayers, each with its own residual addition. We group them into a transformer block because they form a repeating sequence: attention mixes information between positions, then the MLP processes the updated representation at each position. The MLP can therefore respond to information attention has just brought in. The next block repeats this sequence, with the residual stream continuing through both components and across block boundaries.
The diagram also shows that the attention layer contains several heads, labeled , , and so on. Each head performs the query–key comparisons and value mixing we described, using its own learned projection weights. Within a head, the query projection uses the same weights at every token position, as do the key and value projections. The heads read the same incoming representations in parallel, but can assign different attention weights to the available positions and extract different information from them. Their projected outputs are added to the residual stream. This lets several heads contribute different kinds of information at in, although their roles can overlap.
For our worked example, we’ll use just one head and omit the MLP so we can trace one attention contribution in detail. Even with this simplification, the updated vector at in can carry information about the whole prefix, beyond the identity or meaning of in itself.
Why we learn projection matrices
We’ve seen how attention uses queries and keys to decide where to read, and values to supply the information it gathers. To produce these vectors, each head applies learned projection matrices to the current representation at each position. Before working through those calculations, let’s establish why we learn the matrices that produce Q, K, and V rather than learning the vectors directly for each token.
In our toy model, the two approaches would be equivalent. In the numerical example below, we’ll choose one-hot embeddings: one coordinate is 1 and the others are 0. Multiplying such a vector by a projection matrix simply selects one row. With those embeddings fixed, learning the projection matrix is equivalent to learning a table of output vectors, one per input token.
The distinction matters in later transformer blocks. Their attention heads read representations that earlier layers have already updated with context. The vector at in can therefore differ between inputs, even though the token is the same. A projection computes a query from that current representation: . During inference, stays fixed, but a change in can change the query. The same applies to keys and values. This lets earlier layers influence what later heads read and transmit, as described in the paper’s discussion of attention-head composition.
Learning projection matrices therefore gives the model a shared way to extract Q/K/V vectors from the information currently available at each position. Looking up fixed Q/K/V vectors by token ID would ignore the contextual updates made by earlier layers. Our one-layer example makes the two approaches look equivalent because its projections act directly on the original token embeddings.
Follow one prediction through Q, K, V, and O
Let’s now work through the prediction for keep this in, starting with token IDs and embeddings, then calculating each step illustrated in the earlier diagrams.
| Step in the attention calculation | What we’ll calculate |
|---|---|
| Each token’s query, key, and value | Apply the projection matrices , , and to the input embeddings |
| Compute attention weights | Compare the query at in with the available keys, then apply softmax |
| Scale and mix the values | Multiply each source value by its attention weight and add the results |
Write the update at in | Apply to the mixture and add the update to the starting representation |
The vocabulary readout will then turn that updated representation into next-token scores. First, we’ll assemble the input matrix that supplies the embeddings for these calculations.
Encode the input with token IDs and embeddings
Now that we’ve conceptually established the roles of queries, keys, and values, let’s set up the numerical example. We’ll start with , the input matrix that the attention head will use to calculate them. It will contain one embedding vector for each token in our input, in sequence order. To create it, we’ll assign token IDs, show the rows of an embedding table for the three words in our input, and use their IDs to retrieve the rows we need.
For our word-level tokenizer, we’ll start with the four-word vocabulary below and assign each word an integer ID.
| Word | keep | this | in | mind |
|---|---|---|---|---|
| ID | 0 | 1 | 2 | 3 |
Our tokenizer simply splits on spaces and looks up each word. It converts keep this in to [0, 1, 2]. These input IDs refer to the corresponding rows in the embedding table. For the input keep this in, the target next word is mind, stored separately as ID 3.
Next, we’ll specify the three rows of the input embedding table used by keep this in. Each token gets a vector with four coordinates:
| ID | Word | Embedding row |
|---|---|---|
| 0 | keep | |
| 1 | this | |
| 2 | in |
These rows deliberately put the input words on separate coordinate axes to simplify the calculations. In real networks, embedding coordinates are learned real-valued numbers, not just 0s and 1s. We leave the embedding for mind unspecified because this forward pass does not look it up. The separate vocabulary readout matrix introduced below produces four output scores, including a score for mind.
Now that we’ve defined the embeddings for our input words, we can assemble the input matrix that will be fed into the attention head.
For this input, we retrieve the embeddings for keep, this, and in from and arrange them as rows of , producing a matrix:
In our toy model, is the starting state of the residual stream: one row per input position, initially containing that token’s embedding. Attention reads these rows and adds an update to each one. The resulting matrix still has three rows and four coordinates per row, but its values now incorporate information from the context.
We omit positional embeddings in this toy model so we can concentrate on the token projections and attention calculation.
Define the projection matrices for our example
With the input embeddings in place, we first need to define the matrices that produce queries, keys, and values. As illustrated earlier, each attention head has three projection matrices for producing these vectors: for queries, for keys, and for values. In a trained model, their entries are parameters adjusted during training. For this walkthrough, we choose the weights manually so we can follow a complete prediction with simple numbers. We’ll explain how these weights produce the vectors and affect the prediction; these values are not the result of a training run.
To see what determines a matrix’s dimensions, start with one input vector containing four coordinates. Temporarily write it as a column, as in our feature-detector walkthrough:
The matrix needs four columns so each row can take a dot product with all four input coordinates. Each row contains one reader’s weights and produces one output number. For example, its first row produces .
The number of rows determines the output dimension and is defined when we design the model architecture. Choosing rows gives the output coordinates, with each row defining the weights for an individual reader. Each reader’s weights determine which combination of input coordinates it extracts. Different readers may extract similar or identical combinations from the same number of input coordinates, so more output coordinates do not necessarily mean more distinct features.
For the rest of this article, we write token vectors as rows so we can stack the input tokens into . Transposing the calculation reverses the multiplication order: the input becomes a row vector on the left, and the matrix becomes on the right. The readers now occupy columns instead of rows. We get:
In this convention, the four matrix rows match the input width, and the columns determine the output width. The model architecture specifies these vector widths, which determine the projection-matrix shapes.
For our example, we will use four coordinates per embedding (), one coordinate per query and key (), and two coordinates per value (). Queries and keys need matching widths for their dot product; values can have a different width.
The table shows how each projection maps the input width to its output width:
| Projection | Matrix shape | Our example: input → output width |
|---|---|---|
These small dimensions keep the arithmetic easy to follow. With one-coordinate queries and keys, each matching score is simply a multiplication of two numbers. Two-coordinate values let us see how a source’s single attention weight scales multiple coordinates before we add the weighted vectors.
With the matrix shapes fixed, we will use the following weights:
We chose these weights to demonstrate the following behavior, which we’ll work through in the upcoming sections, starting with the query calculation:
| Matrix | What the choice lets us examine |
|---|---|
Produces a single-number query vector, with a value of 1 for in, to keep matching simple | |
keep receives a positive matching score from the query at in, while the other sources receive zero scores | |
keep supplies two equal value coordinates, letting us track how one attention weight scales both together |
Applying these matrices to produces one query, key, and value per input position:
Here, holds the current residual-stream representations, with one token per row. Multiplying each row of by , , or is how the head reads that representation to produce its query, key, and value. After attention mixes the values, maps the mixture into an update that is added back to the stream.
The token count stays the same: each result has three rows, one per input position. What changes is the number of coordinates per token.
When generating text one token at a time, the model can save the keys and values it has already computed for earlier tokens. This saved data is called a KV cache. When processing the next token, those saved keys and values are reused instead of being computed again. Model providers can also reuse cached computation across requests that share an identical prompt prefix, a technique called prompt caching.
The name KV cache reflects what later tokens need: earlier keys and values, but not earlier queries. For example, the query for in determines how strongly in reads from keep, this, and itself. When we process the next token, we use that token’s query instead; we still need in’s key and value, which we can retrieve from the cache, but no longer need its query.
Build a query from the current token’s embedding
We’ll now apply the query projection matrix to each input embedding to calculate its query vector. We chose a query width of in the previous section, so each resulting query vector contains only one number, calculated as a weighted sum. This is the same operation used by a feature detector in our neuron walkthrough.
First, we’ll build a formula we can use for all input embeddings. The single column of contains the weights . For any input row , the query is:
Only the third coordinate contributes, because its weight is 1 and the other weights are zero. The following table applies this formula to our input embeddings:
| Token | Embedding | Calculation | Query |
|---|---|---|---|
| keep | 0 | ||
| this | 0 | ||
| in | 1 |
For in, the third coordinate is 1 and the others are zero, so its query is 1. The queries for keep and this are zero.
Now we can apply to all token embeddings in —the three rows—to obtain , the query matrix for the whole input phrase. Each row of contains the query vector for one input token. This gives:
The result contains one query vector per input token: the three rows correspond to keep, this, and in. All three are computed using the same projection matrix .
This calculation demonstrates the concept of extracting a feature: using the weights in to turn each token’s embedding into a query vector. Our chosen weights produce a single-value vector for each token: 1 for in and zero for keep and this. Each number is the single coordinate of its token’s query vector. Once we’ve extracted the key vectors, we’ll compare these query vectors with them to calculate attention weights. With our hand-chosen embeddings, the combination is easy to interpret. In a learned embedding, information can be spread across many coordinates, and a useful reader may need nonzero weights on all of them.
Build keys and values from the token embeddings
We’ve calculated the query vectors. Let’s now apply and to the same input embeddings to calculate the keys and values. We chose a key width of and a value width of earlier, so each resulting key vector contains one number and each value vector contains two. Both use the same mechanics as the query calculation: each number is calculated as a weighted sum using one column of the corresponding projection matrix.
As with the query calculation, we can first derive formulas from the projection matrices and for any input embedding . Simply running the calculations gives us:
Plugging in keep’s embedding , where , gives a key of and a value of . For this and in, the first coordinate is zero, so both their keys and values come out zero. These are the numbers that fill the table below.
We chose identical columns to keep the arithmetic simple while showing how one attention weight scales both value coordinates. These coordinates belong to the head’s value space; they are not vocabulary scores. The output projection and vocabulary readout will determine how the mixture contributes to predicting mind.
Just as we collected the queries into , we can collect the keys into and the values into , with one row per input token:
The key matrix has one coordinate per token, while the value matrix has two.
The following table shows these keys and values alongside the queries we calculated earlier:
| Token | Query | Key | Value |
|---|---|---|---|
| keep | 0 | 4 | |
| this | 0 | 0 | |
| in | 1 | 0 |
We now have the queries, keys, and values. Next, we’ll use them to calculate attention.
Compute query–key matching scores
We’ll now use and to calculate a table of query–key matching scores, then apply softmax to turn those scores into attention weights. The calculations we’re working through here correspond to the Compute attention weights block in the earlier diagram, where we showed the full attention mechanism. The main idea is to compute a dot product for every query–key pair, comparing each token’s query with every token’s key.
For example, we have the query vector for in and the key vector for keep. Their dot product is . When we do this for every query–key pair, we end up with a table that contains one matching score for each pair. With three input tokens, this gives scores. We can calculate them all at once through matrix multiplication by transposing so its token rows become columns, then multiplying by the result. This gives us :
It might be easier to visualize this calculation as a table of query–key comparisons. Each row in the table below represents one receiving token, which supplies the query. Each column represents one possible source token, which supplies the key. Reading across a row keeps the receiving token’s query fixed and compares it with each source token’s key. Both rows and columns follow the token order in our input matrix : keep, this, in. Query values appear in blue beside the row labels, and key values appear in purple beneath the column labels. Each cell shows their dot product:
For example, the entry in the third row and first column compares the query at the receiving token in with the key at the source token keep. The query at in helps determine how strongly to read from keep, whose value supplies the information to mix into in. We’ve highlighted this cell in orange. It contains their matching score, which softmax will later turn into an attention weight.
Note that each query–key dot product produces one number, regardless of the vector width. For example, a two-coordinate query and key give:
This means that, while our query and key vectors have only one coordinate, the result would still have three rows and three columns if those vectors had multiple coordinates. The token count determines the number of rows and columns; the query/key width determines how many terms each dot product sums. More generally, for input tokens and a query/key width of , the computation has the following dimensions:
The standard formula you’ll often see in explanations of attention includes one more step: dividing each dot product by , where is the query/key width. For a query at input token and a key at input token , the score is:
is the matching score between the query at token position and the key at token position , after dividing by . It becomes an attention weight only after applying softmax across that row of scores.
The indices and are row indices in our input matrix . The index identifies the receiving token, whose query vector is . The index identifies a possible source token, whose key vector is . These indices refer to token positions, not individual coordinates within their vectors.
For example, compares the query derived from ’s in row with the key derived from its keep row:
One interesting detail is the division by . When query and key vectors contain more coordinates, their dot product sums more terms and can produce larger values. Dividing by helps prevent softmax from assigning nearly all the weight to one token, which can make gradients too small for effective learning. The original paper that introduced transformers explains why square-root scaling is used. In our example, , so the scores remain unchanged.
Turn scores into attention weights
There are two more things we need to do before we get the attention weights: apply causal masking, then run softmax on each row of scores. The idea behind causal masking is to let each token read only from itself and earlier tokens. When generating text, the model must predict the next token using only the prefix it has received. Processing a whole sequence at once must preserve that restriction: an earlier position should not use later tokens to help predict what comes next. Causal masking prevents that access to future information.
To apply the mask, we take the score table computed in the previous section and set the scores for future tokens to negative infinity: keep cannot read from this or in, and this cannot read from in. The table below shows the masked scores, , with query tokens in rows and key tokens in columns. The gray cells mark the future tokens that each query cannot read:
The masked scores are ready. We can now turn them into attention weights.
The last step is to apply softmax separately to each row so its weights over the available source tokens sum to one. Softmax exponentiates each score, then divides each result by the sum of the exponentiated scores in that row. This is why causal masking uses negative infinity rather than zero: , so masked entries receive zero attention weight, whereas would still give them a share of the weight.
For our example, the masked score matrix is:
For a row of scores , softmax gives each source token the weight:
The numerator uses that token’s score; the denominator sums the exponentiated scores of all source tokens in the row. Let’s apply this formula to the last row of , which contains the scores for the receiving token in:
which gives us:
The three rounded entries correspond to keep, this, and in. About 96.47% of the weight goes to keep; each remaining token gets about 1.77%. Notice that the weight on keep depends on the other sources too: softmax compares its score with theirs. A high score for one source is not an attention weight by itself.
These attention weights show how much each source token’s value contributes to the mixture at the receiving token. The weight of 0.9647 on keep means that in directs most of its attention there. Next, we’ll use those weights to calculate what each source contributes.
After applying the same operation to every row, we get the attention-weight matrix :
The rows and columns still follow the order keep, this, in. Each row now contains one receiving token’s weights over the source tokens; these weights are nonnegative and sum to one before rounding. The first row assigns all of keep’s attention to itself. The second assigns half of this’s attention to keep and half to itself. The last row contains the weights we’ll use to mix the value vectors at in.
This table also helps explain the context window: the limit on how many token positions the model can work with, including the input and generated continuation. Our three input tokens give a attention matrix; with tokens, the full matrix has rows and columns. A longer context adds token positions, while the width of each query, key, and value vector stays the same. Each generated token becomes another input position for the next prediction. For scale, documentation checked in November 2026 lists 256k tokens for Mistral Small 4 and 1M tokens for models including Claude Opus 4.6.
In the next section, we’ll use the final row—the attention weights at in—to mix the source tokens’ value vectors.
Combine value vectors using attention weights
We now have the two ingredients we need: attention weights and value vectors. Both come from calculations using the projection matrices , , and , whose weights we chose by hand here but which are normally learned during training. We applied and to the embeddings to produce queries and keys, then calculated the attention weights by comparing those vectors, scaling the scores, applying the causal mask, and running softmax. Separately, we used the value projection matrix to extract information from each source token’s embedding into a value vector—that’s the information we’ll mix into the receiving token’s representation.
The table below summarizes the projection matrices and the two ingredients they help produce:
| Component | How it is obtained | Role in the calculation |
|---|---|---|
| Projection matrices | Chosen by hand here; normally learned during training | Turn token embeddings into queries, keys, and values |
| Attention weights | Computed from queries and keys by scaling, causal masking, and softmax | Set how much each source’s value enters the mixture |
| Value vectors | Produced by applying to each source token’s embedding | Carry the information being mixed |
We now have everything we need to form the mixture. The last step is to multiply each source’s value vector by its attention weight, then add the weighted vectors coordinate by coordinate. Remember that we’re focusing on the token in, so we’ll denote the resulting mixture by .
The final row of the attention-weight matrix contains the weights for the receiving token in. The rows of contain the source value vectors those weights will scale:
Both matrices follow the row order keep, this, in; the columns of follow the same source-token order. The rows of give , , and . We multiply each vector by its corresponding weight from the final row of , then add the results to produce the attention output at in:
The attention weight multiplies each coordinate of the value vector. Multiplying the rounded weight by gives . Using the unrounded weight and rounding only the final result gives . Because the attention weights are nonnegative and sum to one, this mixture is a weighted average of the source values.
We now have the mixture vector , which contains the information gathered from the source tokens for in. In this example, all its nonzero content comes from keep, because the other value vectors are zero. The last step is to add this information to in’s representation in the residual stream, using the output projection to match its dimensions first. Before that, here’s an overview of what we’ve just demonstrated.
What to mix in, and how much
We’re following keep … in → mind: how the source tokens contribute to the representation at in, which we’ll use to predict the next token. Each source token supplies a value vector describing what information to mix in, and a key that we compare with in’s query to help determine how much to mix in. The resulting attention weight comes from applying softmax to the matching scores.
For the receiving token in, the contributions are:
| Source token | Value vector: what to mix in | Attention weight: how much | Weighted contribution |
|---|---|---|---|
keep | |||
this | |||
in |
The following diagram shows how comparing queries and keys produces attention weights, and how those weights determine each source value’s contribution to the mixture at in. It highlights the contribution from keep, showing the paths that produce its key, value, and attention weight.
What we can see in the diagram are the two separate jobs an attention head does: deciding where to look and what information to move. The paths that perform these jobs are named after the weight matrices involved. The terms QK circuit and OV circuit are used in mechanistic interpretability, notably in Anthropic’s A Mathematical Framework for Transformer Circuits.
QK path (query–key): where to look. The receiving token, in, produces a query, and every available source—including in itself—produces a key. Query–key dot products give matching scores; scaling, causal masking, and softmax turn those scores into attention weights. This path answers “how much should in read from each source?” It determines how strongly each value is weighted, without determining the value’s contents. Here, it makes in attend strongly to keep.
OV path (output–value): what information to move. Each source’s embedding passes through the value projection, , and then the output projection, , to produce the vector it can contribute to the receiving token’s representation. This path answers “if in attends to keep, what information arrives?” The attention weight scales that vector. The diagram shows the value part of this path and stops at the mixture; next, we’ll calculate the output projection that turns the mixture into a residual-stream update.
The two paths use separate projection weights but read the same input representations. With those representations held fixed, changing the QK weights changes how much is read, while changing the OV weights changes what is delivered. The final update is a weighted sum of the source vectors. We compute it by mixing the values first and applying afterward; because is linear, this is equivalent to projecting each value first and then summing the weighted results.
keep receives most of the attention weight and supplies all the nonzero information in this mixture. this contributes exactly zero because its value vector is , even though its attention weight is nonzero. The same is true of in’s value vector. The displayed numbers are rounded; the contributions use the unrounded weights.
Add the attention output to the residual stream
We’ve combined the source values into the mixture vector , with each token contributing according to its attention weight. To use that information for the next-token prediction, we need to update in’s existing representation in the residual stream. The attention branch transforms the mixture to match the residual stream’s width, then adds it to the current token’s representation, as shown in the diagram below.
Remember that the residual stream carries a separate representation for each input token. For keep this in, those representations belong to keep, this, and in, as shown below. The target token mind is not part of the input.
At the start of our calculation, these representations are the token embeddings collected in . Each row contains the four coordinates for one input token:
After projection, our calculated mixture will be added to the row to update in’s representation. The layer computes a separate update for each token and adds it to the corresponding row. We’re tracing only the final row because we want the prediction after the whole prefix, keep this in. The other rows receive their own updates and can be read to predict their respective following tokens.
Before we can perform the update, we need to make the mixture match the width of the token’s representation in the residual stream. In our example, the mixture has two coordinates, while the token’s representation has four. This is typical in transformers: each attention head usually works with fewer coordinates than the residual stream. To perform this mapping, we use an output projection matrix, , which transforms the two-coordinate mixture into a four-coordinate update.
In our single-head model, is the head’s output projection. In a typical multi-head implementation, the head outputs are concatenated and passed through one shared . Mathematically, that matrix can be split into a separate output projection for each head, whose contributions are then added together.
For this walkthrough, we choose weights that copy the two mixture coordinates into the third and fourth coordinates of the residual representation. Keeping them separate and unchanged makes the mapping easy to follow. Our vocabulary readout will later use the third coordinate to score mind:
Because the mixture is a row vector multiplied on the left, we compute each output coordinate by taking its dot product with a column of , using rounded values below:
Putting those four coordinates together gives:
As you can see, the two entries we set to in copy the mixture coordinates to their chosen positions. The zeros make the first two update coordinates zero, so adding this update leaves the first two residual coordinates unchanged.
We can now add the update vector coordinate by coordinate to the last row of , which holds in’s original embedding. This residual addition gives us the updated representation we’ll use to predict the next token:
The last row has therefore changed from to . The original in representation and the information read from keep are now present in the same vector. This completes the attention update: in’s representation now includes information from the surrounding tokens.
Turn the updated representation into a next-token prediction
We’ve finished updating in’s representation. To turn it into a next-token prediction, we introduce a vocabulary readout matrix, , also called the unembedding matrix. In a full decoder-only language model, this readout sits after the final transformer block. It maps a token’s final representation to one score per vocabulary word. The output layer that performs this mapping is often called the language-model head. Here, the word head refers to the model’s output layer, which has a different role from the attention heads inside transformer blocks.
The unembedding matrix can read every position’s representation, using the same weights for each row. During training, this lets us compare each position’s prediction with the token that actually follows it and use those errors to update the model’s weights. Given keep this in, we can therefore obtain three sets of vocabulary scores in one forward pass:
| Position being read | Context available at that position | Next-token target |
|---|---|---|
keep | keep | this |
this | keep this | in |
in | keep this in | mind |
As we demonstrated earlier, causal masking lets each position read only its own token and the tokens before it. To generate the next token, we only need to read the last row—in in our example. Our toy model omits the MLP and normalization, so we apply directly after its single attention layer’s residual update.
Recall our four-word vocabulary: keep, this, in, and mind. The matrix maps the four-coordinate representation to one score for each of these words. The rows correspond to the four coordinates of the updated token representation in the residual stream. The columns correspond to the four vocabulary words in the order above. This gives the matrix a shape of . We choose:
Each entry tells us how much that coordinate contributes to that word’s score. We defined the matrix to read the third representation coordinate into the score for mind. Its other rows are zero, so this readout ignores the remaining coordinates. The scores for keep, this, and in are zero:
We use for the updated representation at in and for the vocabulary scores it produces. These scores are called logits. The score for mind combines about 1.9293 from attention with 1 from in’s embedding, , retrieved from the embedding table and carried forward through the residual connection.
In a trained model, the embedding table is learned jointly with the attention and readout weights through the same prediction loss. We chose its entries manually for this example. During a forward pass, attention updates the representation in the residual stream; it does not change the embedding stored in the table.
To obtain next-token probabilities from these logits, we apply softmax across the four vocabulary scores:
The value 0.8618 means that, given keep this in, our model assigns an 86.18% probability to mind as the next token. To compute these probabilities, we use the same softmax formula as in attention, but this time, instead of determining how strongly to read each input position, it turns vocabulary scores into next-token probabilities.
The chart below separates each logit into the contribution from attention (blue) and from in’s embedding (orange)—the vector retrieved from the embedding table and carried forward through the residual connection. That table is learned jointly with the other model weights during training; the attention update leaves its stored entries unchanged. The green bars show the probabilities after vocabulary softmax. Each row shows the model’s score and probability for one word in our four-word vocabulary.
The blue contribution comes entirely from keep. The attention weight assigned to keep by the query at in scales keep’s value vector: . The output projection writes the mixture into the third and fourth residual coordinates; our readout uses the third to increase the score for mind. The value vectors for this and in are zero, so they add nothing to the mixture. Together with the 1 carried forward from in’s embedding, the attention contribution gives mind a logit of 2.9293 and a probability of 0.8618. Each other word has probability 0.0461. The most likely next token is therefore mind, matching the continuation we wanted after keep this in.
How the MLP uses the updated representations
Our walkthrough goes directly from the attention update to vocabulary scores. In a full transformer block, an MLP processes the updated representations before they pass to the next block. Let’s connect that step to the numbers we calculated.
Here is the transformer-block diagram again: , , and denote the token representations before attention, after attention, and after the MLP, respectively.
After attention and residual addition, the representation at in is:
This vector contains both the original contribution from in and the information attention brought in from keep. The MLP reads this combined representation. In a block that normalizes before each sublayer, its calculation at this position is:
Inside a standard MLP, a learned projection reads combinations of the input coordinates, a nonlinear activation transforms those responses, and another learned projection combines them into an update. The hidden representation is usually wider than the residual stream, but the output must match its width so it can be added back. In our four-coordinate example, the MLP would therefore produce another four-coordinate update. We haven’t assigned MLP weights, so we cannot calculate that update numerically here.
The same MLP, with the same weights, processes each token’s row independently. Given our three-row matrix, it produces a three-row matrix of updates, with each update added to its corresponding row. Different input rows can produce different updates. At in, the MLP can use information from keep because attention has already brought that information into the row it reads.
This gives the two sublayers complementary roles: attention mixes information between positions, and the MLP transforms the information now available within each position. An attention update can therefore affect a later prediction both through its own contribution to the residual stream and by changing how the MLP responds. Our attention-only example leaves out that additional computation so we can follow the source contributions directly into vocabulary scores.
What the calculation shows
Our chosen query and key projections make in attend strongly to keep. The value and output projections carry information from keep into the representation at in, and the vocabulary readout turns that information into an increase of about 1.9293 in the score for mind. With only the original embedding’s contribution, mind would have a score of 1 and a probability of about 47.54%; adding attention’s contribution raises its probability to 86.18%. This is the contribution we set out to trace.
Our weights were chosen by hand to make these mechanics visible. Training can learn the embeddings and projection weights that produce such behavior; this walkthrough demonstrates the computation those weights implement. The direct calculation of logit contributions is exact in this toy model because no normalization, MLP, or later layer intervenes between the attention update and the linear readout. The separation between matching and value delivery also applies within attention heads in larger models, but later computations can transform what a head writes before the final prediction.