1/23
Learn

Tensor shapes for attention

Model coding rounds ask you to write attention, a small GPT or a KV cache in PyTorch. Most lines of those programs move a tensor from one shape to another, and a wrong move often runs with no error. This lesson's practice problem puts those moves in five small functions:

Write five functions in PyTorch, with no Python loops over batches, heads or positions. B is the number of sequences, T the tokens in each, C the channels per token, H the heads, and d = C // H.

  1. split_heads(x, n_head): x is (B, T, C). Return (B, n_head, T, d), where head h at position t holds channels h * d to h * d + d - 1 of position t. Raise ValueError when n_head doesn't divide C.
  2. merge_heads(y): y is (B, H, T, d). Return (B, T, H * d), so that merging undoes the split.
  3. causal_softmax(scores): scores is (..., T, T). Return softmax weights over the keys, with exactly 0 on every key after the query.
  4. append_greedy(idx, logits): idx is (B, T) token ids and logits is (B, T, V). Return (B, T + 1): each sequence with its top-scoring next token added at the end.
  5. qkv_heads(qkv, n_head): qkv is (B, T, 3C), the queries, then the keys, then the values. Return (q, k, v), each split into heads.
CallReturns
split_heads(x, 2), with x = [[[0, 1, 2, 3], [10, 11, 12, 13]]][[[[0, 1], [10, 11]], [[2, 3], [12, 13]]]]
merge_heads of that result[[[0, 1, 2, 3], [10, 11, 12, 13]]], the x you started with
causal_softmax(torch.zeros(3, 3))rows [1, 0, 0], [0.5, 0.5, 0] and [0.33, 0.33, 0.33]
append_greedy(idx, logits), with idx = [[0, 2]] and last-position scores [0.5, 0.1, 3.0][[0, 2, 2]]

This lesson teaches those moves one at a time, each with a small task: what changes from NumPy, the five letters that name every shape, then the split, the merge, the mask and one step of text generation. The whole problem comes back at the end, as the lesson's practice, from a blank file.