---
title: Attention and transformers
heading: 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
eyebrow: S14 · Lesson 29 · Attention and transformers
xp: 50
---

::: hook
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.
:::

::: play
- 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 $\sqrt d$ plays the part of the temperature, keeping scores near unit size so attention neither saturates nor washes out as the dimension grows.
:::

```sim plot
view: graph
x: D = 0..12
y: w = 0..1
slider: n = 2..10000 = 100 log
slider: t = 0.2..5 = 1
plot: exp(D/t)/(exp(D/t) + n - 1) | label: weight on the best key
```

::: 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?

- [ ] 1
- [x] 8
- [ ] 64
- [ ] 0.125

::: reveal
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 $\sqrt{64}$ = 8.
:::
:::

::: nameit
## 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:
$$\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$
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 $1/\sqrt{d_k}$ 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 $4d^2$ weights and the feedforward network $8d^2$: about $12d^2$ per layer. A forward pass costs about 2 operations per weight per token, $24d^2$ per layer, plus the attention itself, about $4nd$ 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 $2Ld$ 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.
:::

::: example
## Count the parameters of a transformer with width 768, 12 layers, a 50,257-token vocabulary and 1024 learned positions.

::: solution
1. **The layers.** Each layer has
   $$12 \times 768^2 = 7.08\ \text{million}$$
   weights, so the 12 layers hold 84.9 million.
2. **The embeddings.** The token embedding adds
   $$50{,}257 \times 768 = 38.6\ \text{million}$$
   and the positions 0.8 million.
3. **Total.**
   $$\begin{aligned} &84.9 + 38.6 + 0.8 \\ &= 124\ \text{million} \end{aligned}$$
   with biases and normalization adding a few hundred thousand more.
4. **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.
:::
:::

::: 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?

::: solution
1. **Per token.** Keys and values, 32 layers, 4096 numbers, 2 bytes each:
   $$\begin{aligned} &2 \times 32 \times 4096 \times 2 \\ &= 524{,}288\ \text{bytes} \end{aligned}$$
   half a megabyte.
2. **Per conversation.** For 4096 tokens it's 2 GiB.
3. **Serving many.** Serving 32 conversations at once needs 64 GiB of cache beside the weights.
4. **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.
:::
:::

::: 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?

::: solution
1. **Where they match.** The layer's matrix multiplications cost $24d^2$ per token and attention about $4nd$, equal at
   $$\begin{aligned} n &= 6d \\ &= 4608\ \text{positions} \end{aligned}$$
2. **Score matrices.**
   $$\begin{aligned} &8192^2 \times 32 \times 2\ \text{bytes} \\ &= 4.3\ \text{GB} \end{aligned}$$
   per layer.
3. **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
kind: parts
given: d = 512 | 1024 | 4096; L = 6 | 24 | 48; V = 32000 | 100000

## A transformer has width {d}, {L} layers and a vocabulary of {V} tokens (feedforward width 4d).

::: part
answer: 12*d^2*L/1e6
unit: million
tolerance: 0.5%

### How many weights do its layers hold, in millions?

::: misses
- [4*d^2*L/1e6] That's attention alone; the feedforward network adds $8d^2$.
- [any] $12d^2$ per layer.
:::
:::

::: part
answer: (12*d^2*L + V*d)/1e6
unit: million
tolerance: 0.5%

### Including the token embedding, how many in all?

::: misses
- [any] Add V × d.
:::
:::
:::

::: check
kind: parts
given: d = 16 | 64 | 128 | 256

## Queries and keys have {d} independent entries with zero mean and unit variance.

::: part
answer: sqrt(d)
tolerance: 0.5%

### What is the standard deviation of a query–key dot product?

::: misses
- [d] That's the variance.
- [any] $\sqrt d$.
:::
:::

::: part
answer: 1
tolerance: 0.5%

### And after dividing by $\sqrt d$?

::: misses
- [any] The scaling makes it 1.
:::
:::
:::

::: check
kind: parts
given: n = 3 | 10 | 30; D = 1 | 2 | 4; w = 0.5 | 0.9

## A query attends to {n} keys; one scores {D} above the rest, which are equal.

::: part
answer: exp(D)/(exp(D) + n - 1)
tolerance: 0.5%

### What weight does the softmax give it?

::: misses
- [exp(D)/(exp(D) + n)] The other n − 1 keys each get weight proportional to 1.
- [any] $e^\Delta/(e^\Delta + n - 1)$.
:::
:::

