Implement differential attention with the lambda reparameterization

Why it matters Differential attention is a recent idea for reducing attention noise in long contexts, and coding it is a good exercise in reading a paper's equations exactly.

Differential attention computes two softmax attention maps and subtracts one from the other, which cancels attention noise that both maps share.

Write diff_attention(x, Wq1, Wk1, Wq2, Wk2, Wv, lq1, lk1, lq2, lk2, lam_init). x is (T, d); the four Wq/Wk matrices are (d, dk); Wv is (d, dv); lq1, lk1, lq2, lk2 are vectors of length dk.
1. lam = exp(lq1 . lk1) - exp(lq2 . lk2) + lam_init.
2. A1 = causal_softmax((x Wq1)(x Wk1)^T / sqrt(dk)) and A2 the same with Wq2, Wk2.
3. out = (A1 - lam * A2) @ (x Wv).
Return (out, lam) with lam as a float.

Signaturedef diff_attention(x, Wq1, Wk1, Wq2, Wk2, Wv, lq1, lk1, lq2, lk2, lam_init)

Example

x = [[1, 0], [0, 1]], all five weight matrices the identity, all lambda vectors zero and lam_init = 0.8 gives lam = 0.8 and out = [[0.2, 0], [0.066, 0.134]].

Understand the idea

Softmax attention always gives some weight to irrelevant tokens, a kind of background hum. Differential attention runs two attention maps and subtracts one from the other, the way noise-cancelling headphones subtract a copy of the outside noise. Weight that both maps put on irrelevant tokens cancels, and the real signal stays.

Example: if both maps are identical, out = (1 - lam) A V. With lam = 0.8 only 20% of the usual output remains, so for the 2-token case with identity weights row 1 is 0.2 * [0.33, 0.67] = [0.066, 0.134].

Rule: lam = exp(lq1 . lk1) - exp(lq2 . lk2) + lam_init; out = (softmax(Q1 K1^T / sqrt(dk)) - lam * softmax(Q2 K2^T / sqrt(dk))) V, both causal.

The lambda reparameterization keeps lam learnable and close to lam_init early in training. The full Differential Transformer also normalises each head's output, which this exercise leaves out.

Shapes and data flow

x (T, d) -> q1, k1, q2, k2 (T, dk) -> A1, A2 (T, T) -> v (T, dv) -> out (T, dv)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplediff_attention([[1.0, 0.0], [0.0, 1.0]], np.eye(2), np.eye(2), np.eye(2), np.eye(2), np.eye(2), [0.0, 0.0],...
  • Sample 2: randomdiff_attention(Xd, W1, W2, W3, W4, W5, [0.1, -0.2], [0.3, 0.1], [0.0, 0.2], [0.2, 0.2], 0.5)