01Scaled dot-product attention (NumPy)
01 Scaled dot-product attention (NumPy)
Four levels, one function each, in solution.py. Read one level at a time and run only its tests until they
pass: pytest problems/01_attention -k level1. Earlier levels must keep passing.
q is (..., T_q, d), k is (..., T_k, d) and v is (..., T_k, d_v). The leading axes (batch, heads) can
be anything, and no Python loop may run over them: a test counts the array operations you run.
Level 1. softmax(x, axis=-1). Each slice along axis becomes weights that are positive and sum to 1. It must
survive logits around 1e4 with no inf or nan.
Level 2. attention(q, k, v). Return softmax(q k^T / sqrt(d)) v, shape (..., T_q, d_v), with the softmax
over the keys.
Level 3. attention(q, k, v, causal=True), with T_q == T_k: position i may only attend to positions
j <= i. causal=False keeps level 2's behavior.
Level 4. attention_blocks(q, k, v, block). The same output as attention(q, k, v), but read the keys and
values block at a time, and never build an array of shape (..., T_q, T_k). Keep a running max, a running sum
and a running blend for each query, and rescale the sum and the blend when a block brings a bigger max. block
need not divide T_k. A loop over the blocks is fine. A test measures your peak memory, so filling a
preallocated (..., T_q, T_k) array block by block fails too.
Things to get right: the 1/sqrt(d) scale and why it's there, masking BEFORE the softmax, the max-subtraction,
which axis the softmax runs over, and the O(T^2) memory of the score matrix, which level 4 removes.