How LLMs Use Context: Understanding Self-Attention


On this page

1. Why context matters

Consider these two sentences:

Sentence A: The cargo ship entered the port yesterday.

Sentence B: The server application opened the port yesterday.

As readers, we can easily tell that port means something different in each sentence. The surrounding words give us the context, almost without us thinking about it. But a language model receives these sentences as numbers, and the context doesn’t come naturally for it.

A language model needs to use the context it has been given, whether it is continuing a sentence, answering a question, or following a request. In each case, a useful prediction depends on how pieces of text relate to one another, not just on which tokens appear individually. How does it use those numbers to pick up on the context?

Self-attention gives the model a way to combine information across token positions in the same sequence. It uses their representations to calculate how much each permitted position contributes. Together with the other operations in a transformer block, this allows the model to build representations that can reflect the available context.

In the previous article, From Text to Tokens and Embeddings, we saw how a tokenizer breaks text into tokens and assigns them IDs. Each token ID selects an initial embedding vector. The same token ID selects the same vector each time. That gives the model a starting representation, but the lookup alone does not combine information from other tokens in the input.

In this article, we’ll start with those input embeddings and see how attention is calculated. We’ll follow a single-head attention example, extend it to two heads, and then inspect a small pretrained model. Our two sentences give us an example to return to: both contain the token ' port'. Its initial embedding is the same in each sentence, while the preceding text differs. We’ll inspect what happens to its representation after the model processes that context.

We’ll use SmolLM2-135M, a causal language model: each position can use itself and earlier positions, but not later ones. The opening The, for example, cannot use the words that come after it.

The companion notebook contains the calculations and model inspection. You can follow the article without running it; the notebook and setup instructions are linked at the end.

In a causal model, the selected port token at position 5 can use earlier positions and itself, but cannot attend to the later yesterday token.
The selected position can use itself and earlier positions; it cannot attend to later tokens.

2. How self-attention works

Let’s make the calculation small enough to follow by hand. Imagine an input with three token positions. Each position has a current vector representing it. In the first transformer block, these starting vectors are input embeddings. Later blocks receive vectors updated by earlier blocks; these internal representations are also called hidden states.

For this illustration, each vector has four values. We collect the three vectors as rows in a matrix called XX:

X=[101001011100]X=\begin{bmatrix} 1&0&1&0\\ 0&1&0&1\\ 1&1&0&0 \end{bmatrix}

The rows represent positions 0, 1, and 2. These values are invented to make the arithmetic visible; their coordinates do not have assigned meanings.

We’ll focus on the last position, position 2. Because our model is causal, this position can use information from itself and the two positions before it. How much should each position contribute?

Preparing queries, keys, and values

To decide how position 2 will use the available information, we create three vectors for each position:

  • A query represents what the position will use to compare against other positions.
  • A key provides a way for a position to be compared with a query.
  • A value contains the information that position can contribute to the result.

We compare position 2’s query with the permitted keys. Those comparisons give us scores, which become weights. We then use the weights to combine the corresponding values.

The model creates these vectors using projection matrices. A projection combines input values through matrix multiplication; an output value can depend on all the coordinates of the input vector.

In a trained model, projection matrices are learned parameters. During training from scratch, they start with initialized values; the optimizer adjusts them along with other parameters as the model learns. During ordinary inference, those parameters stay fixed. Queries, keys, and values are calculated for the current input; they are not stored as the projection parameters.

For our example, each of the three projection matrices has four rows and two columns. Let’s start with the query projection:

WQ=[10011001]W_Q=\begin{bmatrix}1&0\\0&1\\1&0\\0&1\end{bmatrix}

For an input row [a,b,c,d][a,b,c,d], this projection produces the query [a+c,b+d][a+c,b+d]. We also use separate projections for keys and values:

WK=[10010002],WV=[10011101]W_K=\begin{bmatrix}1&0\\0&1\\0&0\\0&2\end{bmatrix},\qquad W_V=\begin{bmatrix}1&0\\0&1\\1&1\\0&1\end{bmatrix}

