Implement causal multi-head attention and match GPT-2
CPU · your Macnotebook120 minrequiredGoal · Write a from-scratch attention function that reproduces the output of GPT-2 layer 0's attention block given the same weights.
- 1Load gpt2 and grab block 0, model.transformer.h[0]; extract attn.c_attn and attn.c_proj weights and biases.
- 2Write my_attention(x, W_qkv, b_qkv, W_proj, b_proj, n_head) using only matmul, reshape, transpose, softmax and a causal mask.
- 3Feed the layer-normed hidden state of a 16-token prompt (hook block 0's ln_1 output) into both your function and the real attn module.
- 4Compare with torch.allclose(atol=1e-5) and print max absolute difference.
- 5Remove the 1/sqrt(d_k) scaling and observe how the attention weights change (print entropy per head).
- 6Plot the (16, 16) attention weight matrix for heads 0 to 3 as heatmaps and verify the upper triangle is zero.
- Deliverable
- A notebook with the matching assertion, the max-diff number and the heatmaps.
- Check
- torch.allclose passes at atol 1e-5 and every attention row sums to 1.0 within 1e-6.