Scaled Dot-Product & Multi-Head Attention
Key idea: softmax(QKᵀ/√d)V with an optional causal mask (-inf above the diagonal). Multi-head = reshape (N, T, D) → (N, h, T, D/h), attend per head, merge, project.
import numpy as np
def attention(Q, K, V, causal=False): # (..., T, d)
d = Q.shape[-1]
scores = Q @ np.swapaxes(K, -1, -2) / np.sqrt(d) # (..., T, T)
if causal:
T = scores.shape[-1]
scores = np.where(np.tril(np.ones((T, T), bool)), scores, -np.inf)
scores = scores - scores.max(-1, keepdims=True)
w = np.exp(scores)
w /= w.sum(-1, keepdims=True)
return w @ V, w
def multi_head(x, Wq, Wk, Wv, Wo, h, causal=True): # x: (N, T, D)
N, T, D = x.shape
split = lambda t: t.reshape(N, T, h, D // h).transpose(0, 2, 1, 3) # (N, h, T, D/h)
out, _ = attention(split(x @ Wq), split(x @ Wk), split(x @ Wv), causal)
return out.transpose(0, 2, 1, 3).reshape(N, T, D) @ Wo
rng = np.random.default_rng(0)
N, T, D, h = 2, 5, 16, 4
x = rng.normal(size=(N, T, D))
W = [rng.normal(size=(D, D)) / np.sqrt(D) for _ in range(4)]
y = multi_head(x, *W, h=h)
assert y.shape == (N, T, D)
_, w = attention(x, x, x, causal=True)
assert np.allclose(np.triu(w[0], 1), 0) and np.allclose(w.sum(-1), 1) # no peeking at the future
x2 = x.copy(); x2[:, -1] += 10 # changing the last token
assert np.allclose(multi_head(x2, *W, h=h)[:, :-1], y[:, :-1]) # doesn't affect earlier outputs
print("ok", y.shape)