Pidoku

Attention from First Principles

Module 10 Lesson 10.h 2h Difficulty 4/5

Prerequisites 10.a, 10.b, 10.c, 10.g

This is the most important lesson in Module 10. Everything in Module 12 depends on understanding it mechanically, not just conceptually.


Before you start: five words#

WordPlain meaning
SequenceThe tokens of the input so far, in order. Position 0 is the first token.
Query (q)A vector each token produces that says “what am I looking for?”
Key (k)A vector each token produces that says “what do I contain?” — compared against queries.
Value (v)A vector each token produces that holds “what I pass on if someone attends to me”.
HeadOne independent copy of the attention mechanism. A layer runs many heads side by side.

1. What is it?#

Attention lets each token build its new representation from a weighted mix of other tokens, with the weights computed from the data itself:

For each token:
   1. ask a question                                  (its query)
   2. compare it with what every token offers         (their keys)
   3. take a weighted average of what they contain    (their values)

In one line:

Attention(Q, K, V) = softmax(Q Kᵀ / √d_head) V

Every piece of that line was built in earlier lessons: the dot products in QKᵀ (10.a, 10.b), the √d_head scale (10.a) and the softmax (10.g).


2. Why does it exist?#

Before attention, sequence models were recurrent: process token 1, then 2, then 3, carrying a fixed-size summary vector along. That had two fatal problems:

  1. A bottleneck. Everything about a 1,000-token history had to fit in one vector.
  2. No parallelism. Token 500 could not be processed until token 499 was finished.

Attention fixes both: every token can look directly at every earlier token (no bottleneck), and all positions can be computed at the same time during training and prefill (parallel).

The cost is quadratic: S tokens each looking at S tokens means S² comparisons. That quadratic is the defining engineering constraint of modern inference, and much of Modules 12, 13 and 14 responds to it.


3. Simple analogy#

A library with a very good reference desk.

You arrive with a question (query): “what does it refer to in this sentence?” Every document has an index card describing what it is about (key) and its actual contents (value).

You compare your question with every index card, score each match, turn the scores into weights (softmax), and read a blend of the documents in proportion to their weights. Relevant documents contribute most; irrelevant ones contribute almost nothing.

Three refinements map exactly onto the real mechanism:

  • Everyone asks at once. All queries are compared with all keys in one matrix multiplication.
  • Several specialists work in parallel, each looking for different things — grammar, topic, who-is-who. Those are the heads.
  • In a language model you may only read documents filed before yours. That is the causal mask.

4. Tiny example#

Full attention, by hand. Three tokens, one head, d_head = 2.

Q = [1  0]      K = [1  0]      V = [10  0]
    [0  1]          [0  1]          [ 0 10]
    [1  1]          [1  1]          [ 5  5]

Step 1: scores = Q Kᵀ  (every query dotted with every key)

  Q[0]·K[0] = 1·1+0·0 = 1     Q[0]·K[1] = 0     Q[0]·K[2] = 1
  Q[1]·K[0] = 0               Q[1]·K[1] = 1     Q[1]·K[2] = 1
  Q[2]·K[0] = 1               Q[2]·K[1] = 1     Q[2]·K[2] = 2

  scores = [1  0  1]
           [0  1  1]
           [1  1  2]

Step 2: scale by 1/√2 = 0.7071

  scores = [0.707  0      0.707]
           [0      0.707  0.707]
           [0.707  0.707  1.414]

Step 3: causal mask (token i may only see tokens 0..i)

  scores = [0.707  -inf   -inf ]
           [0      0.707  -inf ]
           [0.707  0.707  1.414]

Step 4: softmax each row

  row 0: only one visible score → [1.000, 0, 0]
  row 1: exp([0, 0.707]) = [1, 2.028]; sum 3.028 → [0.330, 0.670, 0]
  row 2: exp([0.707, 0.707, 1.414]) = [2.028, 2.028, 4.113]; sum 8.169
         → [0.248, 0.248, 0.504]

Step 5: weighted sum of V

  out[0] = 1.000·[10,0]                                    = [10.00, 0.00]
  out[1] = 0.330·[10,0] + 0.670·[0,10]                     = [ 3.30, 6.70]
  out[2] = 0.248·[10,0] + 0.248·[0,10] + 0.504·[5,5]       = [ 5.00, 5.00]

Read what happened. Token 0 could only see itself, so it got V[0] unchanged. Token 1 mixed tokens 0 and 1, leaning towards 1 because its query matched key 1 better. Token 2’s query pointed “diagonally”, matched key 2 best and blended all three.

Do this by hand once. It turns attention from a formula you memorised into a mechanism you understand.


5. Technical explanation#

The full multi-head computation#

