28Tensor shapes for attention (PyTorch)

easytorch
25:00

28 Tensor shapes for attention (PyTorch)

Five small functions, one level each. Each one is a step the multi-head attention, GPT, KV cache and decoding lessons take in a line or two. Shapes use the course's letters: B sequences, T tokens each, C channels per token, H heads, and d = C // H channels per head.

Set a 25-minute timer. Read one level at a time and run only its tests until they pass: pytest problems/28_tensor_shapes -k level1. Earlier levels must keep passing. No Python loops over batches, heads or positions.

Level 1. split_heads(x, n_head). x is (B, T, C). Return (B, n_head, T, d) with d = C // n_head, where head h at position t holds channels h * d to h * d + d - 1 of position t. Raise ValueError when C isn't divisible by n_head.

Level 2. merge_heads(y). y is (B, H, T, d), a fresh tensor like the output of att @ v. Return (B, T, H * d) with each position's heads side by side again, so that merge_heads(split_heads(x, n_head)) gives back x.

Level 3. causal_softmax(att). att is (..., T, T) scores: row i holds query i's scores against keys 0 to T - 1. Return weights of the same shape: a softmax over the keys in which every key after the query (j > i) gets exactly 0, so every row sums to 1 over the keys it may see. Leave att itself unchanged.

Level 4. append_greedy(idx, logits). idx is (B, T) token ids (int64) and logits is (B, T, V). Return (B, T + 1), still int64: idx with one more column, the id of the highest-scoring token at each sequence's last position.

Level 5. qkv_heads(qkv, n_head). qkv is the (B, T, 3C) output of a fused projection: the first C channels are the queries, the next C the keys, the last C the values. Return a tuple (q, k, v), each split into heads as in level 1, (B, n_head, T, d).

Things to get right: view then transpose(1, 2) for the split (a bare reshape to (B, H, T, d) mixes positions and raises nothing), reshape or contiguous() after the transpose in the merge (view fails on a transposed tensor), which positions masked_fill fills, the axis the softmax runs over, keepdim=True before torch.cat, and that split takes the size of each piece, not how many pieces.

solution.py
Run the tests to see which pass.