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.
Bis the number of sequences,Tthe tokens in each,Cthe channels per token,Hthe heads, andd = C // H.
split_heads(x, n_head):xis(B, T, C). Return(B, n_head, T, d), where headhat positiontholds channelsh * dtoh * d + d - 1of positiont. RaiseValueErrorwhenn_headdoesn't divideC.merge_heads(y):yis(B, H, T, d). Return(B, T, H * d), so that merging undoes the split.causal_softmax(scores):scoresis(..., T, T). Return softmax weights over the keys, with exactly 0 on every key after the query.append_greedy(idx, logits):idxis(B, T)token ids andlogitsis(B, T, V). Return(B, T + 1): each sequence with its top-scoring next token added at the end.qkv_heads(qkv, n_head):qkvis(B, T, 3C), the queries, then the keys, then the values. Return(q, k, v), each split into heads.
Call Returns split_heads(x, 2), withx=[[[0, 1, 2, 3], [10, 11, 12, 13]]][[[[0, 1], [10, 11]], [[2, 3], [12, 13]]]]merge_headsof that result[[[0, 1, 2, 3], [10, 11, 12, 13]]], thexyou started withcausal_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), withidx=[[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.