Learning LLM Systems · Module 2
Attention Mechanisms & KV-Cache Internals
Derive scaled dot-product attention from its parts, follow every tensor shape through multi-head and grouped-query attention, and work out exactly what the KV cache stores and how much memory it needs.
Open the 3D Transformer Architecture Explorer → A visual companion to lessons 2.1–2.3, with optional architecture previews.
Learning goal
By the end of this module you should be able to:
- derive Attention(Q, K, V) = softmax(QKT / √dk + M)V and explain the job of each term;
- trace tensor dimensions through single-head and multi-head attention;
- compare multi-head (MHA), multi-query (MQA) and grouped-query (GQA) attention and their effect on the KV cache;
- say precisely what the KV cache contains, when entries are appended, and why decoding with a cache changes the work per step;
- compute raw KV-cache memory for a model configuration and explain why that number alone does not decide whether a deployment fits.
Module 1 covered prefill and decode, autoregressive generation, why a KV cache helps, and prefix reuse. This module opens up the attention computation underneath those ideas rather than repeating them.
Lessons
-
2.1 Self-attention from first principles
Queries, keys and values as learned projections; scores, scaling, softmax, causal masking and the weighted sum of values.
-
2.2 Multi-head attention
Splitting dmodel into heads, per-head attention, concatenation and the output projection, with every reshape spelled out.
-
2.3 MHA vs MQA vs GQA
How many key/value heads each query head shares, and what that does to KV-cache size and decode-time reads.
Experiment results: Compare MHA, GQA and MQA — test loss, cache size, setup and limitations.
-
2.4 KV-cache internals
What is cached, its conceptual shape, how prefill builds it and how each decode step reads and appends to it.
-
2.5 KV-cache memory & performance
Derive the memory formula, size real configurations, see linear growth with context and why decode is often bandwidth-sensitive.
Prerequisites
- Matrix multiplication, transposes and dot products.
- The exponential function and what a probability distribution is.
- The prefill/decode picture from Module 1, or equivalent familiarity with autoregressive generation.
Notation and colour key
Tensor roles use consistent letters. Detailed tables also distinguish roles with border styles and shades; labels carry the meaning independently of colour.
| Marker | Tensor | Meaning |
|---|---|---|
| Q | Queries | What each position is looking for. |
| K | Keys | What each position offers to be matched against. |
| V | Values | The content that gets mixed into the output. |
| A | Attention weights | Softmax of the (scaled, masked) scores; each row sums to 1. |
| O | Output | Weighted sum of value vectors. |
| M | Mask | 0 where attention is allowed, −∞ where it is blocked. |
| Symbol | Meaning |
|---|---|
| T | Sequence length (number of token positions) |
| dmodel | Model (hidden) width |
| dk, dv, dhead, D | Four spellings of one number: the width of a single head’s key/query vectors (dk) and value vectors (dv). Lesson 2.1 writes dk and dv; lesson 2.2 calls it dhead = dmodel / H; the KV-memory lessons 2.3–2.5 write D. With equal-width heads (assumed throughout) D = dhead = dk = dv. |
| H, Hq, HKV | Query heads (H in lesson 2.2 and Hq from lesson 2.3 on: H = Hq) and key/value heads (HKV). In multi-head attention HKV = Hq; GQA and MQA make HKV smaller. |
| M, MKV | Two unrelated symbols: M is the attention mask (lesson 2.1), MKV is KV-cache memory in bytes (lessons 2.3–2.5). The subscript marks the memory. |
| L | Number of attention layers |
| B | Bytes per stored element (2 for BF16/FP16) |
Conventions used throughout: row vectors (a sequence is X ∈ ℝT×dmodel and projections are XW); biases omitted; no batch dimension; contiguous logical tensors; equal head dimensions. Numbers in examples are invented toy values unless a source is given. Memory figures count raw KV storage only. Numbering: token labels in worked tables count from 1 (the first token is token 1). Where a page says an index is zero-based it counts from 0: column ranges such as 0–63 in lesson 2.2, the head index i in lesson 2.3 and the cache position p in lesson 2.4 (whose tracer shows the label p + 1). Each page states which one it uses.
References
- Vaswani et al., Attention Is All You Need (2017) — scaled dot-product and multi-head attention.
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019) — multi-query attention.
- Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023) — grouped-query attention and uptraining.
- Dao et al., FlashAttention (2022) — IO-aware exact attention; mentioned for context, not covered here.
- vLLM documentation — a production serving engine’s view of KV-cache management.
These pages are my own study notes and simplified models built from the sources above; they do not run a real model or measure performance.