Add QK-norm to multi-head causal attention

Why it matters Several recent open models use QK-norm to keep attention logits from growing and destabilising large-scale training.

Very large attention logits make training unstable. QK-norm applies RMSNorm to each head's query and key vectors before the dot product, which bounds the logits.

Write qk_norm_attention(x, Wq, Wk, Wv, g_q, g_k, n_heads, eps=1e-6). x is (T, d); Wq, Wk, Wv are (d, d); g_q and g_k are gains of shape (hd,) with hd = d // n_heads.
1. q, k, v = x @ Wq, x @ Wk, x @ Wv, each reshaped to (n_heads, T, hd) (head h uses columns h*hd to (h+1)*hd).
2. Per head and position: q = q / sqrt(mean(q^2) + eps) * g_q over the hd axis, and the same for k with g_k.
3. Causal softmax of q @ k^T / sqrt(hd) per head, times v.
4. Merge heads back to (T, d) and return it (no output projection).

Signaturedef qk_norm_attention(x, Wq, Wk, Wv, g_q, g_k, n_heads, eps=1e-6)

Example

x = [[1, 0], [0, 1]], Wq = Wk = Wv = identity, gains [1, 1], n_heads = 1 gives [[1, 0], [0.1956, 0.8044]].

Understand the idea

Attention scores are dot products of query and key vectors. If those vectors grow during training, scores blow up, softmax becomes one-hot and gradients vanish. QK-norm is a seat belt: it rescales every query and key to a fixed size first.

Example: one head, q1 = [0, 1]. Its RMS is sqrt((0 + 1) / 2) = 0.707, so the normalised q1 is [0, 1.414]. Keys [1, 0] and [0, 1] become [1.414, 0] and [0, 1.414]. The dot products are 0 and 2; divided by sqrt(2) they are 0 and 1.414; softmax gives about 0.196 and 0.804.

Rule: per head, q = g_q * q / sqrt(mean(q^2) + eps), same for k, then softmax(q k^T / sqrt(hd)) v with a causal mask.

With normalised q and k, the largest possible score is bounded by the gains, no matter how large Wq and Wk get. Several recent open-weight LLMs use it to make large-scale training more stable.

Shapes and data flow

x (T, d) -> q, k, v (H, T, hd) -> normalised q, k (H, T, hd) -> scores (H, T, T) -> out (H, T, hd) -> (T, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleqk_norm_attention([[1.0, 0.0], [0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), [1.0, 1.0], [1.0, 1.0], 1)
  • Sample 2: two headsqk_norm_attention(X, A, B, C, [1.0, 0.5], [2.0, 1.0], 2)
  • Test 3: big weights stay boundedqk_norm_attention(X, 100 * A, 100 * B, C, [1.0, 1.0], [1.0, 1.0], 2)