Multi-head self-attention forward pass
Problem
- Shapes:
X(T, d_model);Wq,Wk,Wv(d_model, d_model);Wo(d_model, d_out); no biases. - ComputeQ = XWq,K = XWk,V = XWv. - Split the last dimension intonum_headscontiguous blocks of sizeh = d_model/num_heads; head i uses columns[i·h, (i+1)·h). - Apply scaled dot-product attention per head with scale1/√h. Ifcausal, position t may only attend to positions ≤ t. - Concatenate the heads in order and multiply byWo. Return shape (T, d_out).
Signature
def multi_head_attention(X, Wq, Wk, Wv, Wo, num_heads: int, causal: bool = False) -> np.ndarray: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(multi_head_attention([[1.0, 0.0],[0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), np.eye(2), 1), [[0.669762, 0.330238], [0.330238, 0.669762]])
True
>>> close(multi_head_attention([[1.0, 0.0],[0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), np.eye(2), 2), [[0.731059, 0.5], [0.5, 0.731059]])
TrueHints
Compute Q, K, V as XW; split the last dim into contiguous heads.
Per head: scaled dot-product attention with scale 1/sqrt(h); causal masks position t to attend to <= t only.
Concatenate heads in order, multiply by Wo, return (T, d_out).
Reference solution
import math
import numpy as np
def multi_head_attention(X, Wq, Wk, Wv, Wo, num_heads, causal=False):
X = np.asarray(X, float)
Q = X @ np.asarray(Wq, float); K = X @ np.asarray(Wk, float); V = X @ np.asarray(Wv, float)
T, d = Q.shape
assert d % num_heads == 0
h = d // num_heads
mask = np.tril(np.ones((T, T), bool)) if causal else None
heads = []
for i in range(num_heads):
sl = slice(i * h, (i + 1) * h)
o, _ = attention(Q[:, sl], K[:, sl], V[:, sl], mask)
heads.append(o)
return np.concatenate(heads, axis=1) @ np.asarray(Wo, float)
def attention(Q, K, V, mask=None):
Q = np.asarray(Q, float); K = np.asarray(K, float); V = np.asarray(V, float)
s = Q @ K.T / math.sqrt(Q.shape[1])
if mask is not None:
s = np.where(np.asarray(mask, bool), s, -np.inf)
s = s - s.max(axis=1, keepdims=True)
w = np.exp(s)
w = w / w.sum(axis=1, keepdims=True)
return w @ V, wWhat a strong solution covers
- Correct reshape/transpose (or slicing) per head.
- Uses the head dimension for scaling.
- Builds the causal mask with
np.tril. - Verifies shapes.
- Discusses batching (B, H, T, h), KV caching for decoding, and GQA.
Common mistakes
- scaling by √d_model
- interleaving columns across heads instead of contiguous blocks.