S1429 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

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

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:

Attention(Q,K,V)=softmax(QKTdk)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/dk 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 4d2 weights and the feedforward network 8d2: about 12d2 per layer. A forward pass costs about 2 operations per weight per token, 24d2 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.

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
  1. The layers. Each layer has 12×7682=7.08million weights, so the 12 layers hold 84.9 million.
  2. The embeddings. The token embedding adds 50,257×768=38.6million and the positions 0.8 million.
  3. Total. 84.9+38.6+0.8=124million 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.

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
  1. Per token. Keys and values, 32 layers, 4096 numbers, 2 bytes each: 2×32×4096×2=524,288bytes 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.

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
  1. Where they match. The layer's matrix multiplications cost 24d2 per token and attention about 4nd, equal at n=6d=4608positions
  2. Score matrices. 81922×32×2bytes=4.3GB 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

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

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°.

Explain why

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

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.