Phase 01/Inside the transformer block/Attention mechanisms
PHASE 01 · Inside the transformer block

Attention mechanisms

0%
8 h6 subtopics2 lessons · 2 required
In plain English

Attention is how each word in a sentence gathers information from the other words. Every word asks a question (a query), every word offers a label (a key) and a payload (a value). Each word compares its question against all labels, decides how much to trust each one, and then blends the payloads in those proportions. Imagine a meeting where each person asks a question, looks around the table to judge who is relevant, and forms their view by weighting what the relevant people said. Doing this with several independent sets of questions at once is multi-head attention. Because every word compares against every other word, the work grows with the square of the sentence length.

Why it matters

Attention is the only part of a transformer whose cost depends on sequence length, and its score matrix is the memory hog that FlashAttention and PagedAttention were invented to tame. The K and V tensors it produces are exactly what the KV cache stores.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement causal multi-head self-attention from scratch in PyTorch and match a reference to 1e-5.
  • Derive the FLOPs and memory of the attention score matrix as a function of sequence length.
  • Explain the role of the 1/sqrt(d_k) scaling and the causal mask.
  • Measure how attention latency grows with sequence length on a CPU.
  • Distinguish multi-head, multi-query and grouped-query attention and their KV sizes.

Key concepts

Query, key, value
Three linear projections of each token's vector; queries probe, keys are matched against, values are mixed.
Scaled dot-product attention
softmax(Q K^T / sqrt(d_k)) V; the scaling keeps logits in a range where softmax is not saturated.
Causal mask
Setting scores for future positions to minus infinity so a token only attends to itself and earlier tokens.
Multi-head attention
Running h independent attentions on d_model/h-sized slices and concatenating; lets heads specialise.
Attention score matrix
The (T, T) matrix per head of attention weights; its size grows quadratically with sequence length.
Grouped-query attention (GQA)
Several query heads share one key/value head, shrinking K and V (and the KV cache) by that ratio; used by Llama 2 70B and TinyLlama.
Output projection
The final (d_model, d_model) linear layer that mixes the concatenated heads back into the residual stream.

Subtopics

  1. 1. Single-head attention by hand

    Compute Q, K, V for a 4-token toy input, the score matrix, the softmax and the weighted sum with pencil-level numbers.

  2. 2. Causal masking

    Why decoder-only models mask the upper triangle, how it is implemented with masked_fill and why it enables caching.

  3. 3. Multi-head attention and shapes

    The (B, T, C) to (B, h, T, d_head) reshape, batched matmul over heads, and concatenation back to (B, T, C).

  4. 4. Cost of attention

    FLOPs 4*T^2*d per layer for QK^T and AV, plus 8*T*d^2 for projections; the score matrix is T^2 per head in memory.

  5. 5. MHA, MQA and GQA

    How sharing K/V heads trades a little quality for a large reduction in KV bytes per token.

  6. 6. Fused attention APIs

    F.scaled_dot_product_attention as the single entry point that dispatches to math, memory-efficient or flash kernels.

Resources

Hands-on lessons

L1

Implement causal multi-head attention and match GPT-2

CPU · your Macnotebook120 minrequired