::: part
answer: ln(w*(n - 1)/(1 - w))
tolerance: 0.5%

### How large a margin would give it a weight of {w}?

::: misses
- [any] Solve $e^\Delta/(e^\Delta + n - 1) = w$.
:::
:::
:::

::: check
kind: parts
given: L = 24 | 32 | 80; d = 2048 | 4096 | 8192; b = 1 | 2; n = 2048 | 32768; B = 1 | 16

## A model with {L} layers of width {d} keeps its key–value cache at {b} bytes per number.

::: part
answer: 2*L*d*b/1e6
unit: MB
tolerance: 0.5%

### How much cache does each token need?

::: misses
- [L*d*b/1e6] Keys and values are both kept.
- [any] $2Ld$ numbers per token.
:::
:::

::: part
answer: 2*L*d*b*n*B/1e9
unit: GB
tolerance: 0.5%

### How much for a batch of {B} sequences of {n} tokens?

::: misses
- [any] Per-token size times tokens times sequences.
:::
:::
:::

::: check
kind: parts
given: d = 512 | 1024 | 4096; n = 1024 | 8192 | 65536

## A transformer layer of width {d} processes a context of {n} positions.

::: part
answer: (24*d^2 + 4*n*d)/1e6
unit: MFLOP
tolerance: 0.5%

### About how many operations does one token cost in this layer?

::: misses
- [24*d^2/1e6] That leaves out attention's own $4nd$.
- [any] $24d^2 + 4nd$.
:::
:::

::: part
answer: 6*d
unit: positions
tolerance: 0

### At what context length does attention's share reach half?

::: misses
- [any] $4nd = 24d^2$.
:::
:::
:::

::: check
kind: parts
given: n = 2048 | 8192 | 32768; h = 8 | 32; b = 2 | 4

## Attention over {n} positions with {h} heads stores its score matrices in {b}-byte numbers.

::: part
answer: n^2*h*b/1e9
unit: GB
tolerance: 0.5%

### How much memory would one layer's scores take?

::: misses
- [n*h*b/1e9] Every position scores every other: n² per head.
- [any] $n^2hb$ bytes.
:::
:::
:::

::: check
kind: choice

## Why does a transformer need positional information added to its inputs?

- [ ] Without it, the softmax can't be normalized
- [x] Attention computes a weighted average over positions that would be unchanged if the inputs were shuffled, so without position information the model couldn't tell word order
- [ ] It replaces the value vectors
- [ ] It stops the model attending to future positions

::: misses
- [1] The softmax normalizes regardless.
- [3] Values are still computed from the inputs.
- [4] That's the causal mask.
:::
:::

::: check
kind: derivation
vars: d = 64..8192, n = 1..100000, L = 1..100

## A transformer has L layers of width d (feedforward width 4d) and processes a context of n positions.

::: step
answer: 12*d^2*L

### About how many weights do its layers hold?
:::

::: step
answer: L*(24*d^2 + 4*n*d)

### About how many operations does a forward pass take per token?
:::

::: step
answer: 2*L*d

### How many numbers per token does its key–value cache hold?
:::

::: right
Right. Weights set the per-token arithmetic; the context sets attention's share and the cache.
:::
:::

::: explain
## Why do attention scores have to be divided by the square root of the key dimension?

::: model
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 $\sqrt d$, 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 $\sqrt d$ brings the scores back to unit size whatever the width, keeping the softmax in its responsive range.
:::
:::

::: practice
::: check
given: d = 768 | 2048; L = 12 | 36
answer: 12*d^2*L/1e6
unit: million
tolerance: 0.5%

## Layer weights: d = {d}, L = {L}?

::: misses
- [any] $12d^2L$.
:::
:::

::: check
given: L = 32 | 64; d = 4096 | 8192; b = 1 | 2
answer: 2*L*d*b/1e6
unit: MB
tolerance: 0.5%

## KV cache per token: L = {L}, d = {d}, {b} bytes?

::: misses
- [any] $2Ldb$.
:::
:::

::: check
given: n = 20 | 500; D = 2 | 5
answer: exp(D)/(exp(D) + n - 1)
tolerance: 0.5%

## Softmax weight: {n} keys, margin {D}?

::: misses
- [any] $e^\Delta/(e^\Delta + n - 1)$.
:::
:::
:::
