“Attention is all you need” is a good paper title and a poor first explanation. I read the paper and a few blog posts, and I still couldn’t say what a query or a key actually is. All I had was three matrices and a softmax somewhere.
What made it click for me was 3Blue1Brown’s Attention in transformers. This post is my write-up of that mechanism, in the order I wish someone had given it to me: intuition, a fully worked three-token example, masking, the low-rank value trick, the real GPT-3 parameter counts, and multi-head attention.
[!NOTE] If tokens and embeddings are fuzzy for you, read how GPT actually works first. It sets up why directions in vector space carry meaning, and I lean on that here.
What problem does attention actually solve?
Right after the embedding step in how GPT actually works, a token’s vector is a context-free lookup. Take the word mole:
- American shrew mole — the animal
- One mole of carbon dioxide — the chemistry unit
- Take a biopsy of the mole — the skin growth
All three start with the exact same vector, even though the meaning depends on the surrounding words. Attention is the step where the surrounding tokens update the mole vector toward the right sense.
These updates can travel far. Suppose a whole mystery novel is fed in and ends with:
Therefore the murderer was …
To predict the next word, that final vector, which started out meaning only was, has to have absorbed information from thousands of tokens back. Attention is the mechanism that moves that information across the sequence.
How do tokens ask each other questions?
The example I keep coming back to is “a fluffy blue creature.” The adjectives fluffy and blue should update the noun creature.
Imagine each noun broadcasting a question: “are there any adjectives in front of me?” Each adjective broadcasts an answer: “yes, I’m an adjective and I describe nouns.” Where a question and an answer match, information flows. Making that matching numerical gives the whole mechanism, which has three parts:
| Role | What it means | Matrix |
|---|---|---|
| Query | what a token is looking for | $W_Q$ |
| Key | what a token offers | $W_K$ |
| Value | the info actually passed along | $W_V$ |
What is a query?
For each token, multiply its embedding by the query matrix $W_Q$ to get a query vector:
The query lives in a much smaller space than the embedding. In GPT-3 the embedding is 12,288-dimensional but the query/key space is only 128. So $W_Q$ is a $128 \times 12{,}288$ matrix that compresses each token’s meaning into a compact description of what it is looking for. The query for creature roughly says “I’m a noun, are there any adjectives ahead of me?”
What is a key?
In parallel, multiply every embedding by the key matrix $W_K$ to get key vectors:
Keys live in the same 128-dimensional space. Think of them as potential answers to the queries: fluffy’s key should land close to creature’s query.
“Close” means large dot product. For every (key, query) pair, compute $\vec{K}_i \cdot \vec{Q}_j$. A large positive value is a strong match (token $j$ attends to token $i$), and a value near zero or negative means the tokens are unrelated.
How do dot products become attention scores?
Lay all the dot products out as a grid. With $T$ tokens, you get a $T \times T$ matrix of raw scores. In matrix form, every key dotted with every query is one product:
Entry $(i, j)$ is key $i$ dotted with query $j$. It answers “how much should token $j$ listen to token $i$?”
flowchart TB
subgraph GRID["Attention scores (dot products)"]
direction LR
R1["fluffy·creature = large"]
R2["blue·creature = large"]
R3["the·creature ≈ 0"]
end
GRID --> SCALE["divide by √d_k"]
SCALE --> SM["softmax each column"]
SM --> AP["Attention pattern<br/>(weights sum to 1 per column)"]
Why do we divide by $\sqrt{d_k}$?
Raw dot products grow with the dimension $d_k$. If each coordinate of the query and key has variance near 1, their dot product sums $d_k$ terms and has variance near $d_k$. Large scores push softmax into a nearly one-hot output where gradients vanish. Scaling each score down fixes this:
In GPT-3, $d_k = 128$, so the divisor is:
To see the effect, I drew 300 random queries and keys with unit variance at each head dimension. I took their dot products and measured how spread out the raw and scaled scores are.
How does softmax turn scores into weights?
Raw scores can be negative and they don’t sum to 1. Softmax fixes that. It is applied down each column of the score matrix, so for every token $j$ the weights over all source tokens $i$ land in $[0, 1]$ and add up to 1.
For one column with scaled scores $s_1, s_2, \ldots, s_T$, the first step is to exponentiate each score:
Then sum them into a normalizer:
Each weight is one exponent divided by that sum:
The full matrix of weights is the attention pattern.
What is a value?
Scores say how much to mix, and values are what gets mixed. Multiply each embedding by the value matrix to get value vectors:
Then each token’s updated output is a weighted sum of all value vectors, using the attention weights from its column:
This weighted sum is the core of attention: the output blends all the tokens instead of picking one.
What is the full attention formula?
With the pieces built one at a time, the original paper’s one-line formula is shorthand for them:
Read it left to right: dot all keys with all queries, scale, softmax each column, blend the values. That is the whole mechanism for one head.
Can we walk through a complete three-token example?
Yes, and this is the step where the formula became concrete for me. I use three tokens, fluffy, blue and creature, with 2-dimensional query/key/value vectors so every arithmetic step fits on the page. (GPT-3 uses $d_k = 128$; the logic is the same.)
Step 1: the inputs. After multiplying by $W_Q$, $W_K$, and $W_V$:
Here $d_k = 2$, so $\sqrt{d_k} = \sqrt{2} \approx 1.414$.
Step 2: dot products for the creature column. Token creature is the one looking for adjectives, so I build column 3 of the score matrix. Key fluffy dotted with query creature:
Key blue dotted with query creature:
Key creature dotted with query creature:
So the raw scores for creature’s column are $[3,\, 2,\, 4]$.
Step 3: scale by $\sqrt{d_k}$. Divide each raw score by $1.414$:
Step 4: softmax, one line per step. Exponentiate each scaled score:
Add them for the normalizer:
Divide each exponent by $Z$ to get the attention weights:
Check: $0.284 + 0.140 + 0.576 = 1.000$, so the weights sum to 1.
Step 5: weighted sum of values. Blend the three value vectors using those weights:
First term:
Second term:
Third term:
Add them:
Creature did not copy any single neighbour. It mixed information from fluffy, blue and itself, weighted by how well each key matched its query. The largest weight (0.576) went to creature itself, and the adjectives still contributed 0.284 and 0.140. Running the same five steps for every column updates all three tokens.
$K^{\top} Q$ decides where to read. Softmax turns scores into a distribution. Multiplying by $V$ decides what information comes back.
I computed the creature weights on the same vectors, with and without the scaling. The left one matches Step 4.
With scaling: the weights from Step 4, and the output $(2.012, 0.856)$.
Without scaling: creature takes 0.665 and the output is $(2.240, 0.845)$.
Why can’t the model peek at future words? (masking)
During training the model predicts the next token at every position at once, which is far more efficient than one prediction per pass. That creates a leak: when predicting the token after position 5, the model must not look at positions 6, 7, 8 and so on.
The fix is masking. Before softmax, set to $-\infty$ every score where a later token would influence an earlier one:
Softmax then turns those entries into exact zeros. Each token attends only to itself and the tokens before it.
I ran the same three-token example without and with the mask. Each side shows the weights for fluffy.
No mask: fluffy gives 0.140 to blue and 0.576 to creature, which come after it.
Causal mask: fluffy puts all its weight, 1.000, on itself.
flowchart LR
A["Raw score grid"] --> B["Set 'future' entries<br/>to −∞<br/>(upper triangle)"]
B --> C["Softmax →<br/>those become 0"]
C --> D["Each token attends<br/>only to itself<br/>and earlier tokens"]
In GPT-style models masking is always on, which is what makes generation strictly left-to-right.
Attention also has a memory cost. The attention pattern has one row and one column per token, so its size is the square of the context length:
Doubling the context quadruples the grid. This quadratic growth is the main reason long context windows are hard.
What is the low-rank value trick?
Scores say how much to mix; values are what gets mixed. Naively, the value map goes from embedding space back to embedding space, so one full matrix would be:
That is about 151 million for one value matrix in one head, roughly 100 times the ~1.5M each for query and key. So GPT-3 factors the value map into two smaller matrices: a value-down ($12{,}288 \to 128$) and a value-up ($128 \to 12{,}288$):
In linear-algebra terms, this constrains the map to a low-rank transformation. The payoff is that all four maps in one head now cost the same.
How many parameters are in one GPT-3 attention head?
GPT-3 numbers — embedding 12,288, key/query/value dim 128:
| Matrix | Shape | Parameters |
|---|---|---|
| Query $W_Q$ | $128 \times 12{,}288$ | 1,572,864 |
| Key $W_K$ | $128 \times 12{,}288$ | 1,572,864 |
| Value-down | $128 \times 12{,}288$ | 1,572,864 |
| Value-up | $12{,}288 \times 128$ | 1,572,864 |
| Per head | ≈ 6.3 million |
All four matrices have the same size, which is the purpose of the low-rank factorization. The counts grow with the head dimension, as shown below.
[!NOTE] Self- vs cross-attention: everything above is self-attention: queries, keys and values all come from one sequence. Cross-attention (translation, speech-to-text) is nearly identical. The only difference is that keys and values come from a different sequence than the queries.
What is multi-head attention?
One head learns one kind of relationship, such as adjective to noun. Language has many more, so a transformer runs many heads in parallel, each with its own $W_Q, W_K, W_V$:
- GPT-3 uses 96 heads per block.
- 96 × ~6.3M ≈ 600 million parameters per multi-head attention block.
flowchart TB
E["Token embeddings"] --> H1["Head 1<br/>(grammar?)"]
E --> H2["Head 2<br/>(subject–object?)"]
E --> H3["…"]
E --> H96["Head 96<br/>(coreference?)"]
H1 --> CAT["Combine all heads"]
H2 --> CAT
H3 --> CAT
H96 --> CAT
CAT --> OUT["Updated embeddings"]
Each head makes its own attention pattern and its own value mix. The results are concatenated and projected back into the embedding space. Different heads can track different things: grammar, coreference (“Harry” meaning Harry Potter or Prince Harry depending on nearby words), physical implications (“they crashed the car”), and so on.
For tensors: input $X$ has shape $(B, T, d)$; per head, $Q, K, V$ have shape $(B, h, T, d_h)$; scores have shape $(B, h, T, T)$; the mixed result has shape $(B, h, T, d_h)$. Concatenating all $h$ heads restores $(B, T, d)$.
How does attention fit into the full transformer?
A transformer runs attention many times, not once. Data flows through attention, then an MLP (feed-forward) block, then attention again, then another MLP, dozens of times over. Each round lets a more refined embedding be updated by its more refined neighbours. The model’s apparent “reasoning” accumulates across that depth.
flowchart LR
A["Embeddings"] --> B["Multi-head<br/>Attention"]
B --> C["MLP /<br/>Feed-Forward"]
C --> D["Multi-head<br/>Attention"]
D --> E["MLP /<br/>Feed-Forward"]
E --> F["… ×96 layers …"]
F --> G["Final embeddings<br/>→ predict next token"]
Attention retrieves and mixes information across tokens, but it does not do all the computation. The surrounding MLPs, residual paths, layer normalization and depth matter just as much. Standard attention also stores a $T \times T$ score matrix, so memory grows quadratically with context length.
Where does this leave you?
What surprised me is how small the core idea is: dot product, scale, softmax, weighted sum, repeated across heads and layers. Queries, keys and values are “what I’m looking for”, “what I offer” and “what I hand over”. Masking keeps the model causal. The low-rank value trick keeps parameter counts manageable. The quadratic grid is the price of letting every token attend to every other token.
After working through this, the original Attention Is All You Need paper reads like a summary of something I understand, not a wall of notation.
If you haven’t read the setup, start with how GPT actually works.
Watch: Attention in transformers — 3Blue1Brown · full text version on 3blue1brown.com · part of the Neural Networks series.
Support the writing
If this post helped, a coffee keeps the deep dives coming.
Buy me a coffee