Split and merge attention heads
Multi-head attention runs several smaller attentions in parallel. The trick is all reshapes: split the model dimension into heads, attend per head, glue the heads back.
Write multihead_attention(x, Wq, Wk, Wv, Wo, n_heads) for x of shape (T, d) and square (d, d) weights. Steps:
1. Q = x Wq, K = x Wk, V = x Wv.
2. Reshape each to (T, n_heads, d_head) and move heads first: (n_heads, T, d_head).
3. Per head: softmax(Q K^T / sqrt(d_head)) V, no mask.
4. Move back to (T, n_heads, d_head), reshape to (T, d), multiply by Wo.
def multihead_attention(x, Wq, Wk, Wv, Wo, n_heads)Understand the idea
Multi-head attention runs several smaller attentions side by side, each on its own slice of the features. The tricky part is only reshaping: each token's features must be cut into head-sized slices without mixing tokens. Reshape (T, d) to (T, heads, d_head) first, then move the head axis to the front. Worked example: T = 2, d = 4, 2 heads, d_head = 2. Q = [[0, 1, 2, 3], [4, 5, 6, 7]]. Correct split: head 0 gets [[0, 1], [4, 5]] and head 1 gets [[2, 3], [6, 7]], so each head sees both tokens. Reshaping straight to (2, 2, 2) would give head 0 [[0, 1], [2, 3]], treating halves of token 0 as two tokens, which is wrong. Each head then computes softmax(Q K^T / sqrt(2)) V with no mask; afterwards move heads back to (T, heads, d_head), reshape to (T, d) and multiply by Wo. Every transformer layer in GPT, BERT and Llama does this split and merge.