Multi-Head Attention
Implement multi-head attention by splitting Q, K, V into multiple heads.
Given Q, K, V of shape (n, d) and number of heads h:
- Split each into h heads: reshape (n, d) → (n, h, d/h) → (h, n, d/h)
- Apply scaled dot-product attention per head: , with the softmax taken over each row (the scale uses the per-head width , not )
- Concatenate heads: (h, n, d/h) → (n, d)
Assume d is divisible by h. No linear projections needed — just split and concat.
Input: multi_head_attention(Q, K, V, h) where Q, K, V are NumPy arrays of shape (n, d) and h is the number of heads.
Output: Multi-head attention output as an (n, d) array; the tests print each value to 4 decimal places.
Example
2 4 2 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 2 3 4 5 6 7 8
[2.3210 3.3210 4.3210 5.3210] [3.6790 4.6790 5.6790 6.6790]
- Inputs: , , are (two tokens, features) and
h, so each head owns consecutive features: head 1 the first two columns, head 2 the last two. That gives , , , . - Scores: each head scales by , not . Both and equal , so both heads score .
- Row softmax: , each token puts on itself and on the other.
- Weighted values: token 1 gets from head 1 and from head 2; token 2 gets and .
- Output: each token's two head results sit side by side, rounded to 4 decimal places:
[2.3210 3.3210 4.3210 5.3210]and[3.6790 4.6790 5.6790 6.6790]. - Notice head 2's values are exactly head 1's plus 2: and every row of weights sums to 1.
Constraints
- d is divisible by h
- 1 <= h <= d, 1 <= n <= 10
- No projection matrices — just split/concat
- Round to 4 decimal places