Skip to content

Attention

Let each token ask a question, match it against every key, and blend the values it needs

Quick recap
  • A query is compared with every key by a dot product.
  • Scaling and softmax turn the scores into weights that sum to 1.
  • The output is a weighted sum of value vectors, so context can change a token’s representation.

This lesson follows Predicting the Next Token and leads into The Transformer. The vector geometry lives in Linear Algebra. You can also open the Attention Playground.

1. The fixed-vector problem

In the cat sat, what does sat need from cat? It needs to know who sat. A fixed embedding for sat cannot depend on the sentence. The same vector would have to serve every use of the word.

Attention solves this by letting each token build a new vector from the other tokens. The token asks a question, compares it with the other tokens’ labels, and takes a weighted blend of their contents. The blend is different in every context.

Before reading the formulas, predict: if sat is most interested in cat, what should happen to the output vector? It should move toward the representation of cat — but only by the amount the weights allow.

2. Query, key, value

Each token produces three vectors by multiplying its input with learned matrices. A useful analogy is a filing cabinet:

  • Query — the question the current token is asking.
  • Key — a label that says what each token offers.
  • Value — the content that gets mixed into the output.

The query and key are used to compute weights. The value is what the weights actually combine. A token’s query is compared with every key, including its own.

3. Scores and scaling

The raw score for key j is the dot product of the query with that key. A large positive score means the query and key point in similar directions:

Raw score

The score is divided by √d_k, where d_k is the key dimension. Without scaling, dot products tend to grow with dimension, and softmax saturates: one weight becomes almost 1 and the rest almost 0.

Scaled score

In the two-dimensional example, the scale is √2 ≈ 1.414. The scores (0, 1, 0.5) become (0, 0.707, 0.354). Scaling does not change the order; it changes how strongly softmax separates the candidates.

4. Softmax and mixing

Softmax turns the scaled scores into non-negative weights that sum to 1:

Attention weights

The output is the weighted sum of the value vectors. A token with a large weight contributes more of its value:

Weighted sum

The weights are often called “attention,” but they are not a complete explanation of the model. They are one layer’s normalized scores, and later layers can use the mixed vector in complicated ways.

Try it

Are the raw q · k scores the attention weights?

5. Worked example

Use a two-dimensional query and three keys. The values are also two-dimensional, so the weighted sum is easy to check by hand.

Query and first key
Other keys

The raw scores are 0, 1, and 0.5. After scaling by √2 and applying softmax:

Weights

The output is the weighted sum of the values (0, 0), (1, 1), and (0, 1):

Output

Worked example: every number in the attention row

tokenkeyscorescore / √2weightvalueweight × value
the(0, 1)0.000.0000.225(0, 0)(0.000, 0.000)
cat(1, 0.5)1.000.7070.456(1, 1)(0.456, 0.456)
sat(0.5, -0.5)0.500.3540.320(0, 1)(0.000, 0.320)
output1.000(0.456, 0.775)

The weights are 0.225, 0.456, and 0.320. The largest weight belongs to cat, so the output is pulled toward cat’s value (1, 1). It is not equal to that value, because the other tokens still contribute.

Note the two different roles: the score for cat is 1, the scaled score is 0.707, and the weight is 0.456. Mixing up those three quantities is the most common attention mistake.

The query used here is (1, 0), which stands in for the token sat. The playground lets you change the vectors and watch the whole row respond.

6. Masks and heads

A language model must not read the future. A causal mask sets the score for every key after the current position to −∞ before softmax, so its weight becomes 0:

Causal mask

Masking changes the normalization: the visible weights are renormalized to sum to 1. Token 1 can see only itself, token 2 can see tokens 1 and 2, and so on. This is why a decoder can be trained on a whole sentence in parallel without leaking the next token.

Multi-head attention runs several attention operations in parallel with different learned projections. One head may track syntax, another may track a repeated entity, and another may focus on nearby tokens. The heads are concatenated and projected back to the model dimension.

Open the Attention Playground and turn on the causal mask. The future keys become unavailable, and the remaining weights renormalize.

7. Where it fails

Attention has no built-in sense of order. If you permute the tokens, the scores permute with them; the operation itself does not know which token came first. Transformers add positional information separately.

Full attention compares every token with every other token, which costs O(n²d) time and memory in the sequence length. Long contexts are expensive, and a long context does not guarantee that the model uses the right part of it.

Quadratic cost

Attention weights are also not a faithful explanation. A high weight means this layer moved more of that value into the mix, not that the model’s final answer is “because of” that token. Later layers, residual connections, and the feed-forward network all matter.

The next lesson puts attention inside a full transformer block, with residuals, layer norm, and a feed-forward network.

Next on the recommended path: The Transformer

8. Going deeper

The full scaled dot-product attention for a matrix of queries is written as softmax(QKᵀ / √d_k)V. The row-wise softmax is the same operation we did by hand; the matrix form just processes every query at once.

Efficient attention implementations such as FlashAttention change the memory access pattern, not the mathematics. Linear attention and sparse attention change the mathematics to avoid the full n×n matrix, at the cost of a different inductive bias.

Positional information can be added to the input, multiplied into the query and key (RoPE), or learned as a relative bias. The choice affects how well a model extrapolates to longer sequences than it saw during training.

9. Practice

Try it

Why divide the scores by √d_k instead of d_k?

Try it

With a causal mask, how many keys can the fourth token see in a four-token sequence?

Try it

A head puts 90% of its weight on one token. Does that prove the model’s answer depends on that token?

10. Resources

The MIT chapter derives attention and the transformer. The Illustrated Transformer gives the visual tour of queries, keys, values, and multi-head attention. Both links were opened and checked for this lesson.

Continue the track

Open the playground for this topic

Attention Playground →

Pick a query token, move its two-dimensional query and key vectors, and watch scores become softmax weights and an output vector.

The mathematics behind this topic: Linear algebra.

All Machine Learning lessons

Site soundtrack