Rúben GalvãoThe Rabbit Hole

The Rabbit Hole / AI and machine learning / Language models / Inside a language model

Attention, from scratch

Self-attention lets the same token gather different clues from its context. How does a model tell a living rabbit from a chocolate one?

Which rabbit?

The embedding table gives “rabbit” the same starting vector in every sentence. But a living rabbit and a chocolate rabbit are very different things.

The same word in two sentencesIn “in the burrow slept an old rabbit”, rabbit means a living animal. In “from chocolate she made a rabbit”, it means a chocolate treat. The token starts with the same vector; earlier tokens supply the context.intheburrowsleptanoldrabbit0.21 −0.54 0.88 0.07 0.63 −0.12→ a living animalfromchocolateshemadearabbit0.21 −0.54 0.88 0.07 0.63 −0.12→ a chocolate treat
What to notice: Same token, same starting vector; different context. The words around “rabbit” tell us which meaning fits.

We can read the surrounding words and work out which rabbit is meant. The embedding lookup cannot: it returns the same starting vector either way.

What would let that vector pick up something from the sentence?

An old rabbit

We have found the animal. Now take “the old rabbit sleeps”. There is something else to learn about this rabbit: it is old.

Imagine “rabbit” asking the other tokens: “Is there an adjective?”

“Old” could reply: “I’m an adjective.”

From rabbit to old rabbitColoured columns represent the token representations of the, old, rabbit and sleeps. An arrow shows the information we want old to contribute to rabbit. The columns stay unchanged. Underneath, an arrow shows the intended change in meaning: rabbit becomes old rabbit.theEarlier context is dimmed; outlined columns are current.oldEarlier context is dimmed; outlined columns are current.rabbitEarlier context is dimmed; outlined columns are current.Current token computation.sleepsEarlier context is dimmed; outlined columns are current.“rabbit”old rabbittoken on its ownmeaning we want to capture7,168
Information from ‘old’ enriches the representation of ‘rabbit’.

But who decides what to ask? Writing a rule for “old” and “rabbit” would only solve this one example.

We need the questions themselves to be learned.

Let a question grow from the token

The rabbit’s vector is what the network has to work with. A table of learned weights can turn it into another vector, representing the question the token is asking.

A question needs an answer. “Old” could answer “I’m an adjective.”

A second table of learned weights turns each token’s vector into a vector representing its answer. We can then compare the question with each answer.

Learn two useful views of each tokenA tall token-representation column with many cells for rabbit passes through learned query weights to become a six-cell query column. A tall column for old passes through different key weights to become a key column. All tokens use both conversions.rabbitEarlier context is dimmed; outlined columns are current.Current token computation.Wq · learned weightsqueryEarlier context is dimmed; outlined columns are current.Current token computation.Is there an adjective?oldEarlier context is dimmed; outlined columns are current.Current token computation.Wk · learned weightskeyEarlier context is dimmed; outlined columns are current.Current token computation.I’m an adjective.Every token makes both a query and a key7,1681927,1681927,1681927,168192
Blue/orange: token data. Violet: learned weights.

The asking vector is a query. The vector it matches against is a key.

These are calculated in parallel. “Old” does not wait to hear “rabbit”’s question: each token makes its query and key from its own vector.

All four tokens use those same two tables.

Every token makes a query and a keyFour coloured token-representation columns for the, old, rabbit and sleeps pass through shared query weights to produce four query columns, and through shared key weights to produce four key columns. Each token therefore has both a question and an answer representation.Token vectorstheoldrabbitsleepsEarlier context is dimmed; outlined columns are current.Current token computation.Query weightsQuestions (queries)theoldrabbitsleepsEarlier context is dimmed; outlined columns are current.Current token computation.Key weightsAnswers (keys)theoldrabbitsleepsEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.One question and one answer for each token7,1681927,168192CLCLCL7,168192192
Every input column produces a question and an answer column. All tokens use the same query weights and the same key weights.

The two tables are trained together. When a prediction goes wrong, training adjusts both, so the questions and answers learn to match in useful ways—without us writing the language rules.

How well do they match?

Now we have two lists. Does the question from “rabbit” match what “old” is offering?

An array of numbers can be viewed as a vector. With just two numbers, we can draw it: one coordinate goes across, the other goes up or down. Together they give us an arrow.

The same calculation works with longer vectors.

When do two vectors match?

Interactive

