Run the gated delta rule for linear attention

Why it matters Gated delta rule layers appear in recent hybrid LLMs to get long context with constant memory per layer.

Linear-attention models keep a fixed-size state matrix instead of a growing KV cache. The gated delta rule updates it by decaying the old memory and then correcting the value stored at the current key.

Write gated_delta(q, k, v, alpha, beta). q and k are (T, dk), v is (T, dv), alpha and beta are length-T arrays in [0, 1]. Start with S = zeros (dv, dk). For each t:
S = alpha_t * S @ (I - beta_t * outer(k_t, k_t)) + beta_t * outer(v_t, k_t)
o_t = S @ q_t
Return (O, S): O is the (T, dv) array of outputs and S the final state.

Signaturedef gated_delta(q, k, v, alpha, beta)

Example

gated_delta([[1, 0]], [[1, 0]], [[2]], [0.5], [1]) returns O = [[2]] and S = [[2, 0]].

Understand the idea

Think of the state S as a small key-value memory. Asking it about key k returns S k. Plain linear attention just keeps adding v k^T, so memories pile on top of each other. The delta rule instead corrects: it moves what the memory returns for k toward the new value v, like editing a contact instead of adding a duplicate. The gate alpha slowly forgets old content.

Expanded, the update is S = alpha S + beta (v - alpha S k) k^T for a unit key: decay, then fix the error at k.

Example: key [1, 0]. Step 1 stores value 2 with beta 1: S = [[2, 0]]. Step 2 stores value 5 at the same key with alpha 1, beta 1: S k = 2, the error is 3, so S becomes [[5, 0]]. Plain linear attention would have given 7.

Rule: S_t = alpha_t S_{t-1} (I - beta_t k_t k_t^T) + beta_t v_t k_t^T; o_t = S_t q_t.

Gated DeltaNet layers built on this rule are used in several recent hybrid long-context models.

Shapes and data flow

S (dv, dk); outer(k, k) (dk, dk); outer(v, k) (dv, dk); o_t = S q_t (dv,); O (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: examplegated_delta([[1.0, 0.0]], [[1.0, 0.0]], [[2.0]], [0.5], [1.0])
  • Sample 2: overwrite same keygated_delta([[1.0, 0.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 0.0]], [[2.0], [5.0]], [1.0, 1.0], [1.0, 1.0])