Transformers & Self-Attention, Part 1: Queries, Keys, Values, Multi-Head Attention and Positions
Canonical lesson. This is the single source of truth for self-attention used by both the Deep Learning track and the Transformers & LLMs track (Track 5), and it comes in two parts. Part 1 (this page) covers the attention operation and position. Part 2 covers rotary positions, grouped-query attention, the causal mask and the full transformer block. If you arrived here from a Track 5 prerequisite link (e.g., from Multi-Head Attention or Positional Encoding), you are in the right place. If you came from BERT, read this part and then Part 2 for the block and the model families, then return to the NLP-track sequel.
After this lesson, you will be able to:
- Explain why RNNs and LSTMs hit a ceiling (sequential compute, fading long-range memory, no parallel training) and why dropping recurrence was the obvious next move once attention existed
- Derive the scaled-dot-product attention formula Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V from first principles, and explain what each of Query, Key, and Value represents semantically
- Justify the sqrt(d_k) scaling factor by tracing what happens to softmax when dot products grow with dimension
- Explain multi-head attention: how d_model is split across heads, why each head can learn a different pattern, and how the head outputs are joined again
- Run attention by hand in numpy on a five-token sentence and read the weight matrix it produces
- Say why attention alone cannot see word order, and build the sinusoidal position signal that fixes it
Before you start
In plain words: every word in a sentence asks a question, every word also offers a label and some content, and each word then takes a blend of the contents whose labels best match its question. That is self-attention. This part builds that idea step by step, runs it in a few lines of numpy, and ends with the one thing it forgets, which is the order of the words. Part 2 stacks the idea into a full transformer.
Every position in a sequence looks at every other position in the same sequence and takes a weighted blend of what it finds.
The vector a token uses to ask what it is looking for.
The vector a token offers as its label, to be matched against the queries.
The content a token hands over when another token decides to read from it.
A function that turns any list of scores into positive weights that add up to 1.
The score between a query and a key: their dot product divided by the square root of the key length, so that softmax does not saturate.
One independent copy of the attention operation, working on a slice of the vector. Several heads run side by side.
The width of the vector that represents one token as it moves through the model.
Attention where the queries come from one sequence and the keys and values come from another, such as a decoder reading an encoder.
A vector added to each token that tells the model where in the sequence the token sits, because attention alone cannot tell.
The transformer is not magic. It is three ideas welded together: (1) self-attention as a learned soft lookup over the sequence, (2) residual streams that make depth cheap, and (3) a feed-forward sublayer that does the actual "thinking" in each block. Once you see those three pieces clearly, every modern LLM is just "what if we did that 96 times and trained on the entire internet?"
Active recall
Before we tear down RNNs and put up transformers, recall from the LSTM lesson: (a) what specific problem did the LSTM cell-state highway solve, and (b) what was Bahdanau attention's role in the seq2seq pipeline? Write both before reading on. Why this matters: every architectural choice below (QKV, masking, residual streams) is a direct response to a limitation you already know but may not have on the tip of your tongue.
Write your answer in your own words — don't look back at the lesson. This is the most effective way to remember what you just learned.
Type your explanation above
#Why RNNs Had to Go
Recall where we left off in the previous lesson. The LSTM solved the vanishing-gradient problem with a cell-state highway, and Bahdanau attention solved the fixed-context-vector bottleneck by letting the decoder look back at every encoder state. But seq2seq with attention still had two fundamental problems that scaling could not fix:
-
Sequential compute. To compute hidden state h_50, you must first compute h_1, h_2, ..., h_49 in order. There is no way to parallelize this in the time dimension. A modern GPU has thousands of cores sitting idle while the LSTM crawls forward one token at a time.
-
Effective context still degrades. Even with the cell-state highway, an LSTM's memory is a fixed-size vector that gets overwritten at every step. Information from 500 tokens ago has been multiplied by 500 forget gates, each slightly less than 1. The signal is technically present but practically faded. Long-document understanding (legal contracts, code repositories, scientific papers) demands that every token can reach every other token equally easily.
Bahdanau already showed us that letting the decoder attend to every encoder state worked beautifully. So Vaswani and his co-authors asked the obvious follow-up: what if attention is enough on its own? What if we just drop the recurrence and let attention do all the work — within a sequence (self-attention), across sequences (cross-attention), and even from a token to its own past (causal self-attention)?
#The Core Move: Self-Attention vs Cross-Attention
| Operation | Queries come from | Keys/Values come from | Used in |
|---|---|---|---|
| Self-attention | Sequence A | Sequence A | Encoder layers, decoder self-attention sublayer |
| Cross-attention | Sequence A (e.g., decoder) | Sequence B (e.g., encoder) | Encoder-decoder bridge (T5, original transformer) |
| Causal self-attention | Sequence A | Sequence A, but masked so position i sees only j <= i | Decoder-only models (GPT, Claude, LLaMA) |
Self-attention is what makes a transformer feel "contextual": the same word ("bank") gets different output representations depending on its neighbors ("river bank" vs "investment bank") because its query vector matches different keys in each context. RNNs eventually achieved this through their hidden state too, but only after sequentially processing the whole prefix. Self-attention does it in one shot, in parallel, with O(1) hops between any two positions.
#Query, Key, Value: A Soft Differentiable Lookup
x (a vector of dimension d_model) gets projected into three vectors:The visualization above shows attention scores between every pair of tokens. Each cell (i, j) is how much token i attends to token j. Notice three things: (1) the diagonal is usually bright — tokens often attend to themselves; (2) some columns light up across many rows — those are "popular" tokens that many positions want context from (often nouns or verbs); (3) the pattern is asymmetric — attention from "it" to "animal" is not the same as attention from "animal" to "it".
#The Scaled-Dot-Product Attention Formula
Here is the equation that does the actual work — the one you will see written on every transformer slide, every system-design whiteboard, every blog post about LLMs:
Let us unpack the four operations.
Q_i · K_j — the dot product of token i's query with token j's key (the dot product is derived in Vectors & Spaces). A large positive value means "these vectors point in the same direction in the learned space" → "token j is highly relevant to whatever token i is looking for."sum_j alpha_{i,j} * V_j. That is the new representation of token i — a mix of relevant value vectors from across the entire sequence.You have a sequence of length 1000. You double it to length 2000. By what factor do the memory and compute requirements of one self-attention layer increase?
#Multi-Head Attention: Many Lookups in Parallel
Why do heads end up specializing? Because they are initialized with different random weights and trained jointly with the rest of the network. Stochastic gradient descent breaks symmetry — each head finds a different niche in the loss landscape. Interpretability work has found heads that specialize in:
- Positional heads. Attend mostly to immediate neighbors (left or right).
- Syntactic heads. Attend from verbs to their subjects, or from pronouns to their referents.
- Induction heads. Attend from "X" to the position right after a previous occurrence of "X" — the mechanism behind in-context learning in LLMs.
- Punctuation-tracking heads. Attend to matching parentheses, quotes, or section boundaries.
Modern LLMs use 8–96 heads per layer. The original transformer used 8. Claude Sonnet and GPT-4 likely use 64+. The exact count is a hyperparameter; you trade head count for per-head dimension at fixed compute budget.
Why does multi-head attention with H heads of dimension d_model/H typically outperform a single attention head of dimension d_model, even though the parameter count and compute cost are roughly equal?
#Toy Implementation: Scaled-Dot-Product Attention from Scratch
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V end-to-end in numpy on a 5-word toy sequence, then visualizes the attention weights as a heatmap. Run it. Modify the input embeddings. Watch the attention pattern change.The heatmap above shows learned attention patterns from a trained transformer on the sentence "The animal didn't cross the street because it was too tired." Look at the row labeled "it" — you should see a bright cell on the column "animal", not on "street". The model has learned (through pure self-supervision on text) that "it" co-refers with "animal". No one annotated coreference for it. The attention pattern fell out of the language-modeling loss.
#Positional Encoding: Attention Is Permutation-Invariant
softmax(QK^T / sqrt(d_k)) V is permutation-equivariant — if you shuffle the rows of X, the output rows shuffle the same way, but otherwise nothing changes. The attention operation has no idea what order the tokens are in.This is a disaster for language. "Dog bites man" and "Man bites dog" have identical token bags but very different meanings. Without injecting position information somewhere, a transformer would treat them as the same input.
If we removed positional encoding from a transformer language model entirely, what would happen to its ability to distinguish 'dog bites man' from 'man bites dog'?
The original transformer added a fixed sinusoidal pattern to each position's embedding:
Modern alternatives:
- Learned absolute (BERT, GPT-2): just learn an embedding per position index. Simple. Fails to extrapolate beyond training length.
- RoPE — Rotary Position Embedding (LLaMA, GPT-J, Mistral, modern Claude): rotates Q and K vectors by an angle proportional to position. Has nice properties (relative-position-aware, extrapolates better, easy to extend context). The current default in open-source LLMs.
- ALiBi (Press et al. 2022): no PE at all — instead, add a linear bias to attention scores that penalizes distant tokens. Very strong extrapolation properties.
#Key Takeaways
- Self-attention is a learned, soft, parallel lookup over the sequence. Each token produces a Query (what I want), Key (what I have), and Value (what to bring back). The score
softmax(QK^T / sqrt(d_k))is the lookup; the multiplication by V is the retrieval. The whole operation is differentiable end-to-end. - The sqrt(d_k) scaling is not optional. Without it, dot-product magnitudes scale with sqrt(d_k), softmax saturates, gradients vanish, and training collapses. This is the single most common implementation bug in hand-rolled attention.
- Multi-head attention lets different heads specialize. Splitting d_model across H heads gives the model H independent lookup patterns per layer. Interpretability work has found heads that handle coreference, induction, syntax, and punctuation — all emerging from random initialization plus gradient descent.
- Positional encoding is mandatory because attention is permutation-invariant. Without injecting position info (sinusoidal, learned, RoPE, or ALiBi), 'dog bites man' and 'man bites dog' would be literally identical inputs to the network.
- RNNs hit two ceilings. Steps must run one after another, and a fixed-size memory fades over long ranges. Letting every position attend to every other one removes both, which is why recurrence could be dropped.
- The attention weights are a matrix you can read. Row i of softmax(QK^T / sqrt(d_k)) shows where token i looks, and each row sums to 1.
#Quick Check
Why is the scaled-dot-product attention formula divided by sqrt(d_k) before the softmax?