These layers replace attention's growing KV cache with a fixed-size state, updated once per token by a rule that is linear in the state, so they train in parallel like attention and decode at constant memory and cost. The designs differ only in how the state forgets and how it writes; and because a fixed state cannot hold arbitrary text exactly, every 2026 model that uses one keeps a few attention layers (a hybrid).
You need: attention and the KV cache (The transformer from zero); the attention layers that hybrids keep (GQA, MLA, windows) are taught on Attention variants, and whole-model cache sizes at a context length on Long context (its KV-cache calculator). This page owns the recurrent half. The Mamba paper page owns the Mamba-1 paper (selective scan, its Blelloch scan animation, Selective Copying toys, the paper's tables): linked, not repeated.
Per layer, for one sequence of T tokens.
| Mixer | What it keeps | Memory over context | Decode work per token | How it trains | Exact recall of context | Shipped in (2026) |
|---|---|---|---|---|---|---|
| Softmax attention | every key and value | grows with T | reads T entries | parallel (FlashAttention) | yes (any token, any distance) | almost every LLM |
| Linear attention | one dk × dv matrix S = ∑ v k⊤ | fixed | fixed | parallel masked form or chunks | weak: writes pile up, nothing is erased | MiniMax-01 (lightning attention, 7 linear : 1 softmax) |
| SSM: S4, Mamba, Mamba-2 | a state per channel (N = 16 in Mamba, 64 to 256 in Mamba-2) | fixed | fixed | S4: convolution; Mamba: parallel scan; Mamba-2: chunked matmuls | weak, improves with state size | Jamba, Nemotron-H, Granite 4.0-H, Falcon-H1, Nemotron 3 Super (all hybrids) |
| RWKV 4 to 7 | v4: a decayed running average per channel; v5 on: matrix states | fixed | fixed | parallel or chunked | weak (RWKV's own paper says so) | RWKV community models (Apache-2.0) |
| Delta rule: DeltaNet, Gated DeltaNet, KDA | a matrix S that overwrites what a key held | fixed | fixed | chunked (WY form) | better than additive writes, still bounded | Qwen3-Next, Qwen3.5, Kimi Linear, Kimi K3 (all hybrids) |
| Hybrid | mostly recurrent layers plus a few attention layers | grows, slowly (only the attention layers) | mostly fixed | both | yes, through the attention layers | every 2026 model above |
Read down and to the right for the history: each step made the state better at keeping what matters. Outlined: layers shipping in 2025 and 2026 models, every one of them a hybrid that keeps one attention layer in every 4 to 8 (section 7). Mamba and S4 keep a state per channel (S4 with a decay fixed by training, Mamba chosen per token); the others keep a matrix per head.
Attention keeps everything: memory grows with every token and each new token reads all of it. To produce token t, causal attention compares qt with every earlier key and averages every earlier value, ot = ∑j≤t softmaxj(qt·kj/√d) vj, so generation keeps all of them (the KV cache): T reads at position T, and T2/2 for a whole sequence. The topic's tiny GPT keeps 6,144 bytes per token in bf16 (6 layers × 8 heads × 32 × 2 for K and V × 2 bytes); Llama 3.1 8B keeps 128 KiB per token, 16 GiB at 131,072 tokens (sizing for any model: Long context).
A recurrent layer keeps a state ht of fixed size, updated once per token, ht = f(ht−1, xt), and reads out yt = g(ht, xt): memory and work per generated token no longer depend on t. Fig. 1 puts one layer of each side by side at the shapes of the Qwen3-Next-80B-A3B config, a hybrid that has both: its attention layers keep 2 KV heads of 256 (1,024 numbers per token), its Gated DeltaNet layers 32 value heads with a 128 × 128 state (524,288 numbers, whatever the context). Volumes are to scale: one brick is one token's keys and values, one glass plate one head's state, 16 bricks to a plate.
Shapes from the Qwen3-Next-80B-A3B config, as Fig. 1. The chart is derived: one layer of each, numbers held against context; they cross at 512 tokens.
Why recurrence lost, and how it came back. RNNs and LSTMs (Sequence models: the pre-transformer lineage) lost to attention for one reason: with a nonlinear f, ht needs ht−1, so training walks the sequence one step at a time and cannot use a GPU's parallelism across positions. The new designs make the update linear in the state, ht = At ht−1 + bt, with At and bt allowed to depend on xt but not on h. Unrolled, every ht is a sum of earlier inputs weighted by products of A's, computable for all t at once: by a parallel scan (an associative combine in log T rounds; the Mamba paper page animates Blelloch's version), by a convolution when A does not depend on the input (S4), or as one masked matrix product that looks exactly like attention (sections 2 and 4). Training is parallel; decoding is the cheap recurrence. What At is and how bt writes are the hero grid's two axes.
What it costs. Whatever the state does not hold is gone: a state of b bits cannot reproduce a string carrying more than b bits, the copying bound of Jelassi et al. 2024 ("GSSMs cannot accurately copy strings with more bits than the size of the latent state"). Attention pays memory to avoid that limit. So the state wins on long contexts, many concurrent sequences and long generations, and loses on tasks that look up exact earlier text (copying, retrieval, few-shot formats). To check a config, compare its state with KV bytes per token × context (State vs KV cache); to check a model, probe recall (section 8).
The derivation. Softmax attention's weight for key j is exp(q·kj) divided by the sum over all keys. Katharopoulos et al. 2020 replace exp(q·k) by a dot product of feature maps φ(q)·φ(k), with φ(x) = elu(x) + 1 to keep weights positive ("We prefer elu(.) over relu(.) to avoid setting the gradients to 0 when x is negative", eq. 7). Then the sum can be reassociated:
In the paper's words, "any transformer layer with causal masking can be written as a model that, given an input, modifies an internal state and then predicts an output, namely a Recurrent Neural Network" with "two hidden states, namely the attention memory s and the normalizer memory z". For one head of the tiny GPT (dk = dv = 32) the state is 1,024 + 32 numbers whatever the context, against 64 numbers per past token for its KV cache: the state is cheaper past 16 tokens.
Fig. 2 runs that recurrence on the small example of section 3 (dk = dv = 8, fixed random unit keys and values, illustrative input, exact arithmetic), without φ and the normaliser so the matrix is visible:
For the real form, with φ and the normaliser: src/code/demos.py (CPU, float64, T = 64, d = 16) computes O = ((φ(Q)φ(K)⊤) ⊙ M) V with M the causal mask, a T × T matrix like an attention map (row-normalised by the same sums), and the recurrence; the two forms agree to 4.4e-16, with a state of 272 numbers whatever T is, where a KV cache here holds 2,048. measured
The cost. The parallel form is quadratic like attention; the recurrence is linear but sequential; production kernels split the sequence into chunks, use the quadratic form inside each chunk (matrix multiplies, which tensor cores are built for) and pass the state between chunks (section 4). MiniMax's lightning attention is this split as a kernel: the masked quadratic "left product" inside a block, one multiplication by the carried state for all earlier blocks (MiniMax steps through it).
The catch. S is a sum. Every write adds to it and nothing is ever removed, so once more keys than dk have been written they cannot all be orthogonal and reads return blends. Schlag, Irie and Schmidhuber 2021: "linear Transformers can end up in an overcapacity regime, if the sequence length L exceeds the dimension d_dot of the keys". How fast it overfills: random unit keys overlap by about ±1/√dk, and the M − 1 wrong memories add like a random walk, so a read's interference over its signal is about √(M/dk) and reaches 1 at M ≈ dk (derived in the transformers-from-memory article). The next section fixes that two ways, on one input.
Decay (forget everything a little). Multiply the state by a < 1 before each write: St = at St−1 + vtkt⊤. A write made n steps ago counts an, so old memories fade and stop interfering (a = 0.9 gives a half-life of 6.6 tokens). RetNet used a fixed a per head; Gated Linear Attention and RWKV-6 make it depend on the input and on the channel; Mamba-2 makes it one input-dependent scalar per head (section 4). In RWKV-7's words decay is "a blunt tool that cannot remove only the values stored at specific keys".
The delta rule (overwrite what this key held). Before writing v under k, read what the state returns for k, S k, and write only the difference: St = St−1 + βt(vt − St−1kt)kt⊤, with write strength β between 0 and 1. With unit keys and β = 1, S k returns exactly v afterwards, so a key written twice keeps only its latest value. Hold the decay gate at 1 as well and make the keys one-hot, and each write replaces exactly one row of S while every other row stays untouched: a head becomes an exact addressable memory of dk rows. Qwenputer compiles a RISC-V CPU onto Qwen3.5's DeltaNet heads this way, with no training. Yang et al. 2024: "This process can also be regarded as optimizing an online regression loss using a single step of SGD", L(S) = ½‖S kt − vt‖2, where plain linear attention follows the "negative inner-product" loss −〈S kt, vt〉. It is the Widrow-Hoff rule of 1960, brought to transformers by DeltaNet (Schlag et al. 2021). Its offline limit is the least-squares store, fitting every pair at once, S = V⊤(K+)⊤ (K the M × dk matrix of keys, + the pseudo-inverse): exact up to dk keys, and past that its interference over signal is √(M/dk − 1), so it holds about 2dk random memories against the plain sum's dk. Overwriting buys a cleaner store, not an unbounded one.
Both together, Gated DeltaNet (Yang, Kautz and Hatamizadeh 2024, eq. 10): St = St−1(αt(I − βtktkt⊤)) + βtvtkt⊤: "gating enables rapid memory erasure while the delta rule facilitates targeted updates". (DeltaNet papers' convention, S is dv × dk; see the conventions mistake in section 11.)
Fig. 3 runs the same 12 writes as Fig. 2 (ten words of the running story, each with a fixed random unit key and a fresh random value; "Roxy" and "hill" are written again at the end with new values) under each rule, then reads every key back and compares (cosine) what comes out with the value last stored under it. illustrative input; exact arithmetic, equal to src/state/state_rules.py.
What it shows. At dk = 8, ten distinct keys overfill the state. Linear attention blends (mean cosine after all 12 writes 0.58; the re-written "Roxy" returns a mix of its old and new values). Decay keeps the recent and loses the old (0.61). The delta rule returns the re-written words almost exactly (1.00 for "hill") but its overwrites damage overlapping keys (mean 0.44; "climb" turns negative). At dk = 16, room for ten keys, the delta rule is the best recurrent rule (0.86 against 0.81 for linear). Softmax over a full cache recalls every single-write word at every size, but averages a re-written key's two values ("Roxy" 0.56): a bare key does not say which write is newer; real attention gets recency from positions.
Ten words of the running story, each with a fixed random unit key, written in order with a fresh random value; "Roxy" and "hill" are written again at the end with new values (underlined). After each write the state is read with every key so far and compared (cosine) with the value last stored under it. Same keys, values and order under each rule. illustrative input (random vectors, seed 1); exact arithmetic, equal to src/state/state_rules.py.
A forget gate is a decay chosen by the input, so the gated RNNs of the pre-transformer lineage (Sequence models) sit in this family. Mamba's Theorem 1 makes it exact: the classical gated RNN is a special case of selection (Gu and Dao, December 2023; the Mamba paper page has a slider for that gate). xLSTM (2024, from Hochreiter's group: exponential gating and a matrix memory) scales a recurrent language model to billions of parameters, as RWKV did (section 5). "Were RNNs all we needed?" (2024) strips the LSTM and GRU gates of their dependence on the previous state, so they too train with a parallel scan.
A state-space model (SSM) comes from control theory: a 1-D input signal u(t) drives an N-dimensional state x(t), x′(t) = A x(t) + B u(t), read out as y(t) = C x(t) (+ D u(t), a skip). S4 (Gu, Goel and Ré 2021) applies one such system to each channel of the model and runs it on tokens by discretising it with a step size Δ, giving the recurrence xk = Āxk−1 + B̄uk, yk = Cxk. Ā, B̄ and C are the same at every position (the model is linear time-invariant, LTI), so the output is one convolution of the input with the kernel K̄ = (CB̄, CĀB̄, CĀ2B̄, ...), computed with FFTs: that is why it trains fast. It remembers because A is not random but the HiPPO matrix, which makes "the state x(t) to memorize the history of the input u(t)".
What it cannot do. Because Ā, B̄, C ignore the input, the layer weighs a token by its distance only, never by what it is. It cannot decide to keep a name and skip filler. The Mamba paper's Selective Copying task makes that failure measurable; its paper page trains an S4-style and a selective layer side by side (99.8% against 67.4% on its toy).
S4 uses the bilinear method, Ā = (I − Δ/2·A)−1(I + Δ/2·A), B̄ = (I − Δ/2·A)−1ΔB; Mamba later switched to zero-order hold, Ā = exp(ΔA). A random A forgets fast or explodes; in an earlier model "simply modifying an SSM from a random matrix A to equation (2) improved its performance on the sequential MNIST benchmark from 60% to 98%". S4 was "the first model to solve the difficult LRA Path-X task (length-16384)". authors
Mamba (Gu and Dao 2023): "simply letting the SSM parameters be functions of the input addresses their weakness with discrete modalities, allowing the model to selectively propagate or forget information along the sequence length dimension depending on the current token". Δt, Bt and Ct become projections of xt: a large Δt resets the state toward the current token, a small one keeps the past. Fig. 4 measures this on the trained tiny SSM (the SSM-only tiny GPT, run ba_ssm, section 9): one head of layer 1, over 17 tokens of the running sequence that contain " Roxy" twice. An S4-style layer would give every token the same decay.
The decay at = exp(ΔtAh) of one head of the SSM-only tiny GPT (run ba_ssm, section 9) over the 256-token running sequence (1 keeps everything, 0 resets the state). The default is layer 1's most variable head: it forgets hardest at the "R" pieces that start "Roxy" and at quotation marks, where a name or a line of dialogue begins. src/inside/ssm_inside.py, CPU, fp32. measured on Apple M1 Pro (CPU)
How it stays fast. The convolution is gone (the kernel changes every step), so Mamba runs the recurrence as "a hardware-aware parallel algorithm in recurrent mode": the expanded state never leaves on-chip SRAM. Its state per layer is dinner × N with N = 16: 5,120 × 16 for Mamba 2.8B. Without a KV cache it serves "4-5x higher inference throughput than a Transformer of similar size" because it "can use much higher batch sizes". authors
Mamba-2 (Dao and Gu 2024) simplifies A "from diagonal to scalar times identity structure": one decay at = exp(ΔtA) per head per step, shared by all its channels and state entries, with head dimension P = 64 or 128 like a transformer. Then unrolling gives
That is linear attention (section 2) with a decaying mask instead of the plain causal mask: "When L is the causal mask, it is standard linear attention", and the two are "duals of each other with the exact same linear and quadratic forms". The name is state space duality (SSD). So every SSM head has an implicit attention map ("Mamba models give rise to three orders of magnitude more attention matrices than transformers", Ali et al. 2024); here they are, on real weights:
Why it matters for speed. Split the sequence into chunks, use the quadratic form inside each chunk (matrix multiplies on tensor cores) and the recurrence between chunks. The SSD kernel is "2-8x faster than Mamba's fused associative scan" (a kernel speedup, not a whole-model one), and the speed buys state: Mamba-2 uses N "around 64 or 128" (code default 64; Nemotron-H 8B uses 128) against Mamba's 16. authors
The topic's tiny GPT uses exactly this layer. Its SSM mixer (16 heads of 32 channels, N = 16, a short causal convolution, a gate) trains in the quadratic dual form and decodes with the recurrence (code in section 11). On the trained SSM-only model the two forms give logits that differ by at most 1.9e-5 on the running sequence (src/inside/ssm_inside.py, CPU, fp32).
Each head's decay at = exp(ΔtAh) is the share of its state that survives one token. Its median over the story, as a half-life ln 0.5 / ln a, in tokens (log scale): one dot per head, one row per layer.
96 heads: half-lives from 1.1 to 910 tokens, median 7.1; 22 heads keep half their state for 64 tokens or more. Most heads are short-range (local syntax); a few per layer carry the story. Head 0 of each layer starts with the slowest decay (A initialised from 1 to 16 across heads) and stays the longest in 5 of 6 layers. In the maps above, the long-memory SSM head draws vertical stripes (a few tokens written strongly, read by every later query, so which tokens are read is decided mostly when they are written); the short-memory head is a band along the diagonal broken where its decay falls to near zero; the attention head's stripes are short and scattered, because softmax compares every query with every key. measured on Apple M1 Pro (CPU)
|Mij| = |(Ci·Bj) × (decays between j and i) × Δj| for one head of the trained SSM-only tiny GPT, each row scaled to its maximum (not normalised like softmax), beside the attention model's (run at_mha) map at the same layer. Rows are queries, columns earlier tokens; pick any of the six layers. measured on Apple M1 Pro (CPU)
RWKV-4 (Peng et al. 2023) keeps, per channel, a weighted average of past values whose weights decay with distance: wkvt = (∑i<t e−(t−1−i)w + ki vi + eu + kt vt) / (same sum without v), with w "a channel-wise time decay" and u a "bonus" for the current token. The scores are a key-only term plus a fixed linear distance penalty, so numerator and denominator can be carried as running sums: a normalised linear attention with exponential decay (the hero grid's fixed-decay row). The authors state the cost: it "inherently limits its ability to 'look back' at previous tokens", and "carefully designed prompts may be even more crucial".
Then RWKV walked the grid: "multi-headed matrix-valued states" in RWKV-5, decay that changes with the input per channel in RWKV-6 (Eagle and Finch, 2024: "each channel of w_t can now vary independently over time, in a data-dependent manner"), and "a newly generalized formulation of the delta rule with vector-valued gating and in-context learning rates" in RWKV-7 (Goose, 2025). It stayed a community line (Apache-2.0) that no 2026 frontier hybrid uses, but its path is the one the others took.
The RWKV-4 authors trained up to 14B parameters, "by far the largest dense RNN ever trained". RWKV-7 is proved to "perform state tracking and recognize all regular languages" (solving an S5 permutation tracking problem with one layer), which the authors set against transformers' TC0 limit under standard complexity conjectures; models from 0.19B to 2.9B. authors transformers 5.20.1 ships only RWKV-4; its CPU fallback carries the two running sums plus a running maximum for numerical safety (quoted in section 11).
Gated DeltaNet is section 3's gated delta rule with learned, input-dependent αt (per head) and βt, L2-normalised queries and keys, a short convolution on q, k and v, and an output gate. Qwen3-Next-80B-A3B (September 2025) ships it: "Hybrid Layout: 12 * (3 * (Gated DeltaNet -> MoE) -> 1 * (Gated Attention -> MoE))", Gated DeltaNet heads "32 for V and 16 for QK; Head Dimension: 128". Qwen3.5 keeps the layout from 0.8B ("6 x (3 x (Gated DeltaNet -> FFN) -> 1 x (Gated Attention -> FFN))") to 397B-A17B ("15 * (3 * ...)"), context "262,144 natively". Qwen model cards, read 2026-10-19
Kimi Delta Attention (KDA), Kimi Linear 2025, changes one thing: "While GDN, similar to Mamba2, employs a coarse head-wise forget gate, KDA introduces a channel-wise variant in which each feature dimension maintains an independent forgetting rate".
In code the difference is one broadcast (section 11): Qwen3-Next's loop multiplies the state by decay[:, :, i].exp()[..., None, None] (one number per head), Kimi Linear's by g[:, i][..., None].exp() (one number per key channel); the delta step is line for line the same. Kimi Linear 48B-A3B interleaves KDA and MLA "in a uniform 3:1 ratio" with no positions in its MLA layers; Kimi K3 keeps the pattern at 93 layers (69 KDA, 24 MLA) and bounds the decay (config gate_lower_bound −5, so every retention factor exceeds e−5 ≈ 0.0067), which lets every 16-token tile of the kernel run as a dense tensor-core matrix multiply (Moonshot AI: Kimi). authors
The authors (Yang, Kautz and Hatamizadeh 2024) report at 1.3B parameters and 100B tokens: Wikitext perplexity 16.42 against 16.56 for Mamba-2, 17.71 for DeltaNet and 18.53 for their Transformer++ (Table 3); on recall-heavy tasks with 2K inputs, average 30.6 against 37.0 for the Transformer++ and 39.0 to 40.1 for their hybrids with sliding-window attention (Table 4); on single-needle retrieval at 8K, 91.8 (pass key) where Mamba-2 falls to 30.4 because it "decays historical information too quickly" (Table 2). authors
In transformers, torch_recurrent_gated_delta_rule (Qwen3-Next) and recurrent_kimi_delta_attention are the readable references; with the flash-linear-attention kernels missing, transformers falls back to them, slowly. The state per layer is value heads × dk × dv (Qwen3-Next: 32 × 128 × 128 = 524,288 numbers) plus the convolution's last 3 inputs, kept in fp32 (Qwen3.5's config: "mamba_ssm_dtype": "float32").
One head's state, dk rows (key channels) by dv columns, drawn 8 × 8 (Qwen3-Next's is 128 × 128). Shade: the share kept this step. Gated DeltaNet (and Mamba-2) multiply the whole matrix by one αt; KDA (and RWKV-6) multiply each key channel's row by its own rate, so one head can keep a slow channel for a name while clearing fast ones. Rates illustrative.
The problem a hybrid solves. A recurrent layer is cheap but cannot look things up exactly; an attention layer can but costs a growing cache. Most of a model's layers do work that a recurrence handles (local syntax, running summaries); a few must retrieve. So keep a few attention layers and make the rest recurrent. The cache then grows only in the attention layers, and the recurrent layers add a fixed state that is reserved from the first token. Fig. 5 reads the layer patterns from the configs:
Per-layer columns and totals: KV in bf16, state in fp32, one sequence, derived from the configs; the State vs KV cache tab races any attention model against any hybrid, token count by token count, and sizes any batch, dtype and context.
Read from each model's config (layer counts by type, cache in bf16, state in fp32, one sequence):
| Model | Recurrent layers | Attention layers | Ratio | KV per token | State per sequence | KV = state at | Cache + state at 128K |
|---|---|---|---|---|---|---|---|
| Jamba v0.1 | 28 Mamba | 4 | 7 : 1 | 16 KiB | 16.6 MiB | 1,064 | 2.02 GiB |
| Nemotron-H 8B | 24 Mamba-2 | 4 | 6 : 1 | 16 KiB | 98.8 MiB | 6,324 | 2.10 GiB |
| Granite 4.0-H Small | 36 Mamba-2 | 4 | 9 : 1 | 16 KiB | 147.5 MiB | 9,439 | 2.14 GiB |
| Falcon-H1 34B | 72 Mamba-2 | 72 | parallel | 144 KiB | 292.2 MiB | 2,078 | 18.29 GiB |
| Qwen3-Next 80B-A3B | 36 Gated DeltaNet | 12 | 3 : 1 | 24 KiB | 75.4 MiB | 3,216 | 3.07 GiB |
| Qwen3.5 397B-A17B | 45 Gated DeltaNet | 15 | 3 : 1 | 30 KiB | 186.3 MiB | 6,360 | 3.93 GiB |
| Kimi Linear 48B-A3B | 20 KDA | 7 MLA | 2.9 : 1 | 7.88 KiB | 42.8 MiB | 5,567 | 1.03 GiB |
| Kimi K3 | 69 KDA | 24 MLA | 2.9 : 1 | 27 KiB | 443.1 MiB | 16,806 | 3.81 GiB |
| Nemotron 3 Super 120B-A12B | 40 Mamba-2 | 8 | 5 : 1 | 8 KiB | 164.7 MiB | 21,080 | 1.16 GiB |
derived from the configs with the root Config calculator's formulas (window.CC, reused unchanged) plus two additions for Kimi Linear's KDA and Qwen3.5 (src/mem/statecalc.py, checked against the page's JavaScript). "KV = state at" is the context at which the attention layers' cache has grown to the size of the recurrent state: below it the state is the larger memory cost. Llama 3.1 8B, for comparison, keeps 128 KiB per token and 16 GiB at 128K.
How the ratios were chosen. Three findings set the one-in-four-to-eight rule:
Jamba (1.3B, 250B tokens): HellaSwag 65.1 for both 1:3 and 1:7, NQ 16.5 against 16.0, "There is no substantial difference between 1:3 and 1:7 ratios". On IMDB, QuAC and NarrativeQA pure Mamba scores 48.8, 20.2, 27.7 against attention's 84.1, 27.9, 45.8 and the hybrid's 90.9, 26.6, 43.7. They conjecture that "the lack of an attention mechanism in the pure Mamba model makes it difficult for it to learn in-context" and found 12 induction heads in the hybrid's attention layers. authors
Kimi Linear on the sweep: "A higher ratio (e.g., 7:1) produced a comparable training loss but led to significantly worse validation performance, while a lower ratio (e.g., 1:1) maintained a similar validation loss but at the cost of increased inference overhead." Qwen's blog on its 3:1: "When we mix Gated DeltaNet with standard attention at a 3:1 ratio ... the model consistently outperforms any monolithic architecture". authors
MiniMax-01 used lightning (linear) attention with "one transformer block with softmax attention ... every seven transnormer blocks" (80 layers). For M2, at small scale the hybrid "looked just as good", but "the price paid became obvious at a larger scale: the model had clear deficits in complex, multi-hop reasoning tasks". vendor
Positions. Jamba, Nemotron-H, Granite 4.0-H and Kimi Linear's MLA layers use no positional encoding (NoPE): the recurrent layers already see order. Qwen3-Next and Qwen3.5 keep partial RoPE (64 of 256 dimensions) in their attention layers; Falcon-H1 uses RoPE with base 1011. Measured here at the same budget: the tiny GPT with one attention layer in six (layer 3, NoPE) and two in six (layers 3 and 6), section 9.
The quotes on positions: Jamba, "positional embeddings or mechanisms like RoPE are not necessary, and so we do not use any explicit positional information" (adding RoPE changed nothing measurable, their Table 8); Nemotron-H, "We do not use any position embeddings". In transformers 5.20.1, modeling_jamba.py and modeling_nemotron_h.py each define apply_rotary_pos_emb and never call it (a pattern search in src/code/quotes.py: 1 definition, 0 calls; the Positional Encodings child found the same), so a config's rope_theta there is dead.
Associative recall is producing a token because it followed the same cue earlier in the context ("Hakuna Matata means no worries Hakuna Matata it means no" → "worries"). Zoology (Arora et al. 2023) found that such tokens are "6.4% of all tokens in the Pile" yet "account for 82% of the perplexity gap to attention" of attention-free models, and that "a 70M parameter attention model outperforms a 1.4 billion parameter gated-convolution model on associative recall". A recurrent model's "required ... hidden state dimensionality grows with the number of key-value pairs that the model needs to recall", attention's does not. For copying, Jelassi et al. 2024 find that "even the smallest transformer (410M parameters) outperforms the largest GSSMs (2.8B parameters) when the phone-book size is long enough (L >= 70)", although "the Mamba models achieve lower perplexity than the Pythia models".
Fig. 6 measures it on the closest public same-data pair: Pythia-160M (attention) and Mamba-130M (no attention), both trained by their authors on the Pile (300B tokens) with the GPT-NeoX tokenizer, asked to repeat lists of random one-token words and to look numbers up in a phone book. measured on Apple M1 Pro (CPU)
Copy: L random common one-token words, a blank line, the same words again; the share of the second copy's tokens predicted exactly (argmax, teacher forcing), 12 lists per length. Pythia / Mamba: 8 words 77% / 82%, 16 words 85% / 93%, 32 words 93% / 85%, 64 words 94% / 76%, 128 words 92% / 57%, 256 words 90% / 29%, 512 words 92% / 14%, 1,000 words 86% / 7%. Phone book: N lines "First Last: ddd-dddd", two example lookups from the book, then a name; the greedy answer must contain the number; 20 books per size. Pythia / Mamba: 5 entries 90% / 90%, 10 entries 60% / 80%, 20 entries 40% / 40%, 40 entries 35% / 5%, 80 entries 30% / 5%, 120 entries 10% / 0%, 200 entries 5% / 0%. Both small models lose the phone book as it grows (Pythia too is only 160M parameters), but Mamba collapses first. fp32 on CPU, transformers 5.20.1 (Mamba on its reference PyTorch path). Pythia's KV cache and Mamba's state are equal in size at 32 tokens (18,432 numbers per token against 589,824). src/recall/pretrained_copy.py.
Copy accuracy at 32 words: Pythia 93%, Mamba 85%; at 256: 90% and 29%; at 1,000: 86% and 7%. In a 40-entry phone book Pythia finds 35% of numbers and Mamba 5%. Both were trained by their authors on the Pile (300B tokens) with the GPT-NeoX tokenizer: the closest public same-data pair of attention and an attention-free SSM. Their memories are equal in size at 32 tokens. measured on Apple M1 Pro (CPU)
Real failures in the 40-entry books (first three per model; prompts of about 374 tokens):
Pythia-160M Edward Stewart: wanted 880-7564, got "870-7100" Richard Murphy: wanted 715-0000, got "945-0994" Mary Parker: wanted 796-0597, got "822-4627" Mamba-130M Edward Stewart: wanted 880-7564, got "880-7520" Charles Nelson: wanted 814-9278, got "715-2610" Sharon Roberts: wanted 558-8603, got "325-6144"
The topic's tiny GPTs show the same. A made-up name ("Zubo", split into " Z" "u" "bo") is introduced, then repeated after d filler tokens; the score is the name's later pieces against a control where the first mention was a different name. Recall benefit (control loss minus loss after the first mention, nats per piece) at 64 filler tokens: at_mha 2.91, pe_nope 1.53, ba_ssm 0.18, ba_hybrid 5.48, ba_hybrid2 5.60. The SSM-only model barely uses the earlier mention; one attention layer in six makes the hybrid the best copier of all, ahead of full attention. measured on Apple M1 Pro (CPU)
"Once upon a time, there was a little dog named Zubo." then d filler tokens from validation stories, then " One day, Zubo". Score: loss on the name's pieces after its first piece (" Z" is free to guess; "u" "bo" need the earlier mention). Solid: the name was mentioned; dashed: control, a different name was mentioned. 10 names × 8 fillers per point. src/recall/tiny_recall.py.
At 128 filler tokens, recall benefit (control minus mentioned): at_mha 1.68, pe_nope 1.20, ba_ssm 0.12, ba_hybrid 5.27, ba_hybrid2 5.51 nats per piece.
MQAR on the topic's tiny GPT code (src/recall/mqar.py): n (key, value) pairs, then every key again in random order; 256 key ids and 256 value ids, so chance is 1/256. Two layers, dmodel 128, 8,000 steps of 64 sequences at lr 1e-3, seed 0; accuracy on 2,048 fresh sequences. Models: two attention layers (RoPE), two SSM layers with state 16 or 64 per channel (NoPE), and SSM then attention.
| Model | 8 pairs | 32 pairs | 64 pairs | State or cache (numbers per layer at the end) |
|---|---|---|---|---|
| 2 attention layers | 35% | 14% | 8% | KV: 256 per token |
| 2 SSM layers, state 16 | 35% | 8% | 1% | state: 4,096 |
| 2 SSM layers, state 64 | 35% | 12% | 3% | state: 16,384 |
| SSM then attention | 99% | 8% | 3% | state 4,096; KV 256 per token |
What a fixed state is good at. Constant memory and constant work per generated token, so long generations and many concurrent sequences are cheap (section 10); no position limit inside the recurrence (the tiny SSM GPT has no positions at all); and some state-tracking problems (parity, permutations) that delta-rule and Mamba-3-style layers solve and plain attention does not at fixed depth (RWKV-7, Mamba-3 papers, published). The trade is exact, unbounded lookup, which is why hybrids keep attention.
The topic's tiny GPT (6 layers, dmodel 256, the running TinyStories data and 4,096-token BPE; root Block lab) with its layer_types switch: every mixer a Mamba-2-style SSM (ssm), one attention layer in six (hybrid, layer 3), two in six (hybrid2, layers 3 and 6), all NoPE as in Jamba and Nemotron-H; against the Attention lab's multi-head attention with RoPE and the Positional child's attention with no positions. Same seed, same batches, 1,500 steps × 8,192 tokens, AdamW at 3e-3, fp32 on MPS. Held-out loss on 100 fixed validation windows; running-sequence loss on the 256-token Roxy story, which repeats "Roxy" 11 times.
| Run | Mixers | Parameters | Held-out loss | Running sequence | Tokens/s (MPS) | Cache at 256 tokens |
|---|---|---|---|---|---|---|
| at_mha (attention, RoPE; Attention lab) | 6 attention | 5,770,496 | 2.160 | 1.741 | 33,500 | 1,572,864 B KV |
| at_mha_s1 (attention, RoPE, seed 1; Attention lab) | 6 attention | 5,770,496 | 2.175 | 1.859 | 34,700 | 1,572,864 B KV |
| pe_nope (attention, no positions; Positional Encodings child) | 6 attention | 5,770,496 | 2.389 | 2.036 | 40,475 | 1,572,864 B KV |
| ba_ssm (SSM only; this page) | 6 SSM | 6,650,336 | 2.152 | 2.024 | 14,034 | 235,776 B state |
| ba_ssm_s1 (SSM only, seed 1; this page) | 6 SSM | 6,650,336 | 2.146 | 2.126 | 14,165 | 235,776 B state |
| ba_hybrid (hybrid, attention at layer 3; this page) | ssAsss | 6,503,696 | 2.089 | 1.688 | 15,770 | 262,144 B KV + 196,480 B state |
| ba_hybrid2 (hybrid, attention at layers 3 and 6; this page) | ssAssA | 6,357,056 | 2.082 | 1.629 | 17,962 | 524,288 B KV + 157,184 B state |
measured on Apple M1 Pro (MPS), recorded in src/runs/out/runs.json; seed spread on this budget is up to 0.016 (Attention lab: MHA 2.160 and 2.175). Cache at 256 tokens: KV in bf16 plus SSM state in fp32.
The average hides the recall gap. Without a single attention layer the SSM model matches attention on held-out text (2.152 and 2.146 over two seeds against 2.160 and 2.175) and beats attention without positions (2.389) by a wide margin: order comes free from the recurrence. It is behind on the running sequence (2.024 and 2.126 against 1.741 and 1.859). One attention layer in six (2.089 held-out, 1.688 on the running sequence) beats full attention on both; two in six give 2.082 and 1.629. The hybrids are the best runs here, as Jamba, Waleffe et al. and Kimi report at scale; on held-out text the gaps are a few hundredths of a nat, larger than the seed spread for the hybrids, within it for the SSM.
at_mha), every layer an SSM (ba_ssm), one attention layer in six (ba_hybrid, layer 3), two in six (ba_hybrid2, layers 3 and 6), and attention without positions (pe_nope). White blocks are attention layers, blue plates SSM layers.at_mha's 2.160, bars down better: the SSM is level (2.152, inside the seed spread), the hybrids better (2.089 and 2.082), attention without positions much worse (2.389).Where the running-sequence gap comes from. The strip colours every token of the story by how much worse (orange) or better (blue) the chosen model does than attention: the SSM's extra loss sits on the pieces of " Roxy" after the first mention, where the hybrids' single attention layer copies the name.
The SSM has 879,840 more parameters (its mixer has 409k parameters per layer against attention's 262k) and trains about 2.4 times slower here, in its quadratic training form on MPS. At equal wall-clock time on this Mac attention would have seen more tokens; on a GPU with SSD kernels the ratio is different (not run here). Tokens per second are rough (shared machine) and the SSM's quadratic training form is not Mamba's kernel: the losses and the cache arithmetic transfer to a datacenter GPU, the timings do not.
Colour: how much worse (orange) or better (blue) the chosen model is than attention (at_mha) on each token of the Roxy story; boxed tokens are pieces of " Roxy". Recorded per-token losses from the root's eval.py. measured on Apple M1 Pro (CPU)
Memory. Per sequence, attention needs KV bytes per token × context, a recurrent layer its state once; both multiply by the batch, so the saving lets a server run more sequences at once, which is where the published throughput gains come from (Nemotron-H: "lower memory footprint from Mamba-2 layers facilitates using higher batch sizes"). The state is not free: at short contexts it is the bigger cost. Nemotron-H 8B's 98.8 MiB of fp32 state per sequence equals its attention layers' cache at 6,324 tokens; Kimi K3 carries 443.1 MiB of KDA state per sequence before its first token's cache; the tiny SSM GPT's state (6 layers × (512 × 16 + 544 × 3) numbers in fp32 = 235,776 bytes) equals the baseline's KV cache at 38 tokens. A server must reserve state memory for every live sequence even if it is 10 tokens long. Against a full-attention MoE the crossover comes sooner: Nemotron 3 Nano holds 6 KiB of cache per token against Qwen3-30B-A3B's 96 KiB, and the two are level at about 533 tokens (Other notable providers).
Compute. Decoding one token reads the weights (the same for both), plus the whole KV cache for attention or the fixed state for a recurrent layer. Prefill is matrix multiplies either way: attention's cost grows with T2, a chunked recurrent layer's with T. Vendor speedups compare whole systems, not mixers (closed block).
What a state makes harder. A KV cache can be cut at any token: share a prompt prefix between requests, roll back rejected tokens in speculative decoding, branch for beam search. A recurrent state exists only at positions where it was saved, as the rollback figure shows.
So prefix caching needs state snapshots at block boundaries, speculative decoding needs the state from before the draft (or a recomputation), and every branch needs its own copy of the state. Serving engines handle this with per-sequence state slots beside the paged KV cache (Batching, KV cache and scheduling, vLLM); in the hybrid, only the attention layers use the paged cache.
Precision. States accumulate over thousands of steps, so they are kept in fp32 even when weights and the KV cache are bf16 (transformers' delta-rule loops cast to fp32: "calculations happen in float as states are more susceptible to rounding errors", modeling_kimi_linear.py). A decay mask built by subtracting cumulative sums loses precision in bf16 (section 11).
16 tokens of one request; the server must return to token 10 (a rejected speculative draft, or a second request sharing the first 10 tokens). The KV cache keeps one entry per token, so it simply drops 11 to 16. The recurrent layer's state is one object overwritten every token; the server kept snapshots only at block boundaries (every 4 tokens here, illustrative), so it restores token 8's snapshot and recomputes 9 and 10. Follows from the mechanism; no measurement needed.
Optional. Common mistakes with real outputs, design questions for rehearsal, and the code at pinned versions, all closed.
[transformers] `causal_conv1d_fn` is falling back to its reference PyTorch implementation because `causal_conv1d` is not installed. This is correct but much slower; install `causal_conv1d` for the optimized kernel. [transformers] `selective_scan_fn` is falling back to its reference PyTorch implementation because `mamba_ssm` is not installed. This is correct but much slower; install `mamba_ssm` for the optimized kernel.The fallback is the Python loop over positions quoted in the code block below: correct, but one step per token per layer. A 1,000-token forward of Mamba-130M took 2.7 s on 4 CPU threads here, against 0.2 s for Pythia-160M on its ordinary attention path (rough, shared machine). Results are right; timings from this path say nothing about the architecture. The same holds for Gated DeltaNet and KDA without flash-linear-attention.
src/code/demos.py, 2,048 positions): max error 0.22 in bf16 against 0.0017 with a segment sum; 3.7e-6 against 5.8e-8 in fp32. transformers' Mamba-2 path uses the segment sum ("More stable ... instead of direct subtractions"); the tiny GPT subtracts, which is fine in fp32 at 256 tokens and would not be in bf16 at long context. Keep states and their decays in fp32.rope_theta; their transformers modeling files define apply_rotary_pos_emb and never call it (section 7, closed block). Changing the base or adding a RoPE scaling for long context changes nothing. Read the modeling code, not the config, before a long-context fix.Located by pattern with src/code/quotes.py in transformers 5.20.1 and the topic's src/data/tiny_gpt.py, so the line numbers are checked, not typed.
The tiny GPT's SSM, in one sentence of maths. (src/data/tiny_gpt.py, lines 293 to 297) at = exp(dtt Ah) is one decay per head per step (Mamba-2's scalar A).
Per head h (P channels, state size N), with a scalar decay a_t = exp(dt_t * A_h) that depends on the input:
state_t = a_t * state_{t-1} + dt_t * x_t B_t^T (P x N)
y_t = state_t C_t + D_h * x_t
Training uses the equivalent "dual" quadratic form y = (L o C B^T) (dt x), L[i,j] = prod_{j<k<=i} a_k, which is
exact and fast at T <= 1-2k; decoding uses the recurrence with a constant-size state (no KV cache).
Training: the dual (quadratic) form. (src/data/tiny_gpt.py, lines 351 to 356) seg is the log of L, the decay mask; G is L ⊙ C B⊤, an attention-like (heads, T, T) matrix.
cs = torch.cumsum(la, 1).transpose(1, 2) # (B,nh,T)
seg = cs[..., :, None] - cs[..., None, :] # (B,nh,Ti,Tj) = sum_{j<k<=i} log a_k
causal = torch.ones(T, T, dtype=torch.bool, device=x.device).tril()
L = torch.exp(seg.masked_fill(~causal, float("-inf"))) # decay from j to i, 0 above the diagonal
G = (Cm @ Bm.transpose(1, 2))[:, None] * L # (B,nh,Ti,Tj): like an attention matrix
y = (G @ (xh * dt[..., None]).transpose(1, 2)).transpose(1, 2) # (B,T,nh,P)
Decoding: the same layer as a recurrence. (src/data/tiny_gpt.py, lines 346 to 347) One state of (heads, P, N) = (16, 32, 16) per layer, whatever the context.
st = torch.exp(la[:, t])[..., None, None] * st + (dt[:, t, :, None, None] * xh[:, t, :, :, None]) * Bm[:, t, None, None, :] ys.append((st @ Cm[:, t, None, :, None]).squeeze(-1)) # (B,nh,P)
transformers' Mamba-2 reference path builds the same mask (transformers/models/mamba2/modeling_mamba2.py, line 301) within each chunk ...
L = torch.exp(segment_sum(A))
... with a segment sum instead of a difference of cumulative sums (transformers/models/mamba2/modeling_mamba2.py, lines 73 to 90) (why: the decay-mask mistake above).
def segment_sum(input_tensor):
"""
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
"""
chunk_size = input_tensor.size(-1)
# 1. expand input tensor to have an additional dimension and repeat along that dimension
# [..., chunk_size] -> [..., chunk_size, chunk_size]
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
input_tensor = input_tensor.masked_fill(~mask, 0)
# 3. compute actual cumsum
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
return tensor_segsum
Gated DeltaNet, one token (Qwen3-Next). (transformers/models/qwen3_next/modeling_qwen3_next.py, lines 552 to 560) Decay the state, read what the key holds (kv_mem), write β times the error, read with the query.
decay_t = decay[:, :, i].exp()[..., None, None] last_recurrent_state = last_recurrent_state * decay_t # Update the recurrent state with the current token beta_t = beta[:, :, i].unsqueeze(-1) kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2) delta = (v_t - kv_mem) * beta_t last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2) # And use it to compute the attention output for the current token core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2)
Kimi Delta Attention, one token (Kimi Linear). (transformers/models/kimi_linear/modeling_kimi_linear.py, lines 452 to 460) The same delta step; the decay g_i has one value per key channel instead of one per head.
g_i = g[:, i][..., None].exp() b_i = beta[:, i][..., None] last_recurrent_state = last_recurrent_state * g_i kv_mem = (last_recurrent_state * k_i[..., None]).sum(dim=-2) delta = (v_i - kv_mem) * b_i last_recurrent_state = last_recurrent_state + k_i.unsqueeze(-1) * delta.unsqueeze(-2) core_attn_out[:, i] = (last_recurrent_state * q_i.unsqueeze(-1)).sum(dim=-2)
RWKV-4's WKV, one token (CPU fallback). (transformers/models/rwkv/modeling_rwkv.py, lines 185 to 197) A numerator and a denominator carried as decayed running sums, with a running maximum for safe exponentials.
max_for_output = torch.maximum(max_state, current_key + time_first) e1 = torch.exp(max_state - max_for_output) e2 = torch.exp(current_key + time_first - max_for_output) numerator = e1 * num_state + e2 * current_value denominator = e1 * den_state + e2 output[:, current_index] = (numerator / denominator).to(output.dtype) # Update state for next iteration max_for_state = torch.maximum(max_state + time_decay, current_key) e1 = torch.exp(max_state + time_decay - max_for_state) e2 = torch.exp(current_key - max_for_state) num_state = e1 * num_state + e2 * current_value den_state = e1 * den_state + e2
Mamba-1's sequential fallback. (transformers/models/mamba/modeling_mamba.py, lines 259 to 267) What runs when the CUDA scan kernel is missing: a Python loop over positions.
scan_outputs = []
for index in range(seq_len):
# State calculation
ssm_state = discrete_A[:, :, index] * ssm_state + deltaB_u[:, :, index]
# Subsequent output
scan_output = torch.matmul(ssm_state.to(input_dtype), C[:, index, :].unsqueeze(-1))
scan_outputs.append(scan_output[:, :, 0])
scan_output = torch.stack(scan_outputs, dim=-1)
The two small checks quoted in section 2 and the decay-mask mistake (src/code/demos.py, CPU, output pasted):
linear attention, T=64, d=16: max |parallel - recurrent| = 4.44e-16 state size: 272 numbers, whatever T is; a KV cache here holds 2048 numbers torch.float32 T=2048: subtract cumsums, max error 3.680e-06; segment sum, max error 5.794e-08 torch.bfloat16 T=2048: subtract cumsums, max error 2.195e-01; segment sum, max error 1.721e-03
A tool for any config on the page: how much memory one sequence (or a batch) needs, split into the cache that grows with context and the recurrent state that does not, for real configs. The numbers come from the root Config calculator's code (window.CC, included unchanged) plus this page's two additions for Kimi Delta Attention and Qwen3.5, checked against src/mem/statecalc.py at six contexts for every model. Conventions: KV in bf16 unless changed below, state in fp32, windows credited. Reading section 7 (Fig. 5) shows the hybrids' layer patterns; the race below sets one attention model against one hybrid at any length. derived from configs, no model run.
Both bars use one scale at each length (the longer bar fills the width); the slider doubles the context from 256 tokens to 1M. KV in bf16, state in fp32, one sequence. derived from the configs; the calculator below sizes any batch, dtype and context.
Log scales on both axes; colours tell models apart within a group, in legend order; KV in bf16, state in fp32. Pure recurrent models are flat lines; attention models are straight lines of slope 1 (gpt-oss bends where its 128-token windows stop growing); hybrids are flat, then join a slope-1 line at their crossover.
| Preset | Layers | KV per token (bf16) | State (fp32) | KV = state at |
|---|---|---|---|---|
| baseline | aaaaaa | 6,144 B | 0 B | |
| ssm | ssssss | 0 B | 235,776 B | 38 tokens of the baseline's cache |
| hybrid | ssasss | 1,024 B | 196,480 B | 192 tokens |
| hybrid2 | ssassa | 2,048 B | 157,184 B | 77 tokens |
From tiny_gpt.kv_cache_bytes_per_token and ssm_state_bytes (root src/data/tiny_gpt.py). The setup README's table lists the same states in bf16 (117,888 bytes for ssm): half of these.
Links checked 2026-10-19. Times are rough reading times. "maker" marks a source written by the people who built the method; "third-party" everything else.
models/mamba2, qwen3_next, kimi_linear, rwkv hold readable PyTorch fallbacks (quoted in Reading section 11, closed block).