Drag the blue arrow’s tip. The green query stays fixed. Watch how much of the key points along it.

Query →Key (drag the tip)Highlighted line: the key’s part along the query

Dot product +0.71

Some of the key points along the query, giving a positive score.

Connect the picture to the calculation

Multiply the horizontal coordinates, multiply the vertical coordinates, then add the two results: q₁k₁ + q₂k₂.

The dot product measures how much the vectors point together. With lengths fixed, alignment gives a positive score; perpendicular arrows give zero; opposing arrows give a negative score.

Put the matches on a map

“Rabbit” has a question. How well does each token answer it?

Take the dot product of “rabbit”’s query with each token’s key. The four scores form a row: one score for each possible answer.

Now do that for every token’s question. Stack the rows and we get an attention map: questions down the side, answers across the top.

Each cell tells us how well that column’s token answers that row’s question.

One query, four different matches

Interactive
Keys →Queries ↓theoldrabbitsleepsthe1.4the query, the key: score 1.4-0.4the query, old key: score -0.40.2the query, rabbit key: score 0.20.7the query, sleeps key: score 0.7old0.3old query, the key: score 0.31.1old query, old key: score 1.12.4old query, rabbit key: score 2.4-0.8old query, sleeps key: score -0.8rabbit-0.6rabbit query, the key: score -0.62.5rabbit query, old key: score 2.50.4rabbit query, rabbit key: score 0.41.2rabbit query, sleeps key: score 1.2sleeps0.1sleeps query, the key: score 0.10.5sleeps query, old key: score 0.52.8sleeps query, rabbit key: score 2.80.8sleeps query, sleeps key: score 0.8Brighter = higher match scoreCLCL

Follow the highlighted rabbit row across the keys. Its matches have different scores.

“Old” is the strongest match for “rabbit”’s question. We want it to contribute more information—but how much more?

Multiplying the query and key matrices gives us the dot products for every question–answer pair.

Then we apply softmax so each row’s scores become attention weights that add up to one.

Build the map with a matrix multiplication

Interactive
Transposed query table times key tableQueriesKeys0.4170.348-0.184-0.2800.3740.673-0.143-0.0260.9020.0860.3460.1930.769-0.0590.2400.406-0.4260.025-0.272-0.206-0.2720.7700.1440.4420.1283.582-1.7532.7231.209-1.023-1.4550.073-0.3883.7473.580-1.913-1.3073.9396.0492.0552.199-1.8652.793-1.0072.5190.5574.5171.716×Query × key scoresHighlighted row × highlighted column → one output cell

First turn query token-columns into rows. Keys stay in columns above the map.

Each output row compares one query with all the keys.

Read each row as one token’s attention to the others.

In the rabbit row, old gets about 69% of the attention—the brightest cell. The remaining attention is shared between the, rabbit and sleeps.

These weights decide how much information to take from each token. What information can they send?

We know where to look. What do we take?

“Old” needs something to send. Another learned set of weights produces its value vector, the information attention can collect from that position.

From a token vector to its value vectorA tall token vector with many cells for old is multiplied by a learned matrix of value weights, producing a six-cell value vector. All tokens use the same value-weight matrix.“old”Earlier context is dimmed; outlined columns are current.Current token computation.Wv · value weightsValue vectorEarlier context is dimmed; outlined columns are current.Current token computation.The same value weights are used for every token7,1681287,168128
Another learned table turns the token’s vector into the value it can contribute.

In our attention map, rabbit gives old about 69% of its attention.

Gather information, in the proportions we chose

Interactive

Read the “rabbit” row of our attention map. Each cell supplies the weight for the value underneath.

Our attention mapKeys →Queries ↓theoldrabbitsleepsthe0.510.080.150.25old0.090.190.700.03rabbit0.030.690.090.19sleeps0.050.080.770.10the0.03× valueold0.69× valuerabbit0.09× valuesleeps0.19× valueValue vectorsInformation collected for “rabbit”CLCL128128128128128

The weights above are the calculated attention to each token.

Multiplying the attention map by the value matrix collects information for every token at once.

The weighted sum is a matrix multiplication

Interactive
Attention weights times transposed value tableAttention weightsValues0.5090.0840.1530.2530.0850.1900.6960.0280.0310.6940.0850.1890.0520.0770.7680.1040.2500.7000.2000.4000.6000.3000.8000.3000.9000.5500.2000.7000.2000.8000.3000.5000.4500.6000.5500.1500.7000.4000.8000.250×Collected value rowsHighlighted row × highlighted column → one output cell

