Attention & Transformers
Queries, keys, values and the architecture behind modern AI.
In 2017, Vaswani and colleagues threw out recurrence altogether. Their transformer alternates just two operations: attention, which moves information between positions, and a small MLP, which processes each position on its own. Here you derive both, assemble the block, and count what it costs to train and to run.
What you’ll learn
- Compute scaled dot-product attention in matrix form and derive why the scores are divided by .
- Assemble multi-head attention and the pre-LN transformer block, and count its parameters (about per layer).
- Distinguish encoder, decoder and encoder–decoder transformers, and explain how the causal mask makes training parallel.
- Analyze attention's cost and the memory-for-compute trade of the KV cache in autoregressive decoding.
Scaled dot-product attention
Attention, as the Input Layer put it, is a soft dictionary lookup. Stack the token vectors of a sequence as the rows of . Three learned matrices map each row to a query, a key and a value: and in , . Output row is a convex combination of the values, weighted by how well query matches each key:
Assume, as Vaswani et al. did in a footnote, that the components of and are independent with mean and variance , roughly the situation at initialization. Each product then has mean and variance :
So raw scores have standard deviation , which is for . Large score gaps push each row of the softmax toward a one-hot vector, where its Jacobian vanishes and almost no gradient reaches and :
Dividing by restores unit variance for every head size, so the softmax starts in its sensitive range. It is the same as a softmax temperature of applied to the raw dot products.
Without any position information, what does self-attention do with "dog bites man" versus "man bites dog"?
- Each word gets exactly the same output vector in both sentences; only the order of the rows differs
- The outputs differ, because the attention weights depend on word order
- The outputs differ, because the softmax is applied row by row
- The outputs differ, because values are weighted by their distance from the query
Show the answer
A. Each word gets exactly the same output vector in both sentences; only the order of the rows differs
Permuting the rows of by a permutation matrix permutes , and alike, and . Self-attention is permutation-equivariant: each output depends on its own token and the multiset of the others, so subject and object are indistinguishable. Positional information breaks the symmetry (Positional Encodings).
Multi-head attention
One softmax gives one weighting per query. To let a token gather several kinds of information at once (the previous token, its syntactic head, its referent), split the width into heads of size , give each its own projections, concatenate the results and mix them with . This is multi-head attention:
Parameter count. The query projections tile one matrix, and likewise for keys and values; with that makes weights (plus biases), whatever is. Heads are not extra capacity. They factor the same capacity into separate attention patterns, each computed from rank- query and key projections. The original transformer used with heads of size (Vaswani et al., 2017).
Think first Why not give every head the full width, ?
You could, at times the cost and parameters. The standard split keeps MHA as cheap as one full-width head. The price is rank: each head's score matrix has rank at most , which limits the patterns a single head can express (The Mathematics of Attention makes this precise). Many heads can be pruned after training with little loss (Michel, Levy & Neubig, 2019; Voita et al., 2019), so the right number is an empirical question.
The block and the residual stream
A transformer layer wraps attention and a position-wise MLP in residual connections and layer normalization. In the now-standard pre-LN arrangement, each sublayer reads a normalized copy of the running vectors and adds its output back:
TRANSFORMER-LM(tokens x₁ … xₙ) // decoder-only, pre-LN
H ← E[x₁ … xₙ] + P[1 … n] // n×d: token and position embeddings
for ℓ = 1 … L:
A ← LN(H)
for r = 1 … h: // heads, computed in parallel
Q, K, V ← A·W_Q^r, A·W_K^r, A·W_V^r // n×(d/h) each
Z_r ← softmax_rows(Q·Kᵀ/√(d/h) + M)·V
H ← H + [Z₁ … Z_h]·W_O // attention writes into the stream
H ← H + GELU(LN(H)·W₁ + b₁)·W₂ + b₂ // MLP d → 4d → d, per position
return softmax_rows(LN(H)·W_U) // n next-token distributionsWith for this is a decoder (next step). Everything except attention acts on each position separately, so all positions are computed in parallel. The original transformer used ReLU and put LN after each residual addition (post-LN), which trains less stably at depth (Normalization & Residual Connections).
Read as a residual stream: one -dimensional channel per position that every sublayer reads from and adds to (Elhage et al., 2021). Attention is the only operation that moves information between positions; the MLPs, which hold two-thirds of the weights, transform it in place. Per layer there are attention weights and MLP weights, so
GPT-3 (Brown et al., 2020) has layers of width . Estimate its non-embedding parameter count with , in billions.
Show the answer
174 B
. The embedding table adds billion, close to the reported 175 billion. Width enters squared: doubling quadruples , while doubling only doubles it.
Encoders, decoders and the causal mask
The same block serves three architectures, distinguished by the mask and by where keys and values come from:
| Architecture | Attention | Typical objective | Examples |
|---|---|---|---|
| Encoder | : every token sees every token | masked-token prediction; classification | BERT (Devlin et al., 2019) |
| Decoder | causal: for | next-token prediction | the GPT series (2018 on) |
| Encoder–decoder | bidirectional encoder; causal decoder plus cross-attention, with queries from the decoder and keys and values from the encoder output | sequence to sequence: translation, span corruption | the original transformer (2017); T5 (Raffel et al., 2020) |
The causal mask is what makes decoder training efficient. Adding before the softmax gives future positions weight exactly while each row still sums to one, so output row depends only on tokens . One forward pass then yields all next-token predictions of a training sequence, each conditioned on the true prefix, and the loss is one cross-entropy summed over positions. An RNN needs sequential steps for the same work.
Cost, and the KV cache
Count the floating-point operations of one layer on tokens, with a multiply-add as 2 FLOPs. The projections and the MLP are dense products costing ; the scores and the mixing cost each:
Generation is different. An autoregressive model emits one token per forward pass, and reprocessing the whole prefix each time would cost per new token. But under the causal mask earlier positions never change, so their keys and values can be stored and reused:
GENERATE(prompt x₁ … x_m, number of new tokens T)
run the model on x₁ … x_m, keeping every layer's K and V // prefill: the KV cache
for t = m+1 … m+T:
sample x_t from the output distribution at position t−1
run x_t alone through the layers; in each layer:
q, k, v ← projections of position t
append k and v to the layer's cache // now t rows
z ← softmax(q·K_cacheᵀ/√d_k)·V_cache // one row: O(t·d)
return x_{m+1} … x_{m+T}A new token now costs for projections and MLP plus for attention per layer. The cache trades memory for that compute: stored numbers per token, the keys and values of every layer.
At 2 bytes per number, how many megabytes of KV cache does GPT-3's configuration (, ) need per token of context?
Show the answer
4.7 MB
bytes MB per token, so one 2,048-token context needs about GB. When many sequences are served at once, the cache can dominate accelerator memory. Sharing keys and values across heads (multi-query and grouped-query attention) shrinks it: see Efficient Attention & Long Context.
Key takeaways
- Attention computes : each output is a convex combination of values weighted by query–key match, and the keeps score variance near so the softmax does not saturate.
- Multi-head attention splits width into heads of size , for weights whatever ; a pre-LN block adds attention and an MLP to a residual stream, about weights per layer.
- Without positions, self-attention is permutation-equivariant. Encoders attend both ways, decoders use a causal mask that makes training parallel, and encoder–decoders add cross-attention.
- A layer costs about FLOPs, so attention dominates beyond ; generation caches keys and values, numbers per token.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Query and key components are independent with mean and variance , and . What is the standard deviation of the unscaled score , and what does the transformer divide it by?
- ; it divides by
- ; it divides by
- ; no scaling is needed
- ; it divides by
Show the answer
A. ; it divides by
The variance is a sum of unit variances, , so the standard deviation is , and dividing by restores unit variance.
A layer has width . You switch multi-head attention from heads to , keeping . How does the number of attention weights change?
- It doubles
- It halves
- It stays at
- It grows by per extra head
Show the answer
C. It stays at
The heads' projections tile one matrix each for queries, keys and values, plus : whatever is. More heads means more, narrower attention patterns.
How does a decoder apply its causal mask?
- It sets the weights of future positions to zero after the softmax, without renormalizing
- It deletes future tokens from the input sequence
- It replaces the values of future positions by zero vectors
- It adds to the scores of future positions before the softmax, so they get weight exactly and the rest still sum to one
Show the answer
D. It adds to the scores of future positions before the softmax, so they get weight exactly and the rest still sum to one
Masking the scores keeps every row a probability distribution over the allowed positions , while the whole sequence is still processed in one pass. That is what makes training parallel.
What does the KV cache store, and what does it save?
- The attention weights of every earlier step, so the softmax need not be recomputed
- Each layer's keys and values for all earlier positions, so a new token needs only its own projections and one attention row per layer
- The model's output probabilities, so repeated prompts are answered instantly
- Compressed weights, so that the model fits in memory
Show the answer
B. Each layer's keys and values for all earlier positions, so a new token needs only its own projections and one attention row per layer
Under a causal mask, earlier keys and values never change, so each is computed once. A new token then costs per layer instead of reprocessing the prefix, at the price of stored numbers per token.
Go deeper
- The Mathematics of Attention · Scaled dot products, softmax and multi-head attention.
- Positional Encodings · Sinusoids, rotary embeddings and length generalization.
- Efficient Attention & Long Context · Sparse, linear and flash attention.
Further reading
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
- N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
- M. Phuong & M. Hutter, "Formal algorithms for transformers," arXiv:2207.09238 (2022).
- D. Jurafsky & J. H. Martin, Speech and Language Processing (3rd ed. draft), chapter on transformers, free at web.stanford.edu/~jurafsky/slp3.