Module 0 · optional · Lesson 0.5
Transformer equations in context
Read the attention pipeline as a sequence of typed transformations. By the end, you should explain projections, scores, masking and weighted values, then separate raw KV bytes from a full memory estimate.
Prerequisite: shape inference from 0.3 and softmax from 0.4. If the roles of Q, K and V (query, key, value) are unfamiliar, read Module 1, steps 5–7 first: this lesson writes them as equations.
0.5.1 A learned projection changes features
Use one sequence, one head and token rows. X is the incoming token matrix. W_Q, W_K and W_V are learned projection matrices; Q, K and V are query, key and value matrices. Multiplication combines input features to produce features suited to each role; it does not add token rows.
Q = X W_Q; K = X W_K; V = X W_V
With X shaped T by d_model, W_Q and W_K shaped d_model by d_k, and W_V shaped d_model by d_v, Q and K are T by d_k while V is T by d_v. T is token count, d_model model width, d_k query/key width and d_v value width. Biases, multiple heads and the output projection are omitted in this simplified pipeline.
0.5.2 A score grid becomes a weight grid
S = Q times transposed K divided by square root d_k; A = row softmax of S plus M
S is the scaled score matrix; A is the attention-weight matrix. M here is the additive causal mask, with zero for legal positions and negative infinity for excluded positions. Each score compares a query with a key by summing paired components. Scaling divides every score by the square root of query/key width. The mask changes availability; softmax normalizes each query row over legal keys. These operations preserve the query-by-key score shape.
The minus-infinity mask is mathematical shorthand for excluding entries from normalization. An implementation must handle fully excluded rows explicitly; the usual causal self-attention case keeps at least the diagonal.
0.5.3 Worked example: follow every output axis
Use a separate invented self-attention model with T=3, d_model=4, d_k=2 and d_v=2. X is 3 by 4; each projection is 4 by 2; Q, K and V are each 3 by 2. Q times transposed K is 3 by 3. Division by the square root of 2 and row softmax keep 3 by 3. Finally:
O = A V; O_ij sums A_ik V_kj over k=1 to 3; O is 3 by 2
O is one head’s output. i selects its token row, j its value feature, and k visits source token rows. For a legal invented weight row [0.25,0.75,0] and corresponding value-feature column [2,6,10], the output feature is 0.25×2 + 0.75×6 + 0×10 = 5. The third position contributes exactly zero because it is excluded in this example.
Common mistake: interpreting A as the output embeddings. A contains query-key mixing weights; multiplying by V produces output features. Its 3-by-3 shape differs from O’s 3-by-2 shape.
0.5.4 Read a storage equation with units
raw KV memory = 2 × layers × cached tokens × KV heads × head width × bytes per element
M_KV names raw cache storage in bytes; it is unrelated to the causal-mask M above. L is layer count, T cached token positions for one sequence, H_KV key/value-head count, D components per head, and B bytes per element. The leading 2 stores both keys and values; queries are not cached. Multiplying counts of elements by bytes per element gives bytes.
2 × 32 × 4096 × 8 × 128 × 2 = 536,870,912 bytes
For 32 layers, 4096 cached positions, 8 KV heads, width 128 and 2 bytes per element, this is 536,870,912 bytes = 512 MiB, using 1 MiB = 1,048,576 bytes. This is an exact raw-element count under the stated equal-size assumptions. Allocator overhead, metadata, weights, temporary activations, fragmentation and implementation-specific cache formats are outside it; it is not a full serving-memory measurement.
0.5.5 Predict the operation and result
Make a prediction before opening hints. Try the task again without help after checking the reasoning.
0.5.6 Practice causal exclusion
Predict which key is blocked and what happens to the remaining weights. This optional check separates exclusion from merely hiding a displayed weight.
0.5.7 Practice raw KV bytes
Count one sequence’s key and value elements, then convert that count to bytes. Use KV heads, not query heads. These are invented dimensions for a raw-storage check, not a serving-memory measurement.
0.5.8 Transfer across unequal lengths
For a new cross-attention example, Q is 2 by 4, K is 5 by 4, and V is 5 by 3. Write the score and output shapes. State the softmax axis. In the cache formula, what happens if only the bytes per element is halved?
Check the reference explanation
Transposed K is 4 by 5, so the scores and weights are 2 by 5. Normalize each query row over its five keys. Multiplying the 2-by-5 weights by the 5-by-3 values produces a 2-by-3 output. Halving B halves raw KV bytes when all other counts and the simple storage format remain fixed; practical quantization metadata can add overhead outside this raw formula.
Original context: the full attention equation and KV-cache memory. Primary sources: Attention Is All You Need, Section 3.2 and GQA.