First turn the value token-columns into rows, so the tokens line up with the attention weights.

Each output row is the collected vector for one query.

No peeking

You may have noticed that every token gets to answer every question. Even sleeps can answer rabbit, although it comes later in the sentence.

But in the previous article, we saw why later tokens must not affect earlier ones. They should not be allowed to answer those earlier questions.

How do we stop them? Mask the attention map. Set the scores for later tokens to −∞ before applying softmax. Softmax turns those scores into zero attention.

What changes when we block future tokens?

Interactive

1. Query–key scores

Keys →Queries ↓theoldrabbitsleepsthe1.4the query, the key: weight 1.4-0.4the query, old key: weight -0.40.2the query, rabbit key: weight 0.20.7the query, sleeps key: weight 0.7old0.3old query, the key: weight 0.31.1old query, old key: weight 1.12.4old query, rabbit key: weight 2.4-0.8old query, sleeps key: weight -0.8rabbit-0.6rabbit query, the key: weight -0.62.5rabbit query, old key: weight 2.50.4rabbit query, rabbit key: weight 0.41.2rabbit query, sleeps key: weight 1.2sleeps0.1sleeps query, the key: weight 0.10.5sleeps query, old key: weight 0.52.8sleeps query, rabbit key: weight 2.80.8sleeps query, sleeps key: weight 0.8Brighter = higher match scoreCLCL

Follow the highlighted rabbit row across the keys. Its matches have different scores.

In the rabbit row, sleeps goes from a score to −∞, then to 0 after softmax. Its value cannot contribute to rabbit.

Add what we learned to “rabbit”

We now have information collected from the other tokens. How do we add it to “rabbit”’s vector?

There is a size mismatch: the collected vector is shorter than “rabbit”’s original vector. We cannot add them coordinate by coordinate yet.

A learned matrix, Wₒ, converts the collected information into a vector the same size as “rabbit”’s. This is the output projection.

Make the collected information fit the original tokenThe shorter vector collected for rabbit passes through a learned output matrix, Wₒ. It produces an update the same size as rabbit’s original vector. Adding the two vectors enriches rabbit’s representation.CollectedWₒLearned weightsUpdateEarlier context is dimmed; outlined columns are current.Coordinate 1: 0.716Coordinate 2: 0.368Coordinate 3: 0.810Coordinate 4: 0.539Coordinate 5: 0.242Coordinate 6: 0.674Current token computation.Earlier context is dimmed; outlined columns are current.Coordinate 1: 0.256Coordinate 2: 1.007Coordinate 3: 0.134Coordinate 4: 0.252Coordinate 5: 0.610Coordinate 6: -0.194Coordinate 7: 0.871Coordinate 8: 0.579Coordinate 9: 0.544Coordinate 10: -1.183Coordinate 11: -0.272Coordinate 12: -0.531Coordinate 13: 0.046Coordinate 14: 0.825Coordinate 15: 0.290Coordinate 16: 0.099Coordinate 17: -0.749Coordinate 18: -1.265Current token computation.Shorter vectorSame size as “rabbit”Original “rabbit”Earlier context is dimmed; outlined columns are current.Current token computation.UpdateEarlier context is dimmed; outlined columns are current.Current token computation.Enriched “rabbit”Earlier context is dimmed; outlined columns are current.Current token computation.+=Add corresponding values1287,1681287,1687,1687,1687,168
Expand the collected information, then add it to the original token vector.

Now we can add the two vectors. “Rabbit” keeps its existing representation and gains information from the tokens it attended to—the residual addition we saw earlier.

Zoom out: the original token vectors travel along the residual stream. Attention branches off, gathers information, and adds its update back to that stream.

The whole attention block and the residual streamThe residual stream runs uninterrupted down the left. A branch reads its token vectors. Learned Wq, Wk and Wv matrices produce queries, keys and values. Query–key dot products produce scores; masking sets future scores to negative infinity; softmax produces the attention map. Its weights collect the values. The output projection Wo expands the collected information. The update is added back to the residual stream.Residual streamToken representationsEarlier context is dimmed; outlined columns are current.Current token computation.7,168192WqEarlier context is dimmed; outlined columns are current.Current token computation.Queries7,168192WkEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.Keys7,168128WvEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.ValuesDot productsMask: −∞SoftmaxAttention mapWeighted sumof valuesEarlier context is dimmed; outlined columns are current.Current token computation.Collected1287,168WₒUpdate+Enriched token representationsCLCLCL7,168192192128128
Attention reads the token representations, collects information, and adds its update to the residual stream.