Applying each projection to all three positions gives:

Q=XWQK=XWKV=XWV\begin{aligned} Q &= XW_Q\\ K &= XW_K\\ V &= XW_V \end{aligned}

Here XX is our 3 × 4 input, each WW is a 4 × 2 projection matrix, and QQ, KK, and VV contain the resulting queries, keys, and values. Each result is 3 × 2: one two-value vector per position. Here VV means the value matrix; we used the same letter for vocabulary size in the previous article.

The calculations produce:

Position Query Key Value
0 [2, 0] [1, 0] [2, 1]
1 [0, 2] [0, 3] [0, 2]
2 [1, 1] [1, 1] [1, 1]

From scores to weights

Now take position 2’s query, [1, 1], and compare it with each key. We use a dot product: multiply corresponding values and add the results.

Key position Calculation Score
0 1 × 1 + 1 × 0 1
1 1 × 0 + 1 × 3 3
2 1 × 1 + 1 × 1 2

The scores help decide how much each position contributes. A higher score receives more weight relative to the other permitted scores after the steps below. This dot product is not cosine similarity, and a score alone does not prove that two tokens are semantically related.

The scores are not yet weights. First, we scale them by dividing by the square root of the query/key width. Our width is dk=2d_k=2, so [1, 3, 2] becomes approximately [0.707, 2.121, 1.414]. Scaling helps prevent scores from becoming so large that the next step produces overly concentrated weights.

Next comes the causal mask. Position 2 is last in our three-position example, so it can use all three scores. Position 1, however, cannot use position 2: its future score is masked. In the calculation, we add zero for permitted positions and negative infinity for future positions, making their eventual weights zero.

Finally, softmax converts each position’s permitted scores into nonnegative weights that sum to one. For position 2, the weights are approximately:

Position 0     Position 1     Position 2
   0.140          0.576          0.284

These are weights over positions, not probabilities of the next token. They tell us how to combine the values.

Combining the values

We now have a weight for each position that position 2 is allowed to use. We multiply each position’s value vector by its weight, then add the weighted vectors together. The result is a new attention output vector for position 2.

Let’s multiply each value vector by its weight:

0.140 × [2, 1] = [0.280, 0.140]
0.576 × [0, 2] = [0.000, 1.152]
0.284 × [1, 1] = [0.284, 0.284]

Now add the weighted vectors coordinate by coordinate:

  [0.280, 0.140]
+ [0.000, 1.152]
+ [0.284, 0.284]
----------------
= [0.564, 1.576]  ← attention output for position 2

Each value vector has two coordinates, so their sum is also a two-value vector. This is the attention output for position 2. The displayed weights and result are rounded; the calculation uses the full-precision values. The other positions get their own outputs using their own queries and permitted keys and values.

Illustrative position 2 scores 1, 3, 2 are scaled, masked, converted to weights and used to combine values. The causal mask does not change this last-position row.
The calculation for position 2. Values are illustrative and rounded; the mask leaves this last-position row unchanged.

We can describe the same process for all positions at once:

A=softmax⁡(QK⊤dk+M)Z=AV\begin{aligned} A &= \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)\\ Z &= AV \end{aligned}

QQ and KK contain queries and keys; K⊤K^\top is the transpose of KK, arranging its keys as columns for multiplication. QK⊤QK^\top contains one score for each query–key pair. dkd_k is the query/key width, and MM is the additive causal mask. Softmax is applied across the key positions for each query, producing the weight matrix AA. Multiplying AA by the value matrix VV gives the head output ZZ.

For our three positions, AA is 3 × 3, VV is 3 × 2, and ZZ is 3 × 2: one output vector per position. The original Transformer paper describes scaled dot-product attention and multi-head attention.

The calculation we’ve followed is one attention head inside a transformer block. In this example, imagine the block’s attention module has just this one head: one set of projections creates queries, keys, and values, and the resulting weights combine the values. We’ve seen its output for position 2, but the same head calculates an output for every position.