Goal · Write a from-scratch attention function that reproduces the output of GPT-2 layer 0's attention block given the same weights.

  1. 1Load gpt2 and grab block 0, model.transformer.h[0]; extract attn.c_attn and attn.c_proj weights and biases.
  2. 2Write my_attention(x, W_qkv, b_qkv, W_proj, b_proj, n_head) using only matmul, reshape, transpose, softmax and a causal mask.
  3. 3Feed the layer-normed hidden state of a 16-token prompt (hook block 0's ln_1 output) into both your function and the real attn module.
  4. 4Compare with torch.allclose(atol=1e-5) and print max absolute difference.
  5. 5Remove the 1/sqrt(d_k) scaling and observe how the attention weights change (print entropy per head).
  6. 6Plot the (16, 16) attention weight matrix for heads 0 to 3 as heatmaps and verify the upper triangle is zero.
Deliverable
A notebook with the matching assertion, the max-diff number and the heatmaps.
Check
torch.allclose passes at atol 1e-5 and every attention row sums to 1.0 within 1e-6.
L2

Measure quadratic scaling on CPU

CPU · your Macexperiment60 minrequired

Goal · Produce a plot of attention time and score-matrix bytes versus sequence length for GPT-2 head dimensions.

  1. 1Build random Q, K, V of shape (1, 12, T, 64) in fp32 for T in [128, 256, 512, 1024, 2048, 4096].
  2. 2Time your manual attention from l1 (materialising the (T, T) scores) with 20 repeats per T.
  3. 3Time F.scaled_dot_product_attention(is_causal=True) on the same inputs.
  4. 4Compute score-matrix bytes as 12*T*T*4 and record alongside timings.
  5. 5Plot both timings on log-log axes and fit the slope between T=1024 and T=4096.
Deliverable
A CSV of (T, manual_ms, sdpa_ms, score_bytes) and a log-log plot.
Check
The fitted slope for the manual implementation is between 1.7 and 2.3, and the score matrix at T=4096 is 805,306,368 bytes.

Build your own

Build your own attention

PythonCPU · your Mac~6 h

Scaled dot-product attention from a single head to causal multi-head and grouped-query attention, finishing with a tiled numpy version that never materialises the full score matrix.

The real thing: github.com/Dao-AILab/flash-attention ↗

How you know a stage passes

Write tests/test_attention.py first. Every stage compares your function with torch.nn.functional.scaled_dot_product_attention on random inputs at several shapes (torch.allclose, atol 1e-5 in float32), and the GPT-2 stages compare with Hugging Face attention outputs on real weights. Memory stages assert on tracemalloc or array sizes. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01one head, no mask
    `attention(q, k, v)` computes softmax(q k^T / sqrt(d)) v for shapes [T, d] using only matmul, exp and sum.
    test · Output matches F.scaled_dot_product_attention at atol 1e-5 for T in {1, 7, 64} and d in {16, 64}; each softmax row sums to 1 within 1e-6.
  2. 02causal mask and numerically safe softmax
    A causal mask sets future scores to -inf before a max-subtracted softmax, so position t attends only to positions 0..t.
    test · Matches SDPA with is_causal=True at atol 1e-5; scores of 1e4 do not produce NaN; the output at position 0 equals v[0].
  3. 03multi-head with the real GPT-2 shapes
    Inputs [B, T, d_model] are projected, split into [B, H, T, d_head], attended per head, merged and projected back.
    test · With GPT-2-small layer-0 weights loaded, your block output matches the Hugging Face GPT2Attention output on 32 real tokens at atol 1e-4.
  4. 04MQA and GQA
    `attention(q, k, v, num_kv_heads)` lets several query heads share one K/V head by index arithmetic, not by repeating K/V in memory.
    test · With 32 query heads and 8 KV heads, output matches a reference that uses repeat_interleave at atol 1e-5; K/V bytes passed in are exactly one quarter of the MHA case.
  5. 05tiled attention in numpy
    Queries and keys are processed in blocks of 64 with a running max and running sum (online softmax), so memory is O(T * block) instead of O(T^2).
    test · Output matches your stage-2 implementation at atol 1e-4 for T=4096; the largest array allocated is under 4 MB where the full score matrix would be 64 MB.
  6. 06measure the shapes you built
    A benchmark prints time and peak memory for naive, tiled and SDPA at T in {512, 1024, 2048, 4096}, with one head.
    test · Naive time grows about 4x per doubling (fitted slope between 1.7 and 2.3 on log-log axes); tiled peak memory stays within 2x of its T=512 value across all four lengths.

Knowledge check

QWhy divide the scores by sqrt(d_k)?

Dot products of d_k random unit-variance numbers have variance d_k; scaling restores unit variance so softmax does not saturate into near one-hot outputs.

QHow does the causal mask make a KV cache possible?

Because token t never looks at tokens after t, its K and V never change when later tokens arrive, so they can be computed once and reused.

QFor GPT-2 small at T=1024, how big is one layer's fp32 score tensor?

12 heads * 1024 * 1024 * 4 bytes = 48 MiB per layer.

QTinyLlama has 32 query heads and 4 KV heads. By what factor does GQA shrink its KV cache versus full MHA?

By 8x; K and V are stored for 4 heads instead of 32.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 checks pass.
  • Can write scaled dot-product attention with a causal mask from memory in under 15 lines.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →