S14 · Lesson 29 · Attention and transformers
Scaled dot-product attention with queries, keys and values, why scores are divided by the square root of the dimension, multi-head and masked attention, positional encodings, the transformer block's parameters and arithmetic, and the key–value cache that inference keeps
A recurrent network passes information along a sequence one step at a time, so word 1 reaches word 500 only through 499 updates. Attention lets every position look directly at every other and take what it needs, weighted by how well they match. Stacked with small feedforward networks, it makes the transformer, the architecture behind today's language, speech and vision models, and its arithmetic decides what they cost to run.
- One query is compared with n keys. The curve is the softmax weight given to the best-matching key, against how far its score exceeds the others' (all equal), at temperature t.
- With many keys, a small margin spreads attention thinly; a large one concentrates it. Lowering t sharpens the choice.
- Dividing scores by plays the part of the temperature, keeping scores near unit size so attention neither saturates nor washes out as the dimension grows.
Predict
A query and a key are random 64-dimensional vectors whose entries are independent with zero mean and unit variance. What is the standard deviation of their dot product?
The dot product sums 64 independent products, each with variance 1, so its variance is 64 and its standard deviation 8. Scores that spread over ±8 or more would drive the softmax into giving nearly all the weight to one key, with vanishing gradients for the rest, so attention divides them by = 8.
Name it
Scaled dot-product attention
Each position produces a query, a key and a value by multiplying its vector by learned matrices. A query attends to all keys:
Row i of the softmax gives the weights position i places on every position, and the output is the weighted average of their values. The scale keeps the scores' spread near 1 whatever the dimension.
Heads, masks and positions
Multi-head attention runs h attentions in parallel on d/h-dimensional projections and concatenates them, so different heads can track different relations. A causal mask sets scores to −∞ for later positions, so a model generating text can't see the future. Attention ignores order, so position is added to the inputs, for instance as sinusoids with wavelengths from 2π up to about 2π × 10⁴ positions (a different frequency per pair of dimensions), or learned.
The transformer block
Each layer applies multi-head attention and then a two-layer feedforward network (hidden width usually 4d) to every position, each wrapped with a residual connection and layer normalization. With model width d the attention projections have weights and the feedforward network : about per layer. A forward pass costs about 2 operations per weight per token, per layer, plus the attention itself, about per token per layer for a context of n positions, which overtakes the rest when n > 6d.
The key–value cache
Generating text one token at a time, a model reuses the keys and values of all earlier tokens rather than recomputing them. The cache holds numbers per token for L layers: memory that grows with context length and batch size, and is read in full at every step, which is why long-context inference is limited by memory as much as by arithmetic.
Worked example
Count the parameters of a transformer with width 768, 12 layers, a 50,257-token vocabulary and 1024 learned positions.
Show the solution
- The layers. Each layer has weights, so the 12 layers hold 84.9 million.
- The embeddings. The token embedding adds and the positions 0.8 million.
- Total. with biases and normalization adding a few hundred thousand more.
- Compare. This is the size of GPT-2's smallest version; nearly a third of it is the vocabulary table, a share that shrinks as models grow, since layers grow as d² and the embedding as d.
Answer about 124 million parameters.
Worked example
A 32-layer model of width 4096 keeps its key–value cache in 16-bit numbers. How much memory does it need per token, and for one 4096-token conversation?
Show the solution
- Per token. Keys and values, 32 layers, 4096 numbers, 2 bytes each: half a megabyte.
- Per conversation. For 4096 tokens it's 2 GiB.
- Serving many. Serving 32 conversations at once needs 64 GiB of cache beside the weights.
- Grouped-query attention. It shares keys and values among several query heads, cuts this by the sharing factor, and is standard in large models for that reason.
Answer 524,288 bytes (half a megabyte) per token, and 2 GiB for one 4096-token conversation.
Worked example
For a model of width 768, at what context length does attention's own arithmetic match the rest of each layer's? And how much memory would the full score matrices of 32 heads take for 8192 positions in 16-bit numbers?
Show the solution
- Where they match. The layer's matrix multiplications cost per token and attention about , equal at
- Score matrices. per layer.
- How kernels avoid it. Optimized kernels never store them, computing the softmax in tiles that stay in on-chip memory; the arithmetic still grows as n², which is why very long contexts remain expensive.
Answer attention's arithmetic matches the rest of the layer at 4608 positions, and the score matrices would take 4.3 GB per layer.
Check
A transformer has width 1024, 6 layers and a vocabulary of 100000 tokens (feedforward width 4d).
(a)
How many weights do its layers hold, in millions?
(b)
Including the token embedding, how many in all?
Check
Queries and keys have 64 independent entries with zero mean and unit variance.
(a)
What is the standard deviation of a query–key dot product?
(b)
And after dividing by ?
Check
A query attends to 10 keys; one scores 1 above the rest, which are equal.
(a)
What weight does the softmax give it?
(b)
How large a margin would give it a weight of 0.9?
Check
A model with 32 layers of width 2048 keeps its key–value cache at 2 bytes per number.
(a)
How much cache does each token need?
(b)
How much for a batch of 1 sequences of 32768 tokens?
Check
A transformer layer of width 1024 processes a context of 1024 positions.
(a)
About how many operations does one token cost in this layer?
(b)
At what context length does attention's share reach half?
Check
Attention over 8192 positions with 8 heads stores its score matrices in 4-byte numbers.
(a)
How much memory would one layer's scores take?
Check
Why does a transformer need positional information added to its inputs?
Check
A transformer has L layers of width d (feedforward width 4d) and processes a context of n positions.
Step 1
About how many weights do its layers hold?
Type it the way you would write it, like 3sin(2πft) or 3*sin(2*pi*f*t). Angles can be in radians or carry a degree sign, like 45°.
Step 2
About how many operations does a forward pass take per token?
Step 3
How many numbers per token does its key–value cache hold?
Explain why
Why do attention scores have to be divided by the square root of the key dimension?
A score is a sum of d products of query and key entries. If those entries have about unit size, the sum's typical size grows like , so in a wide model raw scores spread over a large range. The softmax exponentiates them, and with a large spread it gives almost all the weight to the top score and almost none to the rest, which leaves the attention nearly a hard choice with gradients close to zero for every other key, so it barely learns. Dividing by brings the scores back to unit size whatever the width, keeping the softmax in its responsive range.
Practice
Keep practicing
9 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.