A transformer block can also use multiple attention heads. They process the same input in parallel, each calculating its own output. How are those outputs combined?

3. From one head to multiple heads

So far, our single-head attention calculation has shown one way to combine information from the available positions. What happens if we give the same input to another head?

The second head follows the same steps, but it uses its own query, key, and value projection matrices. This means it can calculate different weights and produce a different output from the same input vectors.

Let’s add a second illustrative head. Its projection matrices are:

WQ2=[01100−110]WK2=[111001−10]WV2=[0110−1011]\begin{aligned} W_{Q2}&=\begin{bmatrix}0&1\\1&0\\0&-1\\1&0\end{bmatrix}\\[12pt] W_{K2}&=\begin{bmatrix}1&1\\1&0\\0&1\\-1&0\end{bmatrix}\\[12pt] W_{V2}&=\begin{bmatrix}0&1\\1&0\\-1&0\\1&1\end{bmatrix} \end{aligned}

These are new invented values, applied to the same input matrix XX (our illustrative input vectors). The second head calculates its own queries, keys, and values, then follows the same scoring and weighting steps. For position 2, the results are:

Illustrative head Weights for positions 0, 1, 2 Output for position 2
Head 1 [0.1400, 0.5760, 0.2840] [0.5641, 1.5760]
Head 2 [0.4717, 0.0565, 0.4717] [0.1131, 1.0000]

The second head’s invented projections produce a different mixture. That does not tell us that either head has a particular linguistic role.

How do we bring the results together? For each position, we concatenate the head outputs: place them side by side. For position 2, this gives approximately [0.5641, 1.5760, 0.1131, 1.0000].

We then apply an output projection: a matrix multiplication that transforms the combined head outputs into the attention module’s output. It can combine information across heads and produce the width needed by the rest of the block. In a trained model, the output projection matrix is learned during training and stays fixed during ordinary inference.

For this example, we apply the following illustrative output projection to the concatenated row:

WO=[100.500100.50.501000.501]W_O=\begin{bmatrix} 1&0&0.5&0\\ 0&1&0&0.5\\ 0.5&0&1&0\\ 0&0.5&0&1 \end{bmatrix}

For example, the first output value combines the concatenated row with the first column of WOW_O:

0.5641 × 1 + 1.5760 × 0 + 0.1131 × 0.5 + 1.0000 × 0 ≈ 0.6206

The full multiplication produces approximately [0.6206, 2.0760, 0.3951, 1.7880] for position 2. We calculate with unrounded values and round for display. Each head produces two values per position, so concatenating two heads gives four; the projection returns four values per position for this example.

In conventional multi-head attention (MHA), heads use separate query, key, and value projections. The heads’ calculations can run in parallel, then their results are combined. The projection parameters in an actual trained model are learned; ours were chosen for illustration.

4. Inspecting attention in SmolLM2

We’ve followed the arithmetic with invented values. Can we observe a change in a trained model?

Let’s run our two sentences through the pretrained SmolLM2-135M base model and inspect its first attention module. We’ll also look at the complete first block’s output to see how it differs from the attention module’s output.

The experiment uses checkpoint revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2 and runs inference on CPU. The model’s parameters stay fixed; the experiment does not generate text.

In this checkpoint, each token’s input embedding has 576 values. The vectors passed between its 30 transformer blocks also have 576 values per position. This size is called the model’s hidden width. Its configuration specifies nine query heads and three key/value heads. This is grouped-query attention (GQA): three query heads share each key/value head. Each query head still calculates its own attention weights and output. Our two-head example used separate key and value projections for each head; the real checkpoint uses sharing.

SmolLM2 has nine query heads in three groups. Each group of three query heads shares one key and value head.
SmolLM2’s nine query heads share three key/value heads in groups of three.