One question is not enough

We can run attention several times with different learned projections. Each version is an attention head.

One head may focus on “old”; another on “the”. The heads can learn different, overlapping patterns without being assigned neat jobs.

The same attention calculation with more heads behind itThe residual stream runs uninterrupted down the left. A branch reads its token vectors. Learned Wq, Wk and Wv matrices produce queries, keys and values. Query–key dot products produce scores; masking sets future scores to negative infinity; softmax produces the attention map. Its weights collect the values. Three more boxes appear behind this calculation. Each head uses its own slice of the output projection Wo, inside its box. The projected head updates are summed before the residual addition. The update is added back to the residual stream.128Residual streamToken representationsEarlier context is dimmed; outlined columns are current.Current token computation.7,168192WqEarlier context is dimmed; outlined columns are current.Current token computation.Queries7,168192WkEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.Keys7,168128WvEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.ValuesDot productsMask: −∞SoftmaxAttention mapWeighted sumof valuesEarlier context is dimmed; outlined columns are current.Current token computation.Collected1287,168WₒOutput projection+Add head updatesUpdate+Enriched token representationsCLCLCL7,168192192128128
Each head projects its collected information back to the token width. Add their updates, then add the result to the residual stream.

This is called multi-head attention.

Explore a small trained model

This small trained model has its own vocabulary.

Pick “rabbit” in “the old rabbit sleeps”, then press Next step. Follow its query through to the weighted sum of values.

Attention on a real, tiny model

Interactive
Attention head
Pick a token

Loading the tiny model (about 50 KB)…

One token’s question, compared with every token’s key
TokenKeyScoreWeightValue × weight

The attention map

Looks most at
·
Row adds up to
·
Cells in the map
·

Try the other heads, and turn the mask off. Each head was trained to look for something different.

Show the calculation, line by lineHide the calculation
Show the words the tiny model knowsHide the words

This is real attention, not an illustration. The numbers come from a small transformer (tokens of 64 numbers, four heads of 16, trained on a toy language of about 60 words: animals, people and things doing simple things) and we show its first layer. It is far smaller than the models in this series, and its queries and keys are 16 numbers long where the reference model’s are 128. The model’s data is about 50 KB (compressed) and is fetched only when this widget nears the screen.

The small transformer learned from training examples. Its token vectors have 64 numbers; each head uses 16.

Try two changes:

  • Switch heads. Do they look at the same tokens?
  • Turn the mask off. Which extra matches become available?

The second experiment changes the calculation, not the training. This model was never trained to look ahead.

What happens to a longer sentence?

Every extra token adds a row and a column. Double the context, and the map grows fourfold. Each head needs its own map.

Watch the attention map grow

Interactive
One head
All 128 heads

Double the context → four times the map.

At long contexts, attention becomes one of the model’s biggest bottlenecks. Other articles explore ways to make it faster and use less memory.

Sources and assumptions

The matrix animations use six-coordinate queries and keys, chosen to reproduce the score map exactly. The query rows start from seeded random values and are orthonormalized, with all six coordinates populated; the key table is calculated from those rows so division by √6 restores the displayed scores. The value animation uses the same six coordinates as the gathering diagram and the same row-wise softmax weights.

The small interactive model has trained weights; rounded softmax scores and the question/key metaphors are teaching aids. Positions, normalisation and the feed-forward sublayer are omitted from this attention-only diagram.

The stacked-head diagram shows each head’s slice of Wₒ inside its box, then sums the projected updates. This is equivalent to concatenating the head outputs and multiplying by the full Wₒ.

The compact formula. With tokens written as rows, a head computes

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}+M\right)V

Here MM supplies the causal mask. The diagrams draw tokens as columns instead, so their projections multiply on the left: Q=WQXQ=W_QX, and likewise for keys and values.

Attention predates the Transformer: Bahdanau, Cho and Bengio used it in recurrent translation in 2014. Vaswani and colleagues introduced the Transformer in 2017. The tiny experiment also adds learned position information; this article isolates attention rather than the whole layer.

← Browse all subjectsBack to the beginning ↑