Beyond transformers: SSMs, Mamba, linear attention¶
Attention remembers by keeping everything; a recurrent model remembers by compressing everything into a state of fixed size. Linear attention, state space models and Mamba are one family of compressors that train in parallel like a transformer and generate like an RNN. Their whole design question is what to forget, and their whole weakness is exact recall.
10,000 ft
A transformer's memory of the past is its KV cache: one key and value per token per layer, so memory grows linearly and attention compute quadratically with context. RNNs had the opposite profile — a fixed-size state, constant cost per token — but trained sequentially and forgot. Since 2020 a line of work has rebuilt the RNN so that it trains in parallel on GPUs: linear attention (drop the softmax and attention becomes a recurrence), structured state space models (S4: a discretised linear dynamical system), Mamba (make that system's parameters depend on the input) and the delta rule (write to memory by correcting it, not just adding). By 2024 these lines had converged on one equation, and by 2025 production models were using them as hybrids: mostly recurrent layers with a few full-attention layers kept for exact recall — Jamba, MiniMax-01, Qwen3-Next, Kimi Linear. This page is the frontier of long context by architecture rather than by kernel.
2,000 ft
Every model on this page keeps a matrix state \(S_t\) and updates it once per token:
- Linear attention: \(G_t = I\). Never forgets; additive writes pile up.
- Decay / gating (RetNet, GLA, Mamba-2): \(G_t = \gamma_t I\) or a diagonal, with \(\gamma_t\) fixed or computed from the input. Old memories fade.
- State space models (S4, Mamba): the same recurrence derived from a continuous-time system; Mamba makes the step size and maps input-dependent ("selective").
- Delta rule (DeltaNet, Gated DeltaNet): \(G_t = I - \beta_t\mathbf{k}_t\mathbf{k}_t^\top\). Before writing a key's value, erase what that key currently retrieves.
- Training uses a parallel form (an attention-like matrix with a decay mask, or a parallel scan), computed chunk by chunk; generation uses the recurrence with constant memory.
- The price: a fixed state cannot store an unbounded number of facts exactly, so pure recurrent models lag on recall and copying. Hybrids add a few attention layers back.
Ground level¶
The cost being attacked¶
Concretely: Llama 3 8B caches \(2 \times 32 \text{ layers} \times 8 \text{ KV heads} \times 128 \times 2\) bytes \(=\) 128 KiB per token. At 128K tokens that is 16 GiB per sequence; at 1M tokens, 128 GiB — more than the 16 GB of weights several times over (see the cache table).
Now take a recurrent model of similar width: 32 layers, inner width 8,192 (Mamba's usual \(2\times\) expansion of \(d = 4096\)) and a state of \(N = 128\) numbers per channel (the Mamba-2 reference code calls 64 or 128 typical). Its state is \(8192 \times 128 = 1{,}048{,}576\) numbers per layer, 2 MiB in BF16, 64 MiB in total — whether the context is 10 tokens or 10 million. That is the same number of bytes as 512 tokens of Llama 3 8B's cache. Everything the model knows about the past must fit in what a transformer would spend on one paragraph.
| context | transformer (Llama 3 8B cache) | hybrid, 1 attention layer in 8 | pure recurrent (64 MiB state) |
|---|---|---|---|
| 4K | 0.50 GiB | 0.12 GiB | 0.06 GiB |
| 32K | 4.0 GiB | 0.56 GiB | 0.06 GiB |
| 128K | 16.0 GiB | 2.06 GiB | 0.06 GiB |
| 1M | 128 GiB | 16.1 GiB | 0.06 GiB |
(The hybrid row keeps 4 of 32 layers as attention and 28 as recurrent. The configuration is illustrative; real models differ in detail, and states are often kept in FP32, which doubles the last column.)
Memory is the headline, but it implies the rest: no cache means larger batches fit on a GPU, so throughput rises (Mamba reported 4–5× the inference throughput of a similar-size transformer, attributing it to "much higher batch sizes"), and each decode step reads a constant number of bytes, so time per token does not grow with context.
Linear attention: drop the softmax, get an RNN¶
Causal attention for one query is
Katharopoulos et al. replaced the exponential with a product of feature maps, \(\operatorname{sim}(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^\top\phi(\mathbf{k})\), with \(\phi(x) = \operatorname{elu}(x) + 1\) to keep similarities positive (arXiv:2006.16236). Then \(\phi(\mathbf{q}_t)\) factors out of both sums:
That is an RNN whose hidden state is the \(d \times d\) matrix \(S_t\). The whole trick is associativity: \((QK^\top)V\) costs \(O(n^2 d)\) and needs an \(n \times n\) matrix; \(Q(K^\top V)\) costs \(O(nd^2)\) and needs a \(d \times d\) one. For \(n = 1024\), \(d = 64\) our NumPy check below gives \(2.7 \times 10^8\) against \(1.7 \times 10^7\) FLOPs — and the gap widens linearly with \(n\). The paper reports up to 4,000× faster autoregressive generation on very long sequences.
Read and write. It helps to read \(S_t\) as an associative memory. Writing the pair \((\mathbf{k}, \mathbf{v})\) adds the outer product \(\mathbf{v}\mathbf{k}^\top\) (we will use this orientation, \(S \in \mathbb{R}^{d_v \times d_k}\), from here on). Reading with query \(\mathbf{q}\) returns \(S\mathbf{q} = \sum_j \mathbf{v}_j(\mathbf{k}_j^\top\mathbf{q})\): each stored value weighted by how well its key matches. If keys were orthonormal, \(S\mathbf{k}_i = \mathbf{v}_i\) exactly. Schlag, Irie and Schmidhuber pointed out that this is precisely a fast weight programmer from the early 1990s: a slow network writes the weights \(S\) of a fast one (arXiv:2102.11174).
Why plain linear attention underperformed. Two reasons, both visible in the memory picture. First, it never forgets: \(S_t\) is a sum over all history, so old and irrelevant pairs keep contributing. Second, a \(d_k\)-dimensional key space holds at most \(d_k\) orthogonal keys; past that, every write interferes with earlier ones and recall degrades. Softmax attention has neither problem — its "state" is the whole cache, and the exponential sharpens retrieval onto the best-matching key. Early linear transformers lost noticeably in language-modelling quality, and Performer's random-feature approximation of the softmax kernel (arXiv:2009.14794) did not close the gap either.
Forgetting on purpose: decay and gates¶
The first fix is to let the state fade:
RetNet used a fixed \(\gamma\) per head (arXiv:2307.08621): a pair written \(\tau\) steps ago is weighted by \(\gamma^\tau\), a built-in recency bias like ALiBi. Gated linear attention (GLA) made the decay data-dependent and per-dimension, computed from the current token (arXiv:2312.06635), so the model can decide to hold on through a long quotation and let go at a paragraph break. Its main engineering contribution was a chunkwise training algorithm that runs at GPU matmul speed — the piece that made the whole family practical. Griffin (Google DeepMind) mixed a gated linear recurrence with local attention (arXiv:2402.19427); RWKV evolved from a channel-wise decaying recurrence in 2023 (arXiv:2305.13048) through matrix-valued states (arXiv:2404.05892) to a generalised delta rule in RWKV-7 (arXiv:2503.14456).
State space models: the same idea from control theory¶
The second road started from a continuous-time linear system, the textbook state space model:
with input \(x(t)\), state \(h(t) \in \mathbb{R}^N\) and matrices \(A \in \mathbb{R}^{N\times N}\), \(B \in \mathbb{R}^{N \times 1}\), \(C \in \mathbb{R}^{1 \times N}\), applied to each channel of a sequence. To use it on tokens you discretise with a step size \(\Delta\). The zero-order hold (assume \(x\) is constant across each step) gives
Worked example. A one-dimensional state with \(A = -0.5\) and \(\Delta = 0.1\): \(\bar{A} = e^{-0.05} = 0.951\), so each step keeps 95.1% of the state and a memory's half-life is \(\ln 0.5/\ln 0.951 = 13.9\) steps. With \(\Delta = 0.01\) the half-life is 139 steps; with \(\Delta = 1\) it is 1.4 steps. \(\Delta\) is a timescale knob: small steps mean the system barely moves per token and remembers long; large steps mean it resets to the current input. Hold on to that; it is what Mamba makes input-dependent.
Two properties made SSMs attractive.
- Long memory by construction. HiPPO showed how to choose \(A\) so that the state holds the coefficients of an optimal polynomial approximation of the whole input history (arXiv:2008.07669). Initialised this way, the model starts with a principled memory rather than having to learn one.
- Two ways to compute. When \(\bar{A}, \bar{B}, C\) are the same at every step — linear time-invariant (LTI) — unrolling gives \(y_t = \sum_{j} C\bar{A}^{\,j}\bar{B}\,x_{t-j}\): a convolution with kernel \(\bar{K} = (C\bar{B}, C\bar{A}\bar{B}, C\bar{A}^2\bar{B}, \dots)\). Train as a long convolution with FFTs in \(O(L\log L)\); generate as a recurrence in \(O(1)\) per step.
S4 made this efficient — a normal-plus-low-rank structure for \(A\) reduces the kernel to a Cauchy kernel computation — and its results were startling: state of the art on every Long Range Arena task, including Path-X at length 16K, "that all prior work fails on" (arXiv:2111.00396). Follow-ups showed a diagonal \(A\) is enough (S4D, arXiv:2206.11893), that a parallel scan can replace the convolution (S5, arXiv:2208.04933), and that a carefully parameterised plain linear RNN matches S4 without the continuous-time story (LRU, arXiv:2303.06349).
But on language, LTI SSMs lagged attention. H3 diagnosed why with synthetic tasks: they could not recall a token seen earlier or compare tokens across the sequence well, and needed help from attention or multiplicative gates (arXiv:2212.14052).
Mamba: selection¶
The diagnosis in the Mamba paper is short: an LTI system treats every token the same, so it cannot decide, based on content, what to remember and what to ignore (arXiv:2312.00752). The fix is to make the SSM's parameters functions of the current input:
Now each token sets its own timescale. A large \(\Delta_t\) means "this token matters: reset towards it"; a tiny \(\Delta_t\) means "ignore this token, keep what you have". Mamba's Theorem 1 makes the link to classic RNN gating exact: with \(N = 1\), \(A = -1\), \(B = 1\), the selective SSM becomes \(h_t = (1 - g_t)\,h_{t-1} + g_t\,x_t\) with \(g_t = \sigma(\text{Linear}(x_t))\) — a GRU-style gate.
Selection has a cost: the system is no longer time-invariant, so the convolution trick is gone. Mamba's answer is the hardware lesson of FlashAttention applied to a recurrence: a fused parallel scan that keeps the expanded state (\(D \times N\) per position) in on-chip SRAM, never writes it to HBM, and recomputes it in the backward pass. A linear recurrence \(h_t = a_t h_{t-1} + b_t\) can be computed in \(O(\log L)\) parallel rounds because combining two steps is associative (derived below).
The Mamba block wraps the selective SSM in a gated MLP-like structure: project up by an expansion factor \(E = 2\), a short causal convolution, the SSM, multiply by a SiLU gate branch, project down. It replaces both the attention and the MLP of a transformer block, with about \(3ED^2\) parameters per block. The results in the paper: selective copying at 99.8% where LTI S4 got 18.3%; induction heads trained at length 256 generalising perfectly to length one million, "4000× longer than it saw during training"; and Mamba-3B outperforming transformers of the same size and matching transformers twice its size in pre-training and downstream evaluation.
The duality: SSMs are linear attention with a mask¶
Write the selective recurrence for all positions at once. Unrolling \(h_t = A_t h_{t-1} + B_t x_t\), \(y_t = C_t^\top h_t\) gives \(y = Mx\) with
Mamba-2 restricts each \(A_t\) to a scalar times the identity, \(A_t = a_t I\). Then \(M_{ji} = (a_j \cdots a_{i+1})\,C_j^\top B_i\), that is,
Rename \(C \to Q\), \(B \to K\) and this is causal linear attention with a decay mask \(L\) — exactly the decayed linear attention of the previous section. Dao and Gu called this state space duality (SSD) (arXiv:2405.21060): the same layer can be computed quadratically (as masked attention, good for tensor cores) or linearly (as a recurrence, good for long sequences). Their algorithm does both: quadratic within chunks of a few dozen to a few hundred tokens, recurrent between chunks. Mamba-2 is reported 2–8× faster than Mamba's scan, crosses over FlashAttention-2 at about 2K tokens and is about 6× faster at 16K, and allows states 8× larger than Mamba's with little slowdown — which matters, as the next sections show.
The delta rule: writing by correction¶
Decay fixes "never forgets" but not "can't update". Suppose the state holds capital_of_X → A and the text says the capital moved to B. Additive writing stores A + B under the same key; decay can only fade everything at once. The delta rule reads what the key currently retrieves, then writes the difference:
With \(\beta_t = 1\) and a unit-norm key, \(S_t\mathbf{k}_t = \mathbf{v}_t\) exactly: the old value is erased and replaced. This is one step of online gradient descent on the regression loss \(\tfrac12\|S\mathbf{k}_t - \mathbf{v}_t\|^2\) — the model learns its memory at test time, token by token. Schlag et al. proposed it for linear transformers in 2021; Yang et al. made it trainable at scale with a chunkwise parallel algorithm (arXiv:2406.06484); Gated DeltaNet combined it with Mamba-2-style decay, \(S_t = \alpha_t S_{t-1}(I - \beta_t\mathbf{k}_t\mathbf{k}_t^\top) + \beta_t\mathbf{v}_t\mathbf{k}_t^\top\), so the model can both wipe everything quickly and edit precisely, and reported gains over Mamba-2 and DeltaNet on language modelling, retrieval and long-context tasks (arXiv:2412.06464).
In our NumPy experiment below (state \(64 \times 64\)), after storing 16 facts and then overwriting all 16, additive writing retrieves a 50/50 blend (cosine 0.62 to both old and new values) while the delta rule retrieves the new value (cosine 0.89) and has erased the old one (cosine 0.01).
The recall wall¶
All of this still compresses. How much does that cost?
Associative recall is the probe: show a model pairs like A 4 B 3 C 6 … B and ask for 3. Zoology trained 17 attention and attention-free models and found the attention-free ones up to 2.1 perplexity points worse on the Pile — and that 82% of the gap was explained by associative recall. A 70M-parameter attention model beat a 1.4B gated-convolution model on their multi-query recall task (arXiv:2312.04927). Repeat After Me proved that a two-layer transformer can copy strings of length exponential in its size while any fixed-state model is limited by its state, and found pretrained transformers "dramatically outperform" SSMs at copying and retrieval from context (arXiv:2402.01032). The Based paper made the trade-off explicit: across architectures, recall ability tracks state size, so you can buy recall with memory but not get it free (arXiv:2402.18668).
The argument is counting. A state of \(s\) numbers at \(b\) bits each holds at most \(sb\) bits. A phone book of \(n\) entries with \(m\) bits each needs \(nm\) bits. Once \(nm > sb\), no update rule, however clever, can answer every query exactly. Attention avoids this by spending memory proportional to \(n\).
At scale, NVIDIA trained 8B Mamba, Mamba-2 and transformer models on the same data (up to 3.5T tokens): pure SSMs matched or beat the transformer on many tasks but lagged on "strong copying or in-context learning" (5-shot MMLU, Phonebook) and long-context reasoning (arXiv:2406.07887).
Hybrids: the 2025 answer¶
If a few attention layers can do the exact recall and the rest can be cheap, mix them. The same NVIDIA study's Mamba-2-Hybrid (43% Mamba-2, 7% attention, 50% MLP layers) beat the 8B transformer on all 12 standard tasks (+2.65 points on average) and was predicted to generate up to 8× faster. Production models followed:
| model | recurrent layer | ratio (recurrent : attention) | notes |
|---|---|---|---|
| Jamba (AI21, Mar 2024) | Mamba | 7 : 1 | plus MoE every other layer; 256K context (arXiv:2403.19887) |
| MiniMax-Text-01 (Jan 2025) | lightning (linear) attention | 7 : 1 | 456B total, 45.9B active MoE; 1M training context, 4M at inference (arXiv:2501.08313) |
| Qwen3-Next-80B-A3B (Sep 2025) | Gated DeltaNet | 3 : 1 | 48 layers, 512 experts with 10 routed + 1 shared (model card) |
| Kimi Linear (Oct 2025) | Kimi Delta Attention (gated delta rule) | 3 : 1 | with MLA; up to 75% less KV cache and up to 6× decoding throughput at 1M context (arXiv:2510.26692) |
Kimi Linear's report is notable for claiming, under a matched training recipe, that the hybrid outperforms full attention (MLA) across short-context, long-context and RL settings — not just matches it more cheaply. As of 2026 the frontier closed models do not publish their architectures, so whether they use such layers is not public.
Other branches worth knowing¶
- Long convolutions. Hyena replaces attention with implicitly parameterised long convolutions interleaved with gating (arXiv:2302.10866).
- xLSTM. Hochreiter's group revisited the LSTM with exponential gating and a matrix memory (mLSTM, a gated linear-attention relative) (arXiv:2405.04517).
- Learned memories at test time. Titans adds a neural memory module trained online during inference, generalising the delta-rule view of "state update = gradient step" to a deep network (arXiv:2501.00663).
History¶
From fast weights to hybrids
1991–92 — Schmidhuber's fast weight programmers: one network writes the weights of another with outer products, the ancestor of linear attention. 1997 — the LSTM's gates. 2020 — Linear attention ("Transformers are RNNs", June), Linformer and Performer approximate attention; HiPPO gives principled polynomial memory (August). 2021 — S4 (October) solves Path-X; Schlag et al. connect linear attention to fast weights and propose the delta rule (February). 2022 — S4D and S5 simplify S4; H3 diagnoses SSMs' recall gap. 2023 — Hyena (February), LRU (March), RWKV (May), RetNet (July), GLA and Mamba (December) — the first attention-free model to match transformers at small scale. 2024 — Jamba (March), Griffin (February), Zoology and Based quantify the recall wall; Mamba-2/SSD unifies the two roads (May); DeltaNet trained at scale (June); NVIDIA's 8B controlled comparison (June); Gated DeltaNet (December). 2025 — hybrids reach production: MiniMax-01 (January), RWKV-7 (March), Qwen3-Next (September), Kimi Linear (October).
First principles¶
Every sequence model is a memory policy. At step \(t\) the model must summarise \(x_1..x_t\) into whatever it carries forward. Attention's policy is "keep everything": exact, with cost growing in \(t\). An RNN's policy is "keep a fixed-size summary": constant cost, lossy. Everything on this page is a choice of how to update a fixed-size summary well. The questions are only what to forget (\(G_t\)) and how to write (additive, or by correction).
Why the recurrence must be linear in the state to train in parallel. An LSTM's update \(h_t = f(h_{t-1}, x_t)\) is nonlinear in \(h_{t-1}\), so step \(t\) needs step \(t-1\)'s result: training is sequential, \(L\) steps deep. If instead \(h_t = a_t h_{t-1} + b_t\) — linear in \(h\), with \(a_t, b_t\) any function of the input — then composing two steps gives another step of the same form, and an associative operator can be evaluated as a tree of depth \(\log_2 L\). All the input-dependence can sit in \(a_t, b_t\) (gates, \(\Delta_t\), \(\beta_t\)); the nonlinearity lives between layers, not inside the recurrence. That is the single design constraint that separates this family from the classic RNN.
Why forgetting must be learned and input-dependent. A fixed decay \(\gamma\) fixes a memory horizon of about \(1/(1-\gamma)\) tokens for everything. Language has wildly different horizons: a variable's name must survive a whole function; a filler word need not survive one step. Only an input-dependent \(\Delta_t\) or \(\gamma_t\) can give each token its own horizon. This is why selection, not the continuous-time maths, was Mamba's decisive ingredient.
Why a fixed state must fail at exact recall. The counting argument above is not a quirk of current models; it is information theory. A model with \(s\) numbers of state cannot answer arbitrary lookups over more than about \(s\) numbers' worth of facts. What a recurrent model can do is learn which facts are likely to be asked for and keep those — which works for most of language and fails on phone books, long code and needle-in-a-haystack retrieval.
Expressivity cuts the other way too. One might hope a recurrent state is at least better at tracking state (who holds which object after a sequence of swaps). Merrill, Petty and Sabharwal showed that SSMs with the usual diagonal, non-negative transitions sit in the same complexity class as transformers (\(\mathsf{TC}^0\)) and cannot compose permutations (arXiv:2404.08819). Grazzi et al. showed that allowing negative eigenvalues — natural in the delta rule's \(I - \beta\mathbf{k}\mathbf{k}^\top\) with \(\beta \in (1, 2]\) — lets linear RNNs solve parity and, with products of such matrices, any regular language (arXiv:2411.12537).
The maths¶
The unified recurrence. State \(S_t \in \mathbb{R}^{d_v \times d_k}\), per-token \(\mathbf{q}_t, \mathbf{k}_t \in \mathbb{R}^{d_k}\), \(\mathbf{v}_t \in \mathbb{R}^{d_v}\):
| model | update \(S_t =\) | transition \(G_t\) |
|---|---|---|
| linear attention | \(S_{t-1} + \mathbf{v}_t\mathbf{k}_t^\top\) | \(I\) |
| RetNet | \(\gamma S_{t-1} + \mathbf{v}_t\mathbf{k}_t^\top\) | \(\gamma I\), fixed |
| Mamba-2 | \(a_t S_{t-1} + \mathbf{v}_t\mathbf{k}_t^\top\) | \(a_t I\), \(a_t = e^{\Delta_t A}\) |
| GLA | \(S_{t-1}\operatorname{diag}(\boldsymbol{\alpha}_t) + \mathbf{v}_t\mathbf{k}_t^\top\) | diagonal, data-dependent |
| DeltaNet | \(S_{t-1}(I - \beta_t\mathbf{k}_t\mathbf{k}_t^\top) + \beta_t\mathbf{v}_t\mathbf{k}_t^\top\) | identity minus rank one |
| Gated DeltaNet | \(\alpha_t S_{t-1}(I - \beta_t\mathbf{k}_t\mathbf{k}_t^\top) + \beta_t\mathbf{v}_t\mathbf{k}_t^\top\) | scaled identity minus rank one |
Output in all cases: \(\mathbf{o}_t = S_t\mathbf{q}_t\) (optionally normalised). Mamba-1 fits the table per channel with \(\mathbf{k}_t = B_t\), \(\mathbf{q}_t = C_t\), \(\mathbf{v}_t = \Delta_t x_t\) and a diagonal transition \(e^{\Delta_t A}\).
Costs. Per token and per head: recurrent update \(O(d_kd_v)\) FLOPs and \(O(d_kd_v)\) memory, independent of \(t\). Parallel (masked) form over a sequence of length \(n\): \(O(n^2 d)\) FLOPs, like attention. Chunkwise with chunk length \(c\): \(O(ncd + nd^2)\) — quadratic only inside chunks.
Derivation: zero-order-hold discretisation
Solve \(h'(t) = Ah(t) + Bx(t)\) on \([t_{k-1}, t_k]\) with \(t_k - t_{k-1} = \Delta\) and \(x\) held constant at \(x_k\). Multiply by the integrating factor \(e^{-At}\): \(\frac{d}{dt}\big(e^{-At}h(t)\big) = e^{-At}Bx_k\). Integrate over the step:
Writing \(A^{-1}(e^{\Delta A} - I)B = (\Delta A)^{-1}(e^{\Delta A} - I)\,\Delta B\) gives the stated \(\bar{B}\). For small \(\Delta A\), \(e^{\Delta A} - I \approx \Delta A\), so \(\bar{B} \approx \Delta B\) — the simpler form Mamba's implementation uses. With \(A\) diagonal and negative, \(\bar{A} = e^{\Delta A}\) has entries in \((0, 1)\): the recurrence is stable for every \(\Delta > 0\), which is why the parameterisation is in continuous time at all.
Derivation: a linear recurrence is a parallel scan
Represent step \(t\) by the pair \((a_t, b_t)\) meaning "\(h \mapsto a_t h + b_t\)". Doing step 1 then step 2 is \(h \mapsto a_2(a_1h + b_1) + b_2\), the pair
Check associativity: \(\big((a_1,b_1)\bullet(a_2,b_2)\big)\bullet(a_3,b_3) = (a_1a_2a_3,\; a_3a_2b_1 + a_3b_2 + b_3)\), and \((a_1,b_1)\bullet\big((a_2,b_2)\bullet(a_3,b_3)\big) = (a_1a_2a_3,\; a_2a_3b_1 + a_3b_2 + b_3)\) — equal. With \(h_0 = 0\), \(h_t\) is the \(b\)-component of \((a_1,b_1)\bullet\cdots\bullet(a_t,b_t)\): a prefix "sum" under an associative operator, computable in \(\lceil\log_2 L\rceil\) parallel rounds (Hillis–Steele) or \(O(L)\) total work (Blelloch). The same holds with matrices \(a_t\) (composition of linear maps is associative), which is why DeltaNet's rank-one transitions also parallelise — though multiplying full \(d \times d\) matrices is expensive, hence its specialised chunkwise algorithm using the WY representation of products of Householder-like matrices.
Derivation: the delta rule is gradient descent on memory
Treat \(S\) as a linear map that should send \(\mathbf{k}_t\) to \(\mathbf{v}_t\). Its squared error on the current pair is \(\ell(S) = \tfrac12\|S\mathbf{k}_t - \mathbf{v}_t\|^2\), with gradient \(\nabla_S\ell = (S\mathbf{k}_t - \mathbf{v}_t)\mathbf{k}_t^\top\). One step of size \(\beta_t\):
For \(\|\mathbf{k}_t\| = 1\), \((I - \beta\mathbf{k}\mathbf{k}^\top)\) has eigenvalue \(1 - \beta\) along \(\mathbf{k}\) and \(1\) on its orthogonal complement: the update edits memory only along the current key direction. \(\beta = 1\) is the exact projection (\(S_t\mathbf{k}_t = \mathbf{v}_t\)); \(\beta \in (1, 2)\) gives a negative eigenvalue, the source of the extra expressivity noted above. Linear attention, by contrast, is the gradient of \(-\mathbf{v}_t^\top S\mathbf{k}_t\), a loss that rewards alignment without bound — which is why it accumulates rather than corrects.
Derivation: SSD — the selective SSM as a masked attention matrix
With scalar transitions \(a_t\), \(h_t = a_th_{t-1} + B_tx_t\) and \(y_t = C_t^\top h_t\), unroll from \(h_0 = 0\):
So \(y = (L \circ CB^\top)\,x\) with \(L\) lower-triangular. \(L\) is 1-semiseparable: every submatrix strictly below the diagonal has rank at most 1, since \(L_{ji} = (\prod_{s\le j}a_s)/(\prod_{s\le i}a_s)\) factors into a function of \(j\) times a function of \(i\). Computed in log space, \(L_{ji} = \exp(\text{cum}_j - \text{cum}_i)\) with \(\text{cum}_t = \sum_{s\le t}\log a_s\) — exactly what the first program below does. With \(D\) channels sharing \(a_t\) and \(B, C\) across channels (Mamba-2's multi-head structure), \(x\) becomes \(V \in \mathbb{R}^{n\times d_v}\), \(C\) and \(B\) become \(Q\) and \(K\), and the layer is causal linear attention with decay mask \(L\).
Build it¶
Three NumPy programs (NumPy 2, CPU).
1. Linear attention: the parallel (attention-like) form equals the recurrent (RNN) form. With a data-dependent decay, this is a GLA / Mamba-2-style layer in miniature.
import numpy as np
rng = np.random.default_rng(0)
n, d = 1024, 64
Q, K, V = (rng.normal(size=(n, d)) / d**0.25 for _ in range(3))
phi = lambda x: np.where(x > 0, x + 1, np.exp(x)) # elu(x) + 1 > 0 (Katharopoulos et al.)
gam = 1 / (1 + np.exp(-rng.normal(2, 1, n))) # per-step decay in (0,1), data-dependent
# parallel form: like attention, with an n x n causal mask (decay-weighted)
logcum = np.cumsum(np.log(gam))
D = np.tril(np.exp(logcum[:, None] - logcum[None, :])) # D[t,j] = gamma_{j+1}...gamma_t
A = (phi(Q) @ phi(K).T) * D # (n, n): no softmax
O_par = (A @ V) / A.sum(1, keepdims=True)
# recurrent form: a d x d state and a d-vector normaliser, constant memory
S, z, O_rec = np.zeros((d, d)), np.zeros(d), np.zeros((n, d))
for t in range(n):
S = gam[t] * S + np.outer(phi(K[t]), V[t]) # write: decay, then add k v^T
z = gam[t] * z + phi(K[t])
O_rec[t] = phi(Q[t]) @ S / (phi(Q[t]) @ z) # read: query the state
print("parallel == recurrent:", np.allclose(O_par, O_rec))
print(f"parallel form FLOPs ~ 4*n^2*d = {4*n*n*d:.2e}, memory n^2 = {n*n:,}")
print(f"recurrent form FLOPs ~ 4*n*d^2 = {4*n*d*d:.2e}, state d^2+d = {d*d+d:,}")
parallel == recurrent: True
parallel form FLOPs ~ 4*n^2*d = 2.68e+08, memory n^2 = 1,048,576
recurrent form FLOPs ~ 4*n*d^2 = 1.68e+07, state d^2+d = 4,160
(This program stores the state as \(\phi(\mathbf{k})\mathbf{v}^\top\), \(d_k \times d_v\), the transpose of the convention in the prose; reading is then \(\phi(\mathbf{q})^\top S\).)
2. The recall wall, and what the delta rule buys. A \(64 \times 64\) state storing random unit-norm key–value pairs.
import numpy as np
rng = np.random.default_rng(0)
d = 64 # key and value width: the state is d x d
def unit(m): return m / np.linalg.norm(m, axis=-1, keepdims=True)
def write(S, k, v, rule):
if rule == "additive": # linear attention: S += v k^T
return S + np.outer(v, k)
return S + np.outer(v - S @ k, k) # delta rule (beta = 1): S += (v - S k) k^T
def recall_error(n, rule):
Kx, Vx = unit(rng.normal(size=(n, d))), unit(rng.normal(size=(n, d)))
S = np.zeros((d, d))
for k, v in zip(Kx, Vx): S = write(S, k, v, rule)
R = Kx @ S.T # read every key back: S k_i
return np.mean(np.linalg.norm(R - Vx, axis=1)) # 0 = perfect, ~1.4 = random
print(" pairs additive delta")
for n in (8, 32, 64, 128, 512):
print(f"{n:6d} {recall_error(n, 'additive'):8.2f} {recall_error(n, 'delta'):5.2f}")
# overwrite: store 16 facts, then update the value of the same 16 keys
Kx = unit(rng.normal(size=(16, d))); old, new = unit(rng.normal(size=(2, 16, d)))
for rule in ("additive", "delta"):
S = np.zeros((d, d))
for k, v in zip(Kx, old): S = write(S, k, v, rule)
for k, v in zip(Kx, new): S = write(S, k, v, rule)
R = Kx @ S.T
print(f"{rule:8s} after overwrite: cos(new) {np.mean(np.sum(R*new,1)/np.linalg.norm(R,axis=1)):.2f}"
f" cos(old) {np.mean(np.sum(R*old,1)/np.linalg.norm(R,axis=1)):.2f}")
pairs additive delta
8 0.30 0.19
32 0.73 0.48
64 0.96 0.73
128 1.42 0.99
512 2.79 1.30
additive after overwrite: cos(new) 0.62 cos(old) 0.62
delta after overwrite: cos(new) 0.89 cos(old) 0.01
Read the table as the recall wall in miniature. Both rules degrade as the number of facts approaches the key width (64): a \(64 \times 64\) map cannot send more than 64 independent keys to arbitrary values. The delta rule degrades more gracefully (its later writes only disturb earlier memories along overlapping key directions), and additive writing gets worse than random (error above 1.41) because interference grows without bound. The overwrite test is where the delta rule is qualitatively different: it replaces, where addition averages.
3. A selective scan, sequentially and as a parallel scan.
import numpy as np
rng = np.random.default_rng(0)
L, N = 4096, 16 # sequence length, state size (one channel)
x = rng.normal(size=L) # input signal for one channel
A = -np.exp(rng.normal(size=N)) # diagonal, negative: a stable continuous system
w_dt, w_B, w_C = rng.normal(size=3), rng.normal(size=(N,)), rng.normal(size=(N,))
# selection: step size, input map and output map all depend on the current input
dt = np.log1p(np.exp(w_dt[0] * x + w_dt[1])) # softplus -> positive step size, shape (L,)
B, C = np.outer(x, w_B), np.outer(x, w_C) # (L, N)
Abar = np.exp(dt[:, None] * A) # zero-order hold, (L, N)
Bx = dt[:, None] * B * x[:, None] # simplified (Euler) input term, as in Mamba
def sequential(a, b): # h_t = a_t * h_{t-1} + b_t
h, out = np.zeros(N), np.empty_like(b)
for t in range(len(a)):
h = a[t] * h + b[t]; out[t] = h
return out
def parallel_scan(a, b): # Hillis-Steele: log2(L) rounds, each fully parallel
a, b, step = a.copy(), b.copy(), 1
while step < len(a): # combine (a1,b1) then (a2,b2) -> (a1*a2, a2*b1 + b2)
a_prev = np.vstack([np.ones((step, N)), a[:-step]])
b_prev = np.vstack([np.zeros((step, N)), b[:-step]])
a, b = a * a_prev, a * b_prev + b
step *= 2
return b
H1, H2 = sequential(Abar, Bx), parallel_scan(Abar, Bx)
y = np.sum(C * H2, axis=1) # y_t = C_t . h_t
print("sequential == parallel scan:", np.allclose(H1, H2))
print("rounds:", int(np.ceil(np.log2(L))), "instead of", L, "sequential steps")
print("step size range: %.3f .. %.3f" % (dt.min(), dt.max()),
"-> per-step retention range: %.3f .. %.3f" % (Abar.min(), Abar.max()))
sequential == parallel scan: True
rounds: 12 instead of 4096 sequential steps
step size range: 0.180 .. 3.738 -> per-step retention range: 0.000 .. 0.975
The last line is selection at work: depending on the input, a state dimension keeps up to 97.5% of itself per step or is wiped almost completely.
Things to try
- In program 1, set
gamto all ones (plain linear attention) and to a constant 0.9 (RetNet). Then replacephi(Q) @ phi(K).Twithnp.exp(Q @ K.T)in the parallel form: the recurrent form can no longer reproduce it. That is the softmax's price. - In program 2, raise
dto 256 and find where the delta rule's error crosses 1.0. Does the crossing scale with \(d\)? - In program 2, try \(\beta = 0.5\) and \(\beta = 1.5\) in the delta rule.
- In program 3, implement the Blelloch (work-efficient) scan and count multiplications against Hillis–Steele's \(L\log_2 L\).
In practice¶
- Use the kernels. The maths fits in a page; the speed does not. Mamba's fused scan and the flash-linear-attention library (GLA, DeltaNet, Gated DeltaNet and more in Triton) are what make these layers competitive on GPUs. A naive PyTorch loop over time is hundreds of times slower.
- Hybrid ratios as of 2025–26: 3:1 to 7:1 recurrent to attention. Attention layers are often placed periodically through the stack; some designs put local (sliding-window) attention in the recurrent layers' place instead.
- Serving changes shape. A recurrent layer's "cache" is a constant-size state per sequence, so prefix caching and paging work differently — you checkpoint states at chunk boundaries rather than storing per-token rows. Support in vLLM and SGLang arrived later than for pure transformers and varies by architecture.
- Evaluate recall explicitly. Perplexity hides the weakness. Test phone-book lookup, multi-key needle retrieval (long context), few-shot in-context learning and copying before trusting a recurrent or hybrid model with retrieval-heavy work.
- State precision matters. Recurrent states accumulate over millions of steps; implementations commonly keep them in FP32 even when weights and activations are BF16.
Common misconceptions¶
- "SSMs and transformers are different worlds." Since SSD, a Mamba-2 layer is a masked linear-attention layer; the vocabularies differ, the computation does not.
- "Linear attention approximates softmax attention." Some variants (Performer) try to; most modern ones do not. They are a different, recurrent memory with their own inductive bias.
- "Fixed state means infinite context." It means constant cost at any length, not that information from far back survives. Usable memory is bounded by the state size.
- "Recurrent models are better at tracking state than transformers." With non-negative diagonal transitions they share transformers' limits on tasks like permutation composition; negative eigenvalues or non-diagonal transitions are needed.
- "Mamba replaced transformers." As of 2026 pure recurrent models have not displaced attention at the frontier; the successful pattern is the hybrid.
Check yourself¶
Why does dropping the softmax turn attention into an RNN?
With \(\operatorname{sim}(\mathbf{q},\mathbf{k}) = \phi(\mathbf{q})^\top\phi(\mathbf{k})\) the query factors out of the sum over past positions: \(\mathbf{o}_t \propto \phi(\mathbf{q}_t)^\top\sum_{j\le t}\phi(\mathbf{k}_j)\mathbf{v}_j^\top\). The sum is a \(d \times d\) matrix updated by one outer product per token — a recurrent state. The exponential of a dot product does not factor this way (its feature map is infinite-dimensional), so softmax attention must keep every key.
An SSM channel has A = −2. What step size Δ gives a memory half-life of 50 tokens?
Need \(e^{-2\Delta} = 0.5^{1/50}\), so \(\Delta = -\ln(0.5)/(50 \times 2) = 0.693/100 \approx 0.0069\). In Mamba, the network would have to output that \(\Delta\) from the current token; a larger \(\Delta\) on an important token resets the memory towards it.
What is 'selection' in Mamba, and why did it require a new algorithm?
Making \(\Delta\), \(B\) and \(C\) functions of the current input, so each token decides how much to remember or overwrite. It breaks time-invariance, so the SSM can no longer be computed as one long convolution with FFTs. Mamba instead uses a fused parallel scan kept in on-chip SRAM, with recomputation in the backward pass.
Show that the delta rule with β = 1 and a unit-norm key makes the memory return exactly the new value for that key.
\(S_t\mathbf{k}_t = S_{t-1}\mathbf{k}_t - (S_{t-1}\mathbf{k}_t - \mathbf{v}_t)\mathbf{k}_t^\top\mathbf{k}_t = S_{t-1}\mathbf{k}_t - S_{t-1}\mathbf{k}_t + \mathbf{v}_t = \mathbf{v}_t\), using \(\mathbf{k}_t^\top\mathbf{k}_t = 1\).
A recurrent model has a 64 MiB BF16 state. Roughly how many 32-bit facts could it store at most, and what does that imply for a 1M-token phone book?
\(64 \times 2^{20}\) bytes \(= 2^{29}\) bits; at 32 bits per fact, at most about \(2^{24} \approx 16.8\)M facts in the information-theoretic limit, and practically far fewer since the state must also serve every other purpose and is written by a fixed update rule. A million-entry phone book with names and numbers is beyond what it can reliably recall exactly, while a transformer's cache grows to hold it all.
Hard: derive why Mamba-2 is 'linear attention with a decay mask'.
With scalar transitions \(a_t\), unrolling \(h_t = a_th_{t-1} + B_tx_t\), \(y_t = C_t^\top h_t\) gives \(y_j = \sum_{i\le j}(\prod_{s=i+1}^j a_s)\,C_j^\top B_i\,x_i\), i.e. \(y = (L\circ CB^\top)x\) with \(L_{ji} = \prod_{s=i+1}^j a_s\) for \(j \ge i\). Identify \(C \leftrightarrow Q\), \(B \leftrightarrow K\), \(x \leftrightarrow V\): causal attention without softmax, with the causal mask replaced by the decay mask \(L\).
Hard: why must the recurrence be linear in the state for parallel training, and where does the model's nonlinearity go?
Only then does composing two steps produce a step of the same form, \((a_1,b_1)\bullet(a_2,b_2) = (a_1a_2, a_2b_1 + b_2)\), which is associative and so computable as a parallel prefix scan in \(O(\log L)\) depth. A nonlinear update \(h_t = f(h_{t-1}, x_t)\) has no such closed composition. The nonlinearity moves to how \(a_t, b_t\) (gates, \(\Delta_t\), \(\beta_t\)) are computed from the input, and to the MLPs and normalisations between layers.
Hard: Zoology found 82% of the perplexity gap between attention-free and attention models came from associative recall. Why would a few attention layers in a hybrid close most of it?
Recall needs memory that scales with the number of stored facts, which only attention's cache provides; it does not need that memory in every layer. A few attention layers can implement induction-style lookups (match the current token against earlier ones and copy what followed), while recurrent layers handle local and compressible structure. Zoology itself found that hybrids with input-dependent sparse attention closed 97.4% of the gap.
Go deeper¶
Papers
- Transformers are RNNs — Katharopoulos, Vyas, Pappas, Fleuret, 2020. Linear attention and its recurrent form; §3 is two pages.
- Linear Transformers Are Secretly Fast Weight Programmers — Schlag, Irie, Schmidhuber, 2021. The memory-capacity view and the delta rule.
- HiPPO — Gu et al., 2020. Memory as online polynomial projection: where SSM initialisations come from.
- S4: Efficiently Modeling Long Sequences with Structured State Spaces — Gu, Goel, Ré, 2021. The convolutional/recurrent duality and Path-X.
- Mamba — Gu, Dao, 2023. §3 on selection and the hardware-aware scan; Theorem 1 links SSMs to gating.
- Transformers are SSMs (Mamba-2) — Dao, Gu, 2024. State space duality; read §3–4 and the chunked algorithm.
- Gated Linear Attention — Yang et al., 2023. Data-dependent decay and the chunkwise training algorithm.
- Parallelizing Linear Transformers with the Delta Rule — Yang et al., 2024. How DeltaNet trains at GPU speed.
- Gated Delta Networks — Yang, Kautz, Hatamizadeh, 2024. The layer inside Qwen3-Next.
- Zoology — Arora et al., 2023. Associative recall explains the gap; MQAR.
- Repeat After Me — Jelassi et al., 2024. The copying theorem against fixed-state models.
- An Empirical Study of Mamba-based Language Models — Waleffe et al., 2024. The controlled 8B comparison, and the hybrid that won.
- Kimi Linear — Kimi Team, 2025. A hybrid claimed to beat full attention under matched training.
- The Illusion of State in State-Space Models — Merrill, Petty, Sabharwal, 2024. What recurrence does not buy in expressivity.
Videos and lectures
- Do we need Attention? Linear RNNs and State Space Models for NLP — Sasha Rush. The clearest one-hour tour of the whole family.
- Do we need Attention? A Mamba Primer — Sasha Rush. The follow-up, focused on selection.
- Efficiently Modeling Long Sequences with Structured State Spaces — Albert Gu, Stanford MLSys Seminar #46. S4 from its author.
Articles and blog posts
- The Annotated S4 — Sasha Rush, Sidd Karamcheti. S4 implemented line by line in JAX.
- State Space Duality (Mamba-2) Part I — Tri Dao. The SSD derivation with pictures; continue to parts II–IV.
- DeltaNet Explained (Part I) — Songlin Yang. Linear attention as memory, and why the delta rule.
- On the Tradeoffs of SSMs and Transformers — Albert Gu, 2025. The co-inventor of Mamba on what each architecture is actually good at.
- A Visual Guide to Mamba and State Space Models — Maarten Grootendorst. Illustrated introduction.
Code
- state-spaces/mamba — Reference Mamba and Mamba-2 with the fused kernels.
- fla-org/flash-linear-attention — Triton kernels for GLA, DeltaNet, Gated DeltaNet, RetNet and more.
- HazyResearch/zoology — Run the associative-recall experiments yourself.
Where this leads¶
- Long context — the other ways to reach a million tokens, and how to test whether a model uses them.
- Mixture of experts — the other axis of efficiency; Jamba, MiniMax-01 and Qwen3-Next combine both.
- Reasoning models — long generated chains are where constant-cost decoding pays off most.
- On-device AI — fixed memory per sequence is especially attractive on phones and laptops.
- Open problems — whether a fixed-state model can ever match attention's recall is one of them.