Attention
Attention lets each token gather information from the others, taking more from the relevant ones. Its query is compared with every key by a dot product, softmax turns the scores into weights that add to 1, and the output is the weighted average of the values.
What the symbols mean
- Queries
One row per token: what that token is looking for.
- Keys
One row per token: what that token offers, as a label to match against.
- Values
One row per token: the content it hands over when attended to.
- Key dimension
How many numbers are in each query and key.
What the symbols mean
- Score
How well token i's query matches token j's key.
- Attention weight
The softmax of the scores in row i: positive and adding to 1 over j.
- Query of token i
Row i of Q.
- Key of token j
Row j of K.
What the symbols mean
- Output for token i
A weighted average of all the values.
- Value of token j
Row j of V.
Explanation
Attention is simply a way for each word (or image patch, or any token) to gather information from the others, taking more from the ones that matter to it. In "the trophy didn't fit in the suitcase because it was too big," the word "it" needs to pull in meaning from "trophy." The machinery is a soft lookup with three roles: a query (what this token is looking for), a key (what each token offers, like a label on a drawer) and a value (what's inside the drawer). The formula looks like a lot, but it's three moves you've already seen: dot products to score how well the query matches each key, softmax to turn the scores into weights that add to 1, and a weighted average of the values. Bear with the matrices; they just do all the tokens at once.
A soft dictionary. A Python dictionary does a hard lookup: the query must equal a key exactly, and you get that one value. Attention does a soft one. The query is compared with every key, and you get a blend of all the values, weighted by how well each key matched. If one key matches far better than the rest, the softmax puts nearly all the weight on it and the lookup is almost hard. If several match, you get a mix. Because every step is smooth, gradients flow through it and the whole thing can be trained.
Where Q, K and V come from. In self-attention, each token starts as an embedding (a row of ), and three learned matrices make its three roles: , , , each a layer like those in Layers as Matrix Multiplication. The scores for every pair of tokens come out at once as , an matrix whose entry is . Softmax runs along each row (over the keys), and multiplying by takes each row's weighted average of the values.
Why divide by . Suppose the entries of a query and a key are independent with mean 0 and variance 1. Each product then has mean 0 and variance . The dot product adds of these independent terms, and variances of independent terms add (see Expected Value), so has variance and standard deviation . With , raw scores routinely land around or . Feed numbers that spread out into softmax and it saturates: one weight is nearly 1, the rest nearly 0, and the gradients through it all but vanish (the same trouble as in Vanishing and Exploding Gradients). Dividing by brings the standard deviation back to 1, whatever the dimension.
The cost grows like . Every token scores every other token, so a sequence of tokens makes scores, each a dot product of multiplications: about operations, and an table to store. Double the context and the work quadruples (see Big-O Notation). That's why longer context windows are expensive, and why so much research goes into cheaper approximations.
Two more facts. Attention by itself ignores order: shuffle the tokens and each output just moves with its token, because a weighted sum doesn't care what order you add in. So models add position information to the embeddings. And real models run several attention "heads" side by side, each with its own , , , so different heads can track different relationships. You'll also see attention again in the next unit: it's message passing (as in Graph Neural Networks) on a graph where every token connects to every other and the edge weights are computed on the fly.
A common mistake. It's tempting to think the attention weights are parameters the model learned. They aren't. What's learned are , and ; the weights are recomputed from scratch for every input, which is exactly what lets "it" attend to "trophy" in one sentence and to "suitcase" in another. Also, the softmax runs over the keys, so each row of weights adds to 1; the columns don't have to.
There's an animation further down where a query turns past four keys and you can watch the weights shift.
See it
Worked examples
One query attends over three tokens with keys , , and values , , . Compute the attention output.
- 1
Score the first key with a dot product: .
A model with key dimension processes a 1000-token input. How many multiplications does one attention head spend on scores, and how does that change at 4000 tokens?
- 1
Every token's query is dotted with every token's key, so there are scores.
Practice
Type your answer and check it. Solve them all to complete the lesson.
In scaled dot-product attention with , a query attends over two keys, and . What weight does key 1 get? Give 4 decimal places.
Attention weights over three tokens are , and , and their (one-number) values are , and . What is the output?
Query and key entries are independent with mean 0 and variance 1, and . What is the standard deviation of the raw dot product ?
A chat model's context grows from 2000 tokens to 8000. By what factor does the number of attention scores per head grow?
A document assistant runs attention over 4096 tokens and stores one head's score matrix as 2-byte numbers. How many mebibytes (MiB, bytes) does that one matrix take?
Which statement about the attention weights in a trained model is true?
With , a query's raw dot products with two keys are and . What weight does the first key get after the usual scaling? Give 4 decimal places. (Compare with the unscaled softmax.)
For a sequence of tokens with and both , what shape is ?
The hardest one here. Get it, and you've got this lesson.
Two tokens have embeddings and . Self-attention uses , and (rows as tokens, so and so on), with . Find the output for token 1. Give 4 decimal places for each entry.
Where it's used
Attention is the core of the transformer, the architecture behind chat assistants, machine translation, code completion and speech recognition, and it's used on image patches and protein sequences too. The cost shapes the products you use: it's why a chatbot has a maximum context length, why long documents cost more to process, and why engineers count the memory of score matrices as carefully as the weights themselves.