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.)

Signaturedef 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,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleretention([[1.0, 2.0]], [[3.0, 1.0]], [[2.0]], 0.9)
  • Sample 2: recurrentretention(_Q, _K, _V, 0.8)