Implement recurrent retention from RetNet
Why it matters Linear-attention families (RetNet, Mamba-2, RWKV) serve long contexts with O(1) state per token this way.
RetNet's retention can be computed in parallel like attention or recurrently like an RNN, with the same result.
Write retention(Q, K, V, gamma). Q, K are (T, d), V is (T, dv). Parallel form: O = (Q K^T * D) V with D[n, m] = gamma^(n - m) for n >= m else 0. Implement the recurrent form: S_0 = 0 (d, dv), S_n = gamma * S_{n-1} + K_n^T V_n (outer product), O_n = Q_n S_n. Return O (T, dv). (Tests compare with the parallel form.)
def retention(Q, K, V, gamma)Example
with T = 1, O = (Q_0 . K_0) V_0.
Understand the idea
Retention in RetNet is like attention without softmax, plus a decay: a token m contributes to output n with weight gamma^(n - m), so older tokens fade. It can be computed in parallel with a decay mask, or recurrently with a small state matrix that is decayed and updated each step. Worked example: T = 2, d = dv = 1, Q = [[1], [1]], K = [[1], [2]], V = [[3], [1]], gamma 0.5. Step 1: S = 0 * 0.5 + 1 * 3 = 3, O_1 = 1 * 3 = 3. Step 2: S = 0.5 * 3 + 2 * 1 = 3.5, O_2 = 1 * 3.5 = 3.5. The parallel form agrees: O_2 = 0.5 * (1 * 1) * 3 + 1 * (1 * 2) * 1 = 3.5. Rule: S starts as a (d, dv) zero matrix; for each n, S = gamma * S + outer(K_n, V_n); O_n = Q_n @ S. The decay multiplies the whole old state, not just the new term; that is what produces gamma^(n - m). Used in: RetNet and related linear attention and state space style models.
Shapes and data flow
state S (d, dv)
S_n = gamma S_{n-1} + outer(K_n, V_n)
O_n = Q_n (d,) @ S_n -> (dv,)Similar problems
- FlashAttention-style tiled causal attention forward (Dao et al., 2022)HardPro
- Mamba-style selective state-space scan with zero-order-hold discretizationHardPro
- Implement differential attention with the lambda reparameterizationHardPro
- Knowledge distillation loss with temperature (Hinton et al., 2015)MediumPro