488. 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)Example 1
Input: linear_attention([[1.0], [1.0]], [[1.0], [0.0]], [[2.0], [4.0]])
Output: [[2.0], [2.6667]]
Constraints
Khas shape(T, d)Vhas shape(T, dv)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Keep S and z as accumulators.
Hint 2
At step t add the outer product of phi(K[t]) and V[t] to S and phi(K[t]) to z, then read out with phi(Q[t]).
Common mistakes
- The buggy version sums over all tokens at once, so early positions see future keys and values.
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.
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.
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.
Topics
Companies1
- Meta the topic appears in interview reports Machine Learning interview questions, page 10 (KatKat)
From public interview reports and guides. Not affiliated with or endorsed by these companies.