1. Who does “it” refer to?
Compare these sentences:
- “The kitten didn’t cross the road because it was too tired.”
- “The kitten didn’t cross the road because it was too congested.”
The adjective changes the likely interpretation. “Tired” suggests the kitten; “congested” suggests the road. Reading the whole sentence lets us connect the pronoun with information elsewhere in the text.
This motivates a question: could a network choose which other representations are relevant to the position it is processing? Attention provides a way to calculate such a selection and combine the selected content.
These examples illustrate a linguistic intuition, not a guarantee that one attention layer will resolve every ambiguous pronoun.
2. Beyond a single recurrent state
RNNs and LSTMs update a fixed-size state as they read. A prediction based only on the current state must use the historical information carried through that state.
Gates improve information flow, but do not turn the state into a complete record of every earlier token. Another approach is to retain representations at separate positions and let a query access them directly.
Attention can also be combined with recurrent networks; it is not restricted to Transformers. In self-attention, positions within the same sequence exchange information through their queries, keys and values.
3. Score, normalise, mix
The basic attention computation has three ingredients:
- Score: calculate compatibility between a query and the available keys.
- Normalise: turn the scores into a distribution of weights, often using Softmax.
- Mix: sum the value vectors using those weights.
For a simple dot-product score:
A dot product depends on both direction and length. It is not the same as cosine similarity, and a large dot product is not automatically evidence of semantic similarity. Learned projections make this score useful for the task.
Softmax gives:
Then the output is:
The weights are a plan for selecting content; the weighted sum actually transfers that content into the output representation. A high attention weight alone does not prove that the model has understood a word's meaning or explain its complete decision.
4. One input, three roles: Q, K and V
Matching and carrying content are different jobs. A useful analogy is a library:
- Query: the request used to find relevant material.
- Key: the matching representation associated with an item.
- Value: the content taken from that item once its weight is known.
Instead of requiring one vector to perform all three jobs unchanged, the model learns separate projections.
With input representations as rows of :
Query
The matching request
Key
The representation used for matching
Value
The content to combine
A query is matched against keys; the resulting weights combine values, not queries or keys. The projection matrices are trained with the rest of the network. Individual coordinates need not correspond to human-readable categories such as “animal” or “subject”.
The inputs can be embeddings in an initial layer or already contextual representations in a later layer. Self-attention uses the same sequence as the source of all three roles. In cross-attention, queries and key-value pairs can come from different sequences.
5. Compute every query in one matrix operation
Stack each position's query into a row of , and do the same for and . For self-attention positions:
The score matrix is:
Its entry is the dot product of query with key . A row asks where one query should look; a column identifies one key position. Raw entries are scores, not percentages.
Scale the scores, normalise each row and combine values:
Score → scale → normalise each row → mix values
Why divide by the square root of key dimension?
Under a simple assumption that query and key components are independent, zero-mean and unit-variance, their dot product has variance . Dividing by gives unit variance under those assumptions.
Large score differences can push Softmax towards a nearly one-hot distribution with small derivatives. Scaling helps control that effect. It does not guarantee a particular score range or prevent saturation in every trained model.
There is no universal requirement that ; that is one possible head dimension. Our numerical example uses .
Masking determines which positions are available
Add a mask before Softmax:
Allowed entries of are zero; disallowed entries are represented by negative infinity so their weights become zero. Each query must have at least one allowed key.
Bidirectional attention can use positions on both sides of a token. Causal attention excludes future positions, so a language model cannot peek at the answer it should predict.
The sentence examples use the later adjective to interpret “it”. They are bidirectional illustrations. A causal query at “it” cannot yet see “tired” or “congested”.
Shorter paths come with a cost
For an allowed pair of positions, attention can transfer information directly rather than pass it through every intermediate recurrent state. That shorter path does not guarantee perfect recall.
Given all inputs to a layer, multiple query rows can be computed together. Autoregressive generation still produces new tokens sequentially. Dense attention also involves an score table, with quadratic pairwise work in sequence length.
6. Calculate a two-dimensional example
Take three teaching positions: kitten, tired and it. These are a shortened, reordered list for arithmetic, not the original sentence's tokenisation.
Choose projected vectors by hand:
The value coordinates are deliberately easy to read in this example. They are not measured semantic features from a trained model.
Step 1: dot-product scores
For the query at “it”:
Both the kitten key and the “it” key point along the first axis. The kitten key is longer, producing a much larger score. This is why direction alone is not enough to explain the result.
Step 2: scale the scores
Since :
Step 3: normalise with Softmax
Using the full-precision scaled scores gives:
About 70.3% of the weight goes to kitten, with about 14.8% each for the other two positions. The unrounded weights sum to one; rounded percentages need not sum to exactly 100%.
| Query ↓ / Key → | kitten | tired | it |
|---|---|---|---|
| kitten | 36.36% | 34.85% | 28.79% |
| tired | 23.29% | 56.77% | 19.94% |
| it | 70.32% | 14.84% | 14.84% |
The table shows every query's normalised weight row, calculated from the same projected vectors. It is not the raw table.
Step 4: combine values
The output contains mostly the first teaching coordinate, with some of the second. That is the result of our chosen numbers—not proof that a model learned “it means a tired kitten”.
Query vector: [2, 0.2]
kitten: dot product 2.400 · scaled score 1.697 · weight 70.32%
tired: dot product 0.200 · scaled score 0.141 · weight 14.84%
it: dot product 0.200 · scaled score 0.141 · weight 14.84%
Weight sum: 1.000000
Weighted output: [0.7774, 0.2226]
Actual arithmetic on hand-chosen vectors. The three positions are a reordered teaching list, not a complete sentence. Masked scores are excluded before Softmax; displayed scores show their values before masking.
Choose another query and inspect its scores, weights and output. Disable scaling to see a sharper distribution for the “it” query. Enable the causal mask and choose the first position: only its own key remains allowed, so its weight becomes one and its output equals its value vector.
A complete Transformer applies an output projection and combines attention with residual connections, normalisation and feedforward operations. Attention is one part of how contextual representations are built; it does not simply overwrite every original vector with a linguistic definition.
7. Inspect contextual weight rows
Return to the two sentence scenarios. Select a word to inspect a row, then switch the adjective and compare the row for “it”.
“The kitten didn’t cross the road because it was too tired.”
Preset query: “it”
Weight sum: 1.000000
Hand-written contextual scores normalised by Softmax. This is a bidirectional illustration, not a trained language model or proof of pronoun resolution. It may use the later adjective; a causal query at “it” cannot see that adjective.
The scores in this panel are manually chosen contextual presets. Softmax actually normalises them, but the panel does not train or run a language model. For other words, its simple rows just illustrate selection and normalisation.
There is another useful limitation: with a single initial-layer query and keys independently projected from unchanged token embeddings, changing a later adjective does not automatically change the relative scores for the unchanged kitten and road keys. Context can affect representations through earlier layers or other processing; our presets assume those contextual scores already exist.
8. What you have discovered
Attention selects and combines value content using query-key compatibility.
- Queries and keys produce matching scores; values supply the combined content.
- Scaling by helps control dot-product magnitude.
- Row-wise Softmax gives weights over the allowed keys.
- Multiplication by turns those weights into contextual output vectors.
- Masks restrict access; causal queries cannot use future positions.
- Parallel query computation and shorter paths are useful, but do not guarantee understanding, unlimited memory or cost-free long contexts.
The next lesson introduces multi-head attention and several learned representation subspaces.