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:

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

  1. 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.2 Multi-head attention

    Splitting dmodel into heads, per-head attention, concatenation and the output projection, with every reshape spelled out.

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

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

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

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.

Tensor roles
MarkerTensorMeaning
QQueriesWhat each position is looking for.
KKeysWhat each position offers to be matched against.
VValuesThe content that gets mixed into the output.
AAttention weightsSoftmax of the (scaled, masked) scores; each row sums to 1.
OOutputWeighted sum of value vectors.
MMask0 where attention is allowed, −∞ where it is blocked.
Symbols
SymbolMeaning
TSequence length (number of token positions)
dmodelModel (hidden) width
dk, dv, dhead, DFour 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, HKVQuery 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, MKVTwo 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.
LNumber of attention layers
BBytes 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

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.