Our illustrative calculation showed how attention combines vectors, but it left out one detail: token order matters. “The server sends data to the client” and “the client sends data to the server” use the same words in a different order.

SmolLM2 accounts for position by applying rotary position processing to queries and keys before calculating scores. This is separate from the causal mask: position processing supplies information about where tokens occur, while the mask prevents a position from using later tokens.

Same token, different preceding text

Let’s return to our two sentences. The selected token ' port' has ID 2399 at zero-based position 5 in both. Its position and ID stay the same; the preceding tokens differ.

In the companion notebook, I ran both sentences through the trained SmolLM2 checkpoint and inspected the selected token at three stages: its input embedding, the first attention module’s output after its output projection, and the complete first block’s output. In sentence A, port refers to a place where ships enter. In sentence B, it refers to a network port used by a server application.

Stage Sentence A: first 4 values Sentence B: first 4 values
Input embedding [0.02942, -0.09668, 0.01099, 0.05298] [0.02942, -0.09668, 0.01099, 0.05298]
Attention-module output [0.02495, -0.01214, -0.00439, 0.00007] [0.03588, 0.00395, -0.02548, 0.00614]
First block output [-1.40992, 1.10573, -0.95352, 1.70307] [-1.39403, 1.25196, -0.90217, 1.95845]

To inspect the full comparison, see the companion notebook linked at the end of this article.

The table shows only the first four of each vector’s 576 values, rounded for display. The notebook compares the full vectors. In this saved CPU run, the complete input embeddings match, while the attention-module and first-block outputs differ.

The same token ID retrieves the same initial embedding. After the model processes the differing preceding text, the selected position has different later representations. This shows sensitivity to the supplied context; it does not prove that the model has resolved the word’s meaning. The block output includes more than attention, so we should keep it distinct from the attention-module output.

The notebook also makes a separate causal check. It changes yesterday to today after position 5 in the cargo-ship sentence and compares the earlier representations. They remain equal within the stated numerical tolerance in this run. The opening The also has matching first-block outputs across the two original sentences: it cannot use the later words that differ.

For an additional check, the notebook reconstructs the first attention module using the actual normalized input, projections, position processing, mask, and shared key/value heads. In the saved run, its reconstructed attention weights and projected output matched the captured module results with a maximum absolute difference of 0.0. That is a result for this run, not a guarantee of identical numbers on every platform.

5. Where attention fits

An attention head’s weighted sum is not yet the output passed to the next transformer block. In SmolLM2, the attention module combines the head outputs and applies an output projection. The block then uses residual additions, normalization, and a feed-forward network before producing its output:

A SmolLM2 transformer block normalizes input, runs the attention module, adds a residual, normalizes and applies the feed-forward network, then adds a second residual. The block output passes to the next block.
Attention produces an intermediate output; residual and feed-forward operations also contribute to the block output.

Normalization adjusts the scale of the values in each position’s vector before attention and feed-forward processing. A residual connection adds an earlier representation to the result of a calculation, keeping a path for that earlier representation. The feed-forward network transforms each position’s vector further, processing each position separately. Attention is the step in this block that combines information across permitted positions.

The next block receives the updated vectors and calculates its own queries, keys, and values. Blocks run in sequence. When the whole input is available, calculations across positions can run in parallel while the causal mask preserves the restriction on future tokens.

During token-by-token generation, a model can retain previously calculated keys and values in a KV cache and reuse them at subsequent steps. This avoids recomputing earlier states but requires storage; the notebook disables caching to inspect full-sequence passes. We’ll leave cache mechanics and other attention designs for a later article.

The practical takeaway is a boundary: an input embedding identifies a token, while the transformer builds representations using the context available to each position. Attention weights show one part of that mixing process; they are not a complete explanation of a model’s prediction. When comparing model representations, check which token position you’re inspecting, what context it can use, and whether the vector comes from the input, the attention module, or the complete block.


The companion notebook contains the calculations, model inspection, and full-vector comparisons. To run it yourself, follow the setup instructions.