How Attention Works in a Transformer
When people ask how attention works in a transformer, they usually want one thing: how can a model figure out that "it" in a sentence means "the animal" and not "the street"? The short answer is that attention lets every token look at every other token, score how relevant each one is, and then blend in information from the relevant ones, weighted by those scores. That one move, repeated across many layers, is what lets a transformer use context.
The problem attention solves
A word on its own is ambiguous. In "The animal didn't cross the street because it was too tired," the word "it" has no meaning until the model connects it to something earlier. Older sequence models read text one word at a time and squeezed everything seen so far into a single running summary, so distant words tended to get blurry. Attention removes that bottleneck: a token can reach directly back to any other token in the context and pull in what it needs.
Queries, keys and values
Each token starts as a vector of numbers (an embedding). The model multiplies that vector by three learned weight matrices to produce three new vectors for the token:
- Query: what this token is looking for.
- Key: what this token offers, a label other tokens can match against.
- Value: the actual information this token passes along if it is chosen.
A useful picture is a library search. Your query is the question in your head, each book's key is its catalogue entry, and the value is the content you read once you pick the book.
How attention works in a transformer, step by step
For one token, say "it", the computation goes in order:
- Score. Take the dot product of its query with the key of every token in the context. A higher score means a better match.
- Scale. Divide the scores by the square root of the key dimension. This keeps the numbers from growing so large that the next step becomes extreme.
- Softmax. Turn the scores into weights that are positive and add up to 1. A token with a strong match might get a large share, while irrelevant tokens get close to nothing.
- Blend. Multiply each token's value vector by its weight and add them up. The result is a new vector for "it" that now carries information mostly from "animal" (if the model has learned that pattern).
Every token does this at the same time, so the whole thing is a handful of matrix multiplications, which is why it runs so well on GPUs.
In models that generate text, a causal mask is applied before the softmax. It blocks each token from looking at tokens that come after it, so the model cannot cheat by peeking at the word it is supposed to predict.
Multi-head attention and stacking
One set of scores can only capture one kind of relationship. So a transformer runs several attention heads in parallel, each with its own query, key and value matrices. Different heads are free to learn different patterns. Researchers have found heads that appear to track things like which noun a pronoun refers to, though what any single head does is an empirical question, not something designed in. The heads' outputs are concatenated and mixed with another learned matrix.
Then the whole block is stacked. Each layer pairs attention with a small feed-forward network, and the output of one layer becomes the input to the next. Early layers tend to capture simpler relationships, and later ones build on them. The mix of attention across tokens and the feed-forward step on each token is the repeating unit of the transformer. For the bigger picture of how those layers become a chatbot, see how large language models like ChatGPT work.
The cost of looking at everything
Because every token is scored against every other token, the work grows with the square of the context length. Double the text and the attention scores quadruple. That is why long context windows are expensive, and why a lot of engineering effort goes into making attention cheaper. Some models also split their feed-forward layers into specialists, as in mixture-of-experts routing.
Quick recap
- Attention lets each token pull in information from the other tokens in its context.
- Each token makes a query, a key and a value; query-key matches decide the weights.
- The steps are score, scale, softmax, then a weighted sum of values.
- Multiple heads learn different relationships in parallel, and layers stack on top of each other.
- Cost grows with the square of the context length.