02Multi-head causal self-attention (PyTorch)
02 Multi-head causal self-attention (PyTorch)
Four levels in solution.py. Read one level at a time and run only its tests until they pass:
pytest problems/02_multihead_attention -k level1. Earlier levels must keep passing.
CausalSelfAttention(n_embd, n_head) takes x of shape (B, T, C) and returns (B, T, C). Do it by hand: no
F.scaled_dot_product_attention, no nn.MultiheadAttention.
Level 1. The layers. One fused input projection self.qkv = nn.Linear(C, 3 * C), whose output is q, then k,
then v, and an output projection self.proj = nn.Linear(C, C). Raise ValueError when n_embd isn't divisible
by n_head. forward returns (B, T, C), and gradients reach self.qkv.
Level 2. The heads. Split q, k and v into heads, (B, T, C) -> (B, n_head, T, C // n_head), run scaled
dot-product attention in every head at once, merge the heads back to (B, T, C) and apply self.proj. Head h
owns channels h * d to (h + 1) * d of q, k and v, with d = C // n_head, and the scale is 1 / sqrt(d). The
last position, which sees every token, must match the reference math.
Level 3. The mask. Token t sees tokens <= t, so the output at every position matches, and changing later
tokens never moves an earlier output. Build the mask once in __init__ with self.register_buffer, sized for the
longest length you support (an extra argument with a default such as block_size=1024 is fine). A mask kept as a
plain attribute stays on the CPU when the model moves to a GPU, and the tests check for the buffer.
Level 4. GroupedQueryAttention(n_embd, n_head, n_kv_head), also causal, (B, T, C) in and out. The queries
come from self.q = nn.Linear(C, C). The keys and values come from one layer, self.kv = nn.Linear(C, 2 * n_kv_head * d)
with d = C // n_head: the first n_kv_head * d outputs are the key heads, the rest the value heads. Query head h reads key/value head h // (n_head // n_kv_head), and
self.proj = nn.Linear(C, C) mixes the heads. Raise ValueError unless n_head divides n_embd and n_kv_head
divides n_head. With n_kv_head == n_head it's level 3's attention, and with n_kv_head == 1 it's multi-query
attention.
Things to get right: the reshape and transpose for heads (a bare view to (B, H, T, d) scrambles
positions), building the mask once as a buffer, the order of the repeated key/value heads, and the cost: FLOPs and
memory per layer in terms of B, T, C. Common follow-ups: why multiple heads, why grouped-query and multi-query
attention shrink the KV cache, and how FlashAttention avoids materializing the T x T matrix.