Causal linear attention with a running state
Softmax attention costs O(T^2) in sequence length. Linear attention (Katharopoulos et al., 2020, "Transformers are RNNs") replaces exp(q.k) with phi(q).phi(k) for a positive feature map phi. Then the sum over past keys can be kept as a running state, so each new token costs O(1) in T, like an RNN.
Write linear_attention(Q, K, V). Q and K have shape (T, d), V has shape (T, dv). Use phi(x) = elu(x) + 1, where elu(x) = x for x > 0 and exp(x) - 1 otherwise. The attention is causal:
- S_t = sum over j <= t of outer(phi(K[j]), V[j]), shape (d, dv)
- z_t = sum over j <= t of phi(K[j]), shape (d,)
- out[t] = phi(Q[t]) @ S_t / (phi(Q[t]) @ z_t)
Return out with shape (T, dv). Update S and z as you go instead of recomputing the sums.
def linear_attention(Q, K, V)Understand the idea
Softmax attention compares every query with every key, slow for long inputs. Linear attention swaps exp(q . k) for phi(q) . phi(k), with phi a positive feature map. The sum over past keys then becomes a running state, like an RNN. Here phi(x) = elu(x) + 1, which is x + 1 for positive x and exp(x) for the rest. Worked example: T = 2, d = dv = 1, Q = [[1], [1]], K = [[0], [1]], V = [[2], [4]]. phi(0) = 1, phi(1) = 2. Step 0: S = 1 * 2 = 2, z = 1, out = 2 * 2 / (2 * 1) = 2. Step 1: S = 2 + 2 * 4 = 10, z = 1 + 2 = 3, out = 2 * 10 / (2 * 3) = 3.333, a 1 : 2 weighting of the values 2 and 4. Rule: at each t, add outer(phi(K[t]), V[t]) to S and phi(K[t]) to z, then out[t] = phi(Q[t]) S / (phi(Q[t]) . z). Summing over all tokens at once leaks the future. Used in RNN-style long-context models.