840. Write multi-head attention that works for self and cross attention
Write multi-head scaled dot-product attention from scratch, with plain Python lists, so the same function serves self attention and cross attention.
mha(x_q, x_kv, Wq, Wk, Wv, Wo, num_heads, causal=False) takes queries x_q (n rows of width d_in), keys and values source x_kv (m rows of width d_in) and weight matrices Wq, Wk, Wv of shape d_in by d and Wo of shape d by d. Compute Q = x_q Wq, K = x_kv Wk, V = x_kv Wv. Split the d columns into num_heads equal heads of width hd = d / num_heads (head h uses columns h*hd to (h+1)*hd - 1). For each head, scores are Q_h K_h^T divided by sqrt(hd), softmax over keys, times V_h. Concatenate heads in order and multiply by Wo. If causal is True (only used when n == m), query i may not attend to keys j > i. Return an n by d list of lists.
Self attention is the case x_kv is x_q; cross attention passes a different x_kv, for example encoder outputs.
def mha(x_q, x_kv, Wq, Wk, Wv, Wo, num_heads, causal=False)Example 1
with x_q = x_kv = [[1, 0], [0, 1], [1, 1]], identity Wq, Wk, Wv, Wo, one head and causal=True, the first output row is [1.0, 0.0] because the first query can only see itself.
Example 2
Input: x_q = X3, x_kv = X3, Wq = I2, Wk = I2, Wv = I2, Wo = I2, num_heads = 1, causal = True
Output: [[1.0, 0.0], [0.330238, 0.669762], [0.751745, 0.751745]]
Example 3
Input: [len(mha(XA, XB, W4, W4, W4, W4, 2)), len(mha(XA, XB, W4, W4, W4, W4, 2)[0])]
Output: [3, 4]
Constraints
- 1 <= n, m <= 64
- d is divisible by
num_heads d_in, d <= 64
Hint 1
Compute Q, K and V before splitting heads.
Hint 2
Scale by sqrt(hd), where hd = d / num_heads.
Hint 3
Mask future keys with minus infinity and use a max-subtracted softmax.
Common mistakes
- Scaling by
sqrt(d)instead ofsqrt(hd). - Taking K and V from
x_qin cross attention. - Applying softmax over queries instead of over keys.
- Forgetting the output projection.
Understand the idea
Multi-head attention runs several smaller attentions in parallel on slices of the projected vectors, then mixes them with an output projection. Shapes are the main thing to get right: Q is n by d, K and V are m by d, each head uses hd = d / num_heads columns, scores are n by m, and the output is n by d. Cross attention only changes where K and V come from; the causal mask is a self attention concept for decoders. The sqrt(hd) scale keeps dot products from growing with the head width, which would push softmax into near one-hot outputs.