# x: (B, S, d)
q = x @ Wq.T          # (B, S, h·d_head)
k = x @ Wk.T          # (B, S, h_kv·d_head)
v = x @ Wv.T          # (B, S, h_kv·d_head)

# split into heads
q = q.view(B, S, h,    d_head).transpose(1, 2)    # (B, h,    S, d_head)
k = k.view(B, S, h_kv, d_head).transpose(1, 2)    # (B, h_kv, S, d_head)
v = v.view(B, S, h_kv, d_head).transpose(1, 2)

# RoPE on q and k: position information (10.f)
q, k = apply_rope(q, k, positions)

# with GQA: each K/V head serves h // h_kv query heads
k = k.repeat_interleave(h // h_kv, dim=1)         # real kernels index instead of copying
v = v.repeat_interleave(h // h_kv, dim=1)

scores = q @ k.transpose(-2, -1) / math.sqrt(d_head)   # (B, h, S, S)   ← the big one
scores = scores + causal_mask
attn   = softmax(scores, dim=-1)
out    = attn @ v                                       # (B, h, S, d_head)

out = out.transpose(1, 2).reshape(B, S, h·d_head)
out = out @ Wo.T                                        # (B, S, d)

These steps are worth memorising. Every optimisation in Modules 12–14 changes one of them.

Why several heads#

With h heads of size d_head (usually d_head = d / h), the model runs h independent attention computations on different learned projections and concatenates the results. The cost is the same as one big head — the projections are just split — but the model can track h different kinds of relationship at once. A typical 8B-class model has d = 4,096, h = 32, d_head = 128.

The causal mask#

A language model generating text must not see the future:

        k0  k1  k2  k3
  q0 [  ✓   ✗   ✗   ✗ ]
  q1 [  ✓   ✓   ✗   ✗ ]
  q2 [  ✓   ✓   ✓   ✗ ]
  q3 [  ✓   ✓   ✓   ✓ ]

Two consequences:

  • Half of the S² score matrix is thrown away, and good kernels skip computing it.
  • The key and value of position i never change once computed, because nothing after it can affect it. That is the property that makes the KV cache possible (12.e). With two-way attention you would have to recompute everything at every step.

MHA, GQA, MQA — the KV-cache lever#

MHA (multi-head):     h query heads, h key/value heads
GQA (grouped-query):  h query heads, h_kv key/value heads (h_kv < h)
MQA (multi-query):    h query heads, 1 key/value head
          queries          keys/values
MHA:   [q0 q1 q2 q3]    [k0 k1 k2 k3]      KV cache: 4 units
GQA:   [q0 q1 q2 q3]    [k0    k1   ]      KV cache: 2 units   (groups of 2)
        \__/  \__/
MQA:   [q0 q1 q2 q3]    [k0         ]      KV cache: 1 unit
        \________/

For Llama 3.1 70B, h = 64 and h_kv = 8: an 8x smaller KV cache than full multi-head attention, which multiplies the number of users that fit in memory by 8. Nearly every current open model uses GQA, typically with 8 KV heads or fewer. Multi-head latent attention (MLA), used by the DeepSeek family and others, goes further: it caches one small compressed vector per token and reconstructs keys and values from it. 12.g compares all of these in bytes.

Other ways to cut the quadratic#

You will meet these in current models; each is taught later:

  • Sliding-window attention — some layers see only the last few thousand tokens (Gemma, gpt-oss, Mistral). The cache for those layers stops growing (12.h).
  • Sparse attention — a cheap “indexer” picks the most relevant earlier tokens and only those are attended to (DeepSeek’s sparse attention and its successors, 24.b).
  • Linear attention and hybrids — most layers keep a fixed-size running state instead of a cache, with full attention in a few layers (Qwen3-Next, Kimi Linear, 24.b).

Complexity#

                         FLOPs              Memory (naive)
Projections (q,k,v,o):   O(S · d²)          O(S · d)
Score computation:       O(S² · d)          O(S²) per head   ← the problem
Softmax:                 O(S²)              O(S²)
attn @ V:                O(S² · d)          O(S · d)

At S = 8,192, h = 32, B = 8, the score tensor alone in 16-bit precision is:

8 · 32 · 8,192 · 8,192 · 2 bytes = 34.4 GB      for ONE layer

Impossible. Hence FlashAttention, which computes scores in tiles and never stores them (13.l), using the online softmax from 10.g.


6. Under the hood#

During decode, the shapes change completely:

Prefill (S = 2,048):
   q: (B, h, 2048, 128)
   k: (B, h_kv, 2048, 128)
   scores: (B, h, 2048, 2048)      ← big, compute-bound

Decode (one new token, 2,048 tokens of context):
   q: (B, h, 1, 128)               ← ONE query row
   k: (B, h_kv, 2049, 128)         ← read from the KV cache
   scores: (B, h, 1, 2049)         ← a vector, not a matrix

Decode attention is a matrix–vector operation against the whole KV cache. Each step reads the entire cache and does very little arithmetic per byte:

FLOPs  ≈ 2 · B · h · S · d_head · 2       (scores, then attn @ V)
Bytes  ≈ 2 · B · h_kv · S · d_head · 2    (read K and V at 2 bytes each)

arithmetic intensity ≈ h / h_kv          ← 1 for MHA; 8 for GQA with 8 queries per KV head

Decode attention’s arithmetic intensity equals the GQA ratio. That is an under-appreciated fact: GQA does not just shrink the cache, it raises attention’s work per byte by the grouping factor, making it less memory-bound. Two wins from one design choice. (MLA raises it further, which is one reason it decodes efficiently.)


7. Performance implications#

PhaseWhat attention looks likeBottleneck
Prefill, short (S < 1k)matrix–matrix, compute-boundtensor cores
Prefill, long (S > 8k)quadratic, compute-boundFLOPs and activation memory
Decode, small batchmatrix–vector against the KV cacheKV read bandwidth
Decode, long contextKV reads dominate everythingKV bandwidth and capacity

At 128k tokens of context, decode attention can read more bytes than the model weights:

Llama 3.1 8B, 128k context, GQA (8 KV heads), 16-bit KV:
  KV bytes = 2 · 32 layers · 8 heads · 128 · 2 bytes · 131,072 tokens = 17.2 GB per sequence
  weights  = 16 GB

The cache is bigger than the model. Every long-context technique in 12.h and 14.i exists to attack that number.


8. Production implications#

  • Always use a fused attention kernel — FlashAttention, FlashInfer, or your engine’s own backend (18.c). Never build the score matrix.
  • The number of KV heads is a first-class serving consideration. Between two models of similar quality, the one with fewer KV heads (or MLA) is much cheaper to serve.
  • Long context is not free. Price it and cap it: a 128k-token request can use 20x the resources of an 8k one.
  • Prefill and decode use different kernels. Their shapes are opposite; engines pick different implementations.
  • Watch for kernel fallbacks. If a head size, precision or feature (such as attention sinks or a sliding window) falls outside the fast kernel’s support, you may silently get a path several times slower.

9. Common mistakes#

Building the score matrix. Fine at S = 512, fatal at S = 8,192.

Forgetting the causal mask. The model sees the future: impossibly good scores in testing, garbage in generation.

Applying RoPE to values, or after caching. RoPE goes on q and k, before k is cached.

Confusing h and h_kv. GQA needs the head mapping; forgetting it gives a shape error, or worse, a silent broadcast.

Assuming attention dominates FLOPs. Below roughly 30k tokens of context, the feed-forward blocks dominate FLOPs. Attention dominates memory at long context.

Softmax over the wrong axis — over queries instead of keys.

Optimising decode attention’s FLOPs. It is memory-bound; fewer FLOPs change nothing.


10. Hands-on exercise#

A. By hand. Redo the section 4 example with V = [[1,2],[3,4],[5,6]], first without the causal mask and then with it. Compare.

B. Implement it. Write multi-head attention in any language: projections, head split, RoPE, causal mask, softmax, output projection. Check it against the transformer block in 10.i.

C. GQA. Extend B to support h_kv < h. Check that h_kv = h reproduces MHA, then compute the KV-memory saving for Llama 3.1 70B’s configuration.

D. Measure the quadratic. Time naive attention for S ∈ {128, 256, …, 4,096}. Plot time against S on log–log axes and confirm a slope of about 2. At what S does memory run out?

E. Decode versus prefill. Implement both shapes (S_q = S and S_q = 1) and measure the achieved TFLOP/s and GB/s for each. Which is compute-bound and which memory-bound?

F. GQA intensity. Measure bytes read and FLOPs of decode attention for h_kv ∈ {1, 8, 32} with h = 32, and confirm that the arithmetic intensity is h / h_kv.


11. Interview questions#

  1. Explain attention in three sentences with no equations.
  2. Write the attention formula and explain every term, including the scale factor.
  3. Why is the causal mask what makes the KV cache possible?
  4. What are MHA, GQA, MQA and MLA? Quantify the KV-cache difference.
  5. Why does GQA raise decode arithmetic intensity, not just save memory?
  6. Why can you not build the score matrix at long context? Do the arithmetic.
  7. How do prefill and decode attention differ in shape and bottleneck?
  8. At what context length does the KV cache of an 8B GQA model exceed its weights?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in