Attention in one diagram
Attention lets each token pull information from the tokens before it. Queries, keys and values in one picture, a worked example, and what it costs.
Feed a model "The laptop arrived. It was broken." and it treats "It" as the laptop, not the arrival. The model reads that sentence as tokens, one vector per token. The embedding the model starts from for "It" is the same in every sentence, so nothing in it says laptop. Something has to let "It" look back at the words before it and pull in the right one. That something is attention, and once you can picture it, a lot of LLM behaviour and cost stops being mysterious.
The short answer
Attention lets every token look at itself and the tokens before it and take in what it needs. Each token sends out a query (what it's looking for), and every token offers a key (what it has) and a value (what it passes on). How well the query matches each key decides how much of each value gets blended into the token.
The diagram
Attention started as a way for translation models to look back at the right source words (Bahdanau, Cho and Bengio, 2014), and the transformer made it the core of the whole network (Vaswani et al., 2017). Here is the core of one attention step, for one token:
Read it as a fuzzy dictionary lookup. An ordinary dictionary finds the one key that matches exactly and returns its value. Attention compares the query with every key, scores how well each one matches, and returns a blend of all the values, weighted by those scores. The query, key and value are three different projections of the same token vector, each learned in training (multiplied by its own weight matrix), so what makes a token relevant can differ from what it contributes.
The pieces of the formula, in order:
- Score: the dot product of the query with each key. Bigger means a better match.
- Scale by √d: divide by the square root of , the number of dimensions in each query and key (64 per head in the original transformer), so scores don't grow just because there are more dimensions (more on why below).
- Mask: a language model predicts the next token, so a token may only look at itself and earlier tokens. Later positions get a score of −∞, which becomes a weight of exactly 0.
- Softmax: turns each token's scores into weights that are positive and add up to 1.
- Blend: the output is the weighted sum of the values. Every head's output is joined with the others, multiplied by one more learned matrix, and added back into the token's own vector.
In one line, for all tokens at once: , where is the mask. On its own, this formula can't tell word order: nothing in it says "laptop" is two tokens back. Real models add position information, today usually by rotating queries and keys according to their position, which The transformer block covers. The Attention, step by step lesson derives each piece of the formula.
A worked example: what does "It" look at?
Take four tokens, "The laptop arrived It", where the model is working out "It". In a real model, queries and keys have dozens to hundreds of learned dimensions per head that nobody labels. Ours have two made-up ones, so the numbers fit on a page. Queries and keys use is a thing and is an event; values carry what a token contributes, here about the laptop and about the arrival. "It" is looking for a thing, so its query is .
1/4Score every token: query · key
| token | key | query · key |
|---|---|---|
| The | 0 | |
| laptop | 3 | |
| arrived | 0 | |
| It | 1 |
"laptop" has a strong thing key, so it matches the query best. "arrived" offers an event, which "It" isn't looking for.
| token | score ÷ √2 |
|---|---|
| The | 0.00 |
| laptop | 2.12 |
| arrived | 0.00 |
| It | 0.71 |
With , every score is divided by . "It" is the last token so far, so the mask hides nothing here: the words "was broken" haven't been seen yet. For "laptop", the mask would hide "arrived" and "It".
| token | weight | |
|---|---|---|
| The | 1.00 | 0.08 |
| laptop | 8.34 | 0.67 |
| arrived | 1.00 | 0.08 |
| It | 2.03 | 0.16 |
Softmax raises to each score and divides by the total (12.37), so the weights add up to 1 (0.99 here after rounding). Two-thirds of the attention goes to "laptop".
| token | value | weight × value |
|---|---|---|
| The | ||
| laptop | ||
| arrived | ||
| It | ||
| output |
The output for "It" is mostly about the laptop. Added back into "It" (in a real model, after the output projection), it carries that information to every layer after it. Notice that the key decided who got attention, while the value decided what came back.
The whole thing is a few lines of NumPy:
import numpy as np
np.set_printoptions(precision=2, suppress=True)
tokens = ["The", "laptop", "arrived", "It"]
# Q and K features: [is a thing, is an event]
Q = np.array([[0, 0], [0, 1], [1, 0], [1, 0]], dtype=float) # what each token looks for
K = np.array([[0, 0], [3, 0], [0, 3], [1, 0]], dtype=float) # what each token offers
# V features: [about the laptop, about the arrival]
V = np.array([[0, 0], [1, 0], [0, 1], [0, 0]], dtype=float) # what each token passes on
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
d_k = Q.shape[1]
scores = Q @ K.T / np.sqrt(d_k)
mask = np.triu(np.ones((4, 4), dtype=bool), k=1) # hide later tokens
weights = softmax(np.where(mask, -np.inf, scores))
out = weights @ V
print("weights for 'It':", weights[3])
print("output for 'It': ", out[3])weights for 'It': [0.08 0.67 0.08 0.16]
output for 'It': [0.67 0.08]In a real model nobody chooses these numbers. The projections that produce queries, keys and values are learned, and the features they encode are whatever helped predict the next token. 3Blue1Brown animates the same steps, from the attention pattern through masking to the values:
Attention in transformers, step-by-step | Deep Learning Chapter 6
3Blue1Brown · segment of 26:09
An 11-minute segment covering the attention pattern, masking, context size and values, drawn the way this post describes them.
Many heads, many layers
One attention step gives each token one blend. Real models run several in parallel, called heads, each with its own query, key and value projections, so one head can track what a pronoun refers to while another tracks the previous word. Each head works in a narrower space, so many heads cost about the same as one wide one, and their outputs are joined and mixed by one more learned matrix (Vaswani et al., section 3.2.2).
Attention is one of two parts of each transformer block. The other is a feed-forward network applied to each position separately and identically (section 3.3), so in a standard transformer, attention is the only place where information moves between tokens. Some newer models are hybrids, such as Jamba, which interleaves attention with state-space layers that also carry information along the sequence. A useful way to picture the whole model is the residual stream from Anthropic's transformer-circuits work: each token has a running vector, and every attention head and feed-forward layer reads from it and adds its result back. The transformer block lesson takes the rest of the block apart.
Some heads have recognisable jobs. An induction head looks for an earlier place where the current token appeared and copies whatever came next, so a repeated pattern gets completed. Anthropic's researchers argue that such heads may account for much of in-context learning, but they call their own evidence "preliminary and indirect" (Olsson et al., 2022), and most heads don't have a job this tidy.
What attention costs you
The scores grow with the square of the length. Every token scores itself and every earlier token, so a sequence of tokens needs about scores per head per layer. Doubling a prompt from 1,000 to 2,000 tokens takes that from about 500,000 to 2 million; at a million tokens it's about 500 billion. That doesn't make a prompt twice as long four times as slow: at a few thousand tokens the rest of the model (the projections and feed-forward layers, which grow only in line with length) does far more work than the scores. By rough arithmetic, the square only takes over at tens of thousands of tokens for a model of typical width. FlashAttention computes exactly the same result in tiles that fit in the GPU's fast on-chip memory, so memory grows only in line with length, though the arithmetic stays quadratic. And long-context models often don't use full attention in every layer: Gemma 3, for example, makes most layers attend only to a short window of recent tokens.
Past keys and values are cached. Because of the mask, a token's key and value never change once it has been processed. When a model generates text one token at a time, it keeps them in a KV cache instead of recomputing them. Each new token still attends to everything in the cache, so generating gets slower as the context grows, and the cache, not the weights, often limits how many long conversations a server can hold. Grouped-query attention shrinks it by letting several query heads share one key/value head, with quality close to full multi-head attention. Context windows, KV cache and caching works out the cache size from a model's config.
Long context isn't evenly used. A model can attend to everything in its window, but that doesn't mean it uses every part equally well. Liu et al. (2023) found that models of the time answered best when the relevant information was at the start or end of a long input and worse when it was in the middle, even models built for long context. Newer models may do better; test yours with the information at different positions before relying on it.
You don't pay for the square directly. Most price lists charge a flat rate per token, so cost grows roughly in line with length. Some charge a higher rate above a context threshold, and cached tokens are cheaper, so check your provider's rules for long prompts. The square shows up mainly in latency and in what providers spend to serve long contexts.
Misconceptions
"The √d is cosmetic." It isn't. Without it, the scores in our example would be 0, 3, 0, 1 instead of 0, 2.12, 0, 0.71, and softmax would put 81% of the weight on "laptop" instead of 67%. The transformer paper's explanation (section 3.2.1) is that with many dimensions, unscaled scores get so large that softmax puts almost all the weight on one token, leaving tiny gradients for training to learn from.
"Attention means the model understands." Attention only moves information between tokens. What the moved information means is built up by many heads and feed-forward layers together, across dozens of layers.
"One head finds the answer." Heads overlap and work in combination across layers. The tidy roles above are the exceptions researchers could isolate, not how every head behaves.
Questions people ask
What are queries, keys and values in simple terms?
Three learned views of each token: the query says what it's looking for, the key says what it has, and the value is what it passes on when another token attends to it.
Why is attention quadratic?
Every token is scored against itself and every earlier token, so the number of scores grows with the square of the sequence length. Doubling the length quadruples them.
What is the causal mask?
It stops a token from attending to tokens after it, so a model trained to predict the next token can't see the answer. Masked scores become weights of exactly zero.
Is attention the same as the KV cache?
No. The KV cache stores the keys and values attention has already computed for earlier tokens, so generating each new token doesn't recompute them.
Sources & further reading
- Attention Is All You NeedPaper · Vaswani et al. · Google · 2017The transformer paper. Section 3.2 defines scaled dot-product and multi-head attention; section 3.3 the position-wise feed-forward layer.
- Neural Machine Translation by Jointly Learning to Align and TranslatePaper · Bahdanau, Cho, Bengio · 2014Where attention began, as a way for a translation model to look back at the right source words. Read the introduction.
- Attention is not ExplanationPaper · Jain, Wallace · 2019NAACL 2019. Attention weights often disagree with other measures of what mattered, and very different weights can give the same prediction.
- Attention is not not ExplanationPaper · Wiegreffe, Pinter · 2019EMNLP 2019. The reply: whether attention explains anything depends on what you mean by explanation, and the earlier tests don't settle it.
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessPaper · Dao et al. · 2022NeurIPS 2022. Computes exactly the same attention with far less traffic to slow GPU memory. The abstract and section 3.1.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsPaper · Ainslie et al. · 2023EMNLP 2023. Grouped-query attention, where several query heads share one key/value head to shrink the cache.
- Gemma 3 Technical ReportPaper · Gemma Team · Google DeepMind · 2025An example of what long-context models do instead of full attention everywhere: most layers attend only to a short local window, to keep the KV cache small.
- Jamba: A Hybrid Transformer-Mamba Language ModelPaper · Lieber et al. · 2024A hybrid that interleaves attention layers with Mamba (state-space) layers, which also move information between tokens.
- Lost in the Middle: How Language Models Use Long ContextsPaper · Liu et al. · 2023TACL. Models of the time used information at the start and end of a long context better than information in the middle.
- A Mathematical Framework for Transformer CircuitsLab research · Elhage et al. · Anthropic · 2021The residual-stream picture of a transformer, where every component reads from and writes to a shared stream. The opening sections are enough.
- In-context Learning and Induction HeadsLab research · Olsson et al. · Anthropic · 2022A pair of attention heads that completes repeated patterns, and the (explicitly preliminary) case that they drive much of in-context learning.
- The Annotated TransformerUniversity · Harvard NLPThe transformer paper re-implemented line by line in PyTorch. The attention section is the code version of this post.
