Beyond attention: SSMs, Mamba, linear attention, RWKV and hybrids

Sequence mixers that keep a fixed-size state instead of a growing KV cache, derived from attention itself: linear attention as a recurrence, decay and the delta rule, S4 to Mamba to Mamba-2's duality, RWKV, Gated DeltaNet and Kimi Delta Attention, and the hybrids that ship in 2026. Measured on the topic's tiny GPT, Pythia-160M against Mamba-130M and trained toys on an Apple M1 Pro; state and cache from real configs; published results kept apart. A child of Topic: llm-architecture. Data as of October 2026. Reading: 37 min, plus 20 in closed details.

The idea in one screen

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.

Sequence mixer
the part of a block that lets a token use earlier tokens (attention in a transformer; the feed-forward then works on each token alone).
State
what a recurrent layer keeps between tokens, the same size at token 10 and token 1 million.
Decay, half-life
the share of the state kept per token (a < 1); a write made n steps ago counts an; half-life ln 0.5 / ln a tokens.
Delta rule
write only the difference between the new value and what the state already returns for this key.
SSM
state-space model: a linear recurrence from control theory, xk = Āxk−1 + B̄uk, yk = Cxk.
Selection
Mamba's step: the recurrence's parameters depend on the current token, so the layer chooses what to keep.
Duality (SSD)
Mamba-2's result: the same layer is a recurrence and a masked attention-like matrix product.
The mixers side by side: memory, decode work, training, recall, who ships them (reference table)

Per layer, for one sequence of T tokens.

MixerWhat it keepsMemory over contextDecode work per tokenHow it trainsExact recall of contextShipped in (2026)
Softmax attentionevery key and valuegrows with Treads T entriesparallel (FlashAttention)yes (any token, any distance)almost every LLM
Linear attentionone dk × dv matrix S = ∑ v k⊤fixedfixedparallel masked form or chunksweak: writes pile up, nothing is erasedMiniMax-01 (lightning attention, 7 linear : 1 softmax)
SSM: S4, Mamba, Mamba-2a state per channel (N = 16 in Mamba, 64 to 256 in Mamba-2)fixedfixedS4: convolution; Mamba: parallel scan; Mamba-2: chunked matmulsweak, improves with state sizeJamba, Nemotron-H, Granite 4.0-H, Falcon-H1, Nemotron 3 Super (all hybrids)
RWKV 4 to 7v4: a decayed running average per channel; v5 on: matrix statesfixedfixedparallel or chunkedweak (RWKV's own paper says so)RWKV community models (Apache-2.0)
Delta rule: DeltaNet, Gated DeltaNet, KDAa matrix S that overwrites what a key heldfixedfixedchunked (WY form)better than additive writes, still boundedQwen3-Next, Qwen3.5, Kimi Linear, Kimi K3 (all hybrids)
Hybridmostly recurrent layers plus a few attention layersgrows, slowly (only the attention layers)mostly fixedbothyes, through the attention layersevery 2026 model above

Every design on this page is one cell of this grid: how the state forgets, how it writes

Softmax attention has no state: it keeps every key and value (the KV cache) and reads them all for each new token.
Adds each write
S += v k⊤
Overwrites what the key held
(delta rule)
Never forgets
Linear attention (2020)
DeltaNet (2021)
Fixed decay
S4 (2021), RetNet, RWKV-4, 5
(unused)
Decay chosen by the input, one per head
Mamba-2 (2024)Nemotron-H, Granite 4.0-H, Falcon-H1, Nemotron 3 Super
Gated DeltaNet (2024)Qwen3-Next, Qwen3.5
Decay chosen by the input, per channel
Mamba (2023), GLA, RWKV-6Jamba
KDA (2025), RWKV-7Kimi Linear, Kimi K3

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.

1. Recurrence against attention

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.

  1. One token, one brick. The first word's key and value (2 KV heads × 256, for keys and for values: 1,024 numbers) are written into the attention layer's cache. They are computed once and kept for the rest of the sequence.
  2. Every new token reads all of it. Each of 8 words adds a brick, and its query (orange) reads every brick already there: at token 8 the layer holds and reads 8,192 numbers. Memory and reads both grow with every token.
  3. A recurrent layer keeps one fixed state. The same words go into a Gated DeltaNet layer: 32 heads, each a 128 × 128 matrix, 524,288 numbers. Each token decays it, erases what its key held, writes its value and reads the output (section 3); the state never grows, and after 8 tokens it is far larger than the cache.
  4. Equal at 512 tokens. The cache keeps adding a brick per token; at 512 tokens (512 × 1,024 = 524,288 numbers) its tower is as tall as the state. Below this context the state is the larger memory cost: it is reserved from the first token.
  5. The cache keeps growing; the state does not. At 1,024 tokens the cache is twice the state; at 128K tokens this one layer holds 256 MiB of cache in bf16 against 1 MiB of state. What the state did not keep cannot be recovered later: exact recall is the price.
The same against context, on log scales (one layer of each)

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

2. Linear attention is a recurrence

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:

ot = ∑j≤t (φ(qt)⊤φ(kj)) vj / ∑j≤t φ(qt)⊤φ(kj) = St⊤φ(qt) / zt⊤φ(qt)
St = St−1 + φ(kt) vt⊤    zt = zt−1 + φ(kt)
St
the state: a dk × dv matrix, the sum of every key's outer product with its value
zt
the normaliser: the sum of the keys
φ
a feature map applied to queries and keys (elu + 1 here; later work uses identity with L2-normalised keys)

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:

  1. A token brings a key and a value. "Roxy" arrives with a key of 8 numbers (teal, lying along the state's columns) and a value of 8 (purple, along its rows). The state S is an empty 8 × 8 matrix.
  2. Their outer product is a matrix. v k⊤ puts value i times key j into entry (i, j): one write is one 8 × 8 matrix, bars up for positive entries and hanging for negative ones.
  3. The state is the running sum. "hill", "icy" and "climb" add their own outer products. The state has 64 numbers after one write and after four; nothing is appended, so it never grows.
  4. A query reads it out. Querying with Roxy's key multiplies the state by it, S q (orange in, blue out): what comes out is mostly Roxy's value, plus a little of every other value whose key overlaps Roxy's.
  5. Past dk keys, reads blend. Eight more writes, ten distinct keys in 8 dimensions: they cannot all be orthogonal, so every read now returns a blend. Read back with every key, the cosines with the stored values fall (the bars on the right; mean 0.58).
  6. The same outputs in parallel. For training, stack all 12 positions: the 12 × 12 matrix of key products, masked above the diagonal, times the values gives every output at once, equal to the recurrence's to rounding (the figure prints the largest difference). Quadratic and parallel against linear and sequential.

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 "4000x faster" claim, read (provenance)
Published speed: "up to 4000x faster on autoregressive prediction of very long sequences" (abstract), which Figure 4 shows is pixel-by-pixel CIFAR-10 image generation (sequence length 3,072; "more than 300 times" on MNIST), not text. authors' measurement

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.

3. Forget or overwrite: decay, gates and the delta rule

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.

  1. Linear: the writes pile up. Each write adds v k⊤ and nothing is removed. Ten keys in 8 dimensions overlap, so every read returns a blend: mean cosine 0.58, and the re-written "Roxy" returns a mix of its old and new values (0.49).
  2. Decay: shrink everything, then write. The whole state is multiplied by 0.9 before each write, so old writes fade and stop interfering: the recent words read back well (re-written "Roxy" 0.81, "slide" 0.89), the early ones fade ("climb" 0.29). Mean 0.61.
  3. Delta: read what the key holds, then write the difference. The 11th write is "Roxy" again. The delta rule first reads what Roxy's key returns now (S k), then writes only v − S k along that key, so afterwards S k returns the new value: the old one is replaced, not blended.
  4. Delta over all twelve writes. The re-written words come back almost exactly ("hill" 1.00, "Roxy" 0.88), but with ten keys in 8 dimensions each correction also changes the keys that overlap it: "climb" and "tree" turn negative. Mean 0.44.
  5. Gated delta: decay, then a delta write. The rule of Gated DeltaNet and KDA (section 6): recent words exact ("Roxy" 0.90, "hill" 1.00), old ones fading or damaged. On this overfilled toy the mean is 0.42; the gate pays off when old content should be forgotten, as in real text.
  6. With room: dk = 16. Ten keys now fit in 16 dimensions with little overlap, and the delta rule is the best recurrent rule: mean 0.86 against 0.81 for linear attention at the same size. Capacity is set by the key dimension.

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.

Predict: a Gated DeltaNet head in Qwen3-Next has dk = dv = 128. Roughly how many unrelated (key, value) facts can its state hold before writes start to damage each other?
Every rule at every key size, write by write (the toy as a widget, with softmax over a KV cache)

One state, five write rules: step through the writes, pick a rule and a key size

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.

The LSTM's descendants: Mamba's Theorem 1, xLSTM and minimal RNNs (depth)

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.

4. State-space models: S4, then Mamba, then Mamba-2

S4: a continuous system, discretised

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's discretisation, HiPPO's evidence and the Path-X numbers (depth; a correction)

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

Checked: two sets of numbers in one paper
The arXiv version read on 2026-10-19 keeps "88% accuracy" on Path-X and an "80.48%" LRA average in its prose, while its Table 4 prints 96.35 and 86.09 (updated runs). Quote the table.

Mamba: make the system depend on the input

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.

  1. S4: one decay for every token. An input-independent layer multiplies its state by the same a at every token; here a is this head's median, 0.60. A write made at the first "R" fades by the same factor per token, the same for a name as for filler: 60%, 36%, 22%, ... of it remains.
  2. Mamba: the decay depends on the token. The same head's recorded at = exp(ΔtAh): it forgets hardest (red) at both " R" pieces that start "Roxy" (0.33) and at "os" (0.42), the end of "rhinoceros", and keeps more inside the name ("x" 0.65, "y" 0.72) and at the full stop (0.81).
  3. The state flows along the sequence. Each token writes into a state of 32 channels × 16 per head (orange, from below), and the state passes to the next token scaled by that token's a (the blue stream thins where a is small). This is the recurrence used for decoding; a parallel scan computes all positions at once for training.
  4. What one write is worth later. The same write at the first "R", with the measured decays: the share left falls to 19% by the full stop and is cut to 6% at the second " R" (the reset where the name begins again), where the constant decay of step 1 would have kept a smooth tail. The layer chooses what to keep from what it reads.
  5. Mamba-2's decay mask. Multiplying these decays between every pair of positions gives Lij = aj+1 … ai (1 on the diagonal, 0 above it): a lower-triangular T × T matrix like a causal attention mask with fading weights. Mamba-2 multiplies it into C B⊤ to get the whole layer as one masked matrix product (next).
Any layer and head over the whole story (the decay explorer)

Selection, measured: a trained head forgets hardest at the start of a name

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's kernel and state, in detail (depth)
The expanded state (batch × length × channels × N) never touches GPU main memory; parameters are loaded into on-chip SRAM, discretised and scanned there. N = 16 is the code's default and the paper's setting, dinner = 2 × dmodel. The throughput quote is section 4.5 ("since without the KV cache it can use much higher batch sizes"); the abstract rounds it to 5x.

Mamba-2: restrict A to a scalar, and the layer becomes masked attention

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

yi = ∑j≤i (Ci·Bj) · (aj+1aj+2…ai) · xj   ⇒   Y = (L ⊙ C B⊤) X
C B⊤
a T × T matrix of query-key scores: C plays the query, B the key, x the value
L
the decay mask, Lij = product of a's between j and i (1 on the diagonal, 0 above it): "1-semiseparable"

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

SSD against FlashAttention-2 (depth)
The full quote: "2-8x faster than Mamba's fused associative scan, which does not leverage matmul units"; SSD crosses FlashAttention-2 "at sequence length 2K" and is "6x faster at sequence length 16K". 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).

How long each trained head remembers (depth: 96 half-lives)

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)

Mamba-3 (2026, published only) (depth)
Mamba-3 adds "a more expressive recurrence derived from SSM discretization", "a complex-valued state update rule that enables richer state tracking" and a multi-input multi-output form; the authors report "comparable perplexity to Mamba-2 despite using half of its predecessor's state size" at 1.5B. authors Not run here (no released small checkpoint in the topic's environment).

The same 48 tokens: an attention head's map against an SSM head's hidden map

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

5. RWKV: an RNN built from attention's pieces

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.

RWKV's scale, state tracking and code (depth)

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

6. Gated DeltaNet and Kimi Delta Attention in production

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

Kimi Linear's claims and its NoPE choice, quoted (depth)
Kimi Linear reports "reducing KV cache usage by up to 75% and achieving up to 6x decoding throughput for a 1M context". On positions: "we apply NoPE to all full attention (MLA) layers. This design delegates the entire responsibility for encoding positional information and recency bias to the KDA layers." authors Qwen tried the same NoPE choice for Qwen3.8-Flash-Next's full-attention layers: it looked the same in pre-training, but after post-training showed "a substantially higher rate of endless generation", so those layers keep RoPE (Alibaba: Qwen). authors
Gated DeltaNet's published results, and how to check a delta-rule layer (depth)

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 forget rate per head against one per key channel

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.

7. Hybrids and their ratios

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:

  1. A hybrid is a layer pattern. Nemotron-H 8B's config lists 28 mixer layers (MLP layers aside): 24 Mamba-2 layers (blue, a fixed state each) and 4 attention layers (white), spread through the depth: 6 recurrent layers per attention layer.
  2. Only the attention layers keep a cache. As the context grows, a cache column rises on each of the 4 attention layers; the 24 states are reserved from the first token (98.8 MiB of fp32 state for one sequence). The two totals at the end of the row are equal at 6,324 tokens: below that, the state is the bigger cost.
  3. Against full attention, at 131,072 tokens. Llama 3.1 8B (behind) keeps a cache on all 32 layers. Each attention layer's column is the same height in both models (8 KV heads of 128), but the hybrid has 4 of them: 2.10 GiB in all against 16 GiB.
  4. The published ratios. Every row is one model's mixer layers from its config, drawn to the same width, so the share of attention is the density of white: Jamba 7 : 1, Nemotron-H 6 : 1, Granite 4.0-H 9 : 1, Qwen3-Next and Qwen3.5 3 : 1, Kimi Linear and Kimi K3 2.9 : 1 (one MLA layer in four, plus a last one), Nemotron 3 Super 5 : 1.
  5. Falcon-H1: side by side instead of interleaved. Every one of Falcon-H1 34B's 72 layers runs attention and Mamba-2 in parallel and concatenates their channels, so every layer has both a cache and a state (the table's 72 + 72).

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

ModelRecurrent layersAttention layersRatioKV per tokenState per sequenceKV = state atCache + state at 128K
Jamba v0.128 Mamba47 : 116 KiB16.6 MiB1,0642.02 GiB
Nemotron-H 8B24 Mamba-246 : 116 KiB98.8 MiB6,3242.10 GiB
Granite 4.0-H Small36 Mamba-249 : 116 KiB147.5 MiB9,4392.14 GiB
Falcon-H1 34B72 Mamba-272parallel144 KiB292.2 MiB2,07818.29 GiB
Qwen3-Next 80B-A3B36 Gated DeltaNet123 : 124 KiB75.4 MiB3,2163.07 GiB
Qwen3.5 397B-A17B45 Gated DeltaNet153 : 130 KiB186.3 MiB6,3603.93 GiB
Kimi Linear 48B-A3B20 KDA7 MLA2.9 : 17.88 KiB42.8 MiB5,5671.03 GiB
Kimi K369 KDA24 MLA2.9 : 127 KiB443.1 MiB16,8063.81 GiB
Nemotron 3 Super 120B-A12B40 Mamba-285 : 18 KiB164.7 MiB21,0801.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:

  • Attention is kept for in-context learning. In Jamba's ablations (AI21, 2024) pure Mamba scores 48.8 on IMDB against attention's 84.1 and the hybrid's 90.9, because "the pure Mamba model often does not follow the correct format" (answering "Very Good" or "3/10" where "Positive" or "Negative" was asked); the hybrid's attention layers hold 12 induction heads. authors
  • Few attention layers suffice. Kimi Linear swept KDA : MLA at equal FLOPs (Table 1, validation perplexity): 3:1 5.65, 1:1 5.66, 7:1 5.70, 15:1 5.82, pure attention (0:1) 5.77. Jamba found "no substantial difference between 1:3 and 1:7 ratios" and took the cheaper 1:7; Qwen chose 3:1, and measured it on a 25B-A3B MoE: the average of nine base-model benchmarks is 49.87 with full attention everywhere, 51.15 for a sliding-window hybrid and 53.81 for the Gated DeltaNet 3:1 hybrid (Flash-Next paper, Table 1; Alibaba: Qwen). authors
  • Too few fails at scale. MiniMax-01 used one softmax block per seven linear (lightning attention) blocks; MiniMax-M2 went back to full attention because at scale "the model had clear deficits in complex, multi-hop reasoning tasks" (MiniMax, 30 October 2025). vendor
The three findings in full: Jamba's ablations, Kimi's sweep, MiniMax's account (depth)

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.

NVIDIA's, IBM's and TII's ratios, and the RoPE that is never applied (depth)
  • NVIDIA: Waleffe et al. 2024 trained 8B Mamba, Mamba-2, Transformer and a hybrid of "43% Mamba-2, 7% attention, and 50% MLP layers" on the same data; the pure SSMs "lag behind Transformers on tasks which require strong copying or in-context learning abilities (e.g., 5-shot MMLU, Phonebook)", the hybrid "exceeds the 8B Transformer on all 12 standard tasks we evaluated (+2.65 points on average)". Nemotron-H follows it: "roughly 8% of the total layers", 4 attention layers of 52 in the 8B (4 attention to 24 Mamba-2 among mixers), "up to 3x faster at inference". Nemotron 3 Super (March 2026, 120B total, 12B active, up to 1M context) keeps 8 attention layers of 88 (counted from its config), as "global 'anchors'". authors
  • IBM Granite 4.0-H: "Mamba-2 layers and conventional transformer blocks sequentially in a 9:1 ratio" (36 to 4), "over 70% reduction in RAM needed to handle long inputs and multiple concurrent batches". vendor
  • Parallel instead of interleaved. Falcon-H1 (TII, 2025) runs attention and Mamba-2 side by side in every layer and concatenates their channels, SSM : attention : MLP channels "roughly following 2:1:5"; "Having more attention channels significantly degrades the performance". Hymba (NVIDIA) also fuses "attention and SSMs in parallel" heads. Every Falcon-H1 layer therefore has both a cache and a state (the table's 72 + 72). authors

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.

8. What a fixed state is bad at, and good at

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

MQAR, BASED and the copying proof (depth)
Zoology's multi-query associative recall (MQAR) task lists key-value pairs and then asks for several keys; the state-dimension quote above is from it. BASED (Arora et al. 2024) turns it into a trade-off curve: "a key tradeoff between a model's state size and recall ability". Mamba-2's own MQAR experiment: going "from N=16 to N=64 and N=256 consistently improves performance". Jelassi et al. prove a two-layer transformer can copy strings of exponential length while a fixed-state model "fails to solve the copy task, unless its latent state grows linearly with the sequence length"; the paper prints the phone-book curves, not the numbers. authors
Predict: Pythia-160M and Mamba-130M are asked to repeat a list of random words. Mamba's state is 24 layers × 1,536 channels × 16 = 589,824 numbers; Pythia's KV cache holds 18,432 numbers per token. At about what list length should Mamba start to fall behind?

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)

  1. Two memories, equal at 32 tokens. Pythia's cache grows by 18,432 numbers per token (2 × 12 layers × 768); Mamba's state is 589,824 numbers whatever the length (24 layers × 1,536 channels × 16). A 32-word list fills one state's worth of cache, and both copy it: 93% and 85% of the second copy's tokens.
  2. 256 words: the cache is 8 states. Pythia keeps every word and still copies 90%; Mamba, with the same state as before, copies 29%.
  3. 1,000 words: 31 states. Pythia 86%, Mamba 7%: the state cannot hold the list, so most of it is gone by the time it must be repeated.
  4. A 40-entry phone book. About 374 tokens of prompt, 12 states of cache: Pythia finds 35% of the numbers, Mamba 5%. Both small models lose the phone book as it grows, but Mamba collapses first.
How the copy and phone-book probes were run, every point, and the failures verbatim (depth)

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.

Every point: attention keeps copying, the SSM falls away past 32 words

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)

Name recall against distance, and MQAR trained from scratch (depth; MQAR does not reproduce)

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

Model8 pairs32 pairs64 pairsState or cache (numbers per layer at the end)
2 attention layers35%14%8%KV: 256 per token
2 SSM layers, state 1635%8%1%state: 4,096
2 SSM layers, state 6435%12%3%state: 16,384
SSM then attention99%8%3%state 4,096; KV 256 per token
Does not reproduce at this budget
Only SSM-then-attention learned 8 pairs within the budget (99%); two attention layers stalled near 35%, the same plateau as the pure SSMs, and nothing learned 32 or 64 pairs. Zoology and Mamba-2 report attention solving MQAR after far longer training: does not reproduce at this budget (8,000 steps, 1 to 29 minutes per run on MPS); read it as a statement about this budget, not about attention. What the toy does show: a short convolution plus an SSM in front of one attention layer finds the lookup much sooner than attention alone, the same effect as the hybrid name-recall result. Larger state (64 against 16) did not help within this budget. measured on Apple M1 Pro (MPS)

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.

9. Measured here: the tiny GPT with an SSM, a hybrid and 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.

RunMixersParametersHeld-out lossRunning sequenceTokens/s (MPS)Cache at 256 tokens
at_mha (attention, RoPE; Attention lab)6 attention5,770,4962.1601.74133,5001,572,864 B KV
at_mha_s1 (attention, RoPE, seed 1; Attention lab)6 attention5,770,4962.1751.85934,7001,572,864 B KV
pe_nope (attention, no positions; Positional Encodings child)6 attention5,770,4962.3892.03640,4751,572,864 B KV
ba_ssm (SSM only; this page)6 SSM6,650,3362.1522.02414,034235,776 B state
ba_ssm_s1 (SSM only, seed 1; this page)6 SSM6,650,3362.1462.12614,165235,776 B state
ba_hybrid (hybrid, attention at layer 3; this page)ssAsss6,503,6962.0891.68815,770262,144 B KV + 196,480 B state
ba_hybrid2 (hybrid, attention at layers 3 and 6; this page)ssAssA6,357,0562.0821.62917,962524,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.

  1. One model, its mixers switched. The same six-layer GPT, data, seed and budget, five ways: attention with RoPE (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.
  2. What each keeps at 256 tokens. Attention's cache is 1,572,864 bytes (bf16); the SSM's state 235,776 bytes (fp32), whatever the length; the hybrids keep one or two layers' cache plus the other layers' states (262,144 + 196,480 and 524,288 + 157,184 bytes).
  3. Held-out loss, against attention. Bars up are worse than 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).
  4. The running sequence. On the 256-token Roxy story the picture changes: the SSM is 0.283 nats worse than attention (2.024 against 1.741), the hybrids still better (1.688 and 1.629).
  5. On the repeated name. On the later pieces of " Roxy" ("o", "x", "y": 27 tokens of the story) attention averages 0.484 nats and the SSM 1.693: the SSM has not kept the name. One attention layer in six brings it to 0.216.

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.

What the SSM costs here, and the training curves (depth)

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.

The running sequence, every token: the SSM's extra loss piles up on the repeated name

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)

10. Serving a recurrent or hybrid model

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

Two vendor speedups, read (depth)
Qwen3-Next's "over 10x" beyond 32K is against dense Qwen3-32B, so its 3B active parameters (mixture of experts) carry part of it; Nemotron 3 Super's "up to 2.2x and 7.5x" against gpt-oss-120b and Qwen3.5-122B is at 8K input and 64K output on B200. Mamba-2's "2-8x" is its kernel against Mamba-1's scan; Mamba's "5x" comes from larger batches without a KV cache. vendor

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

Rolling back to token 10: attention drops entries, a recurrent layer must restore and recompute

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.

11. Depth: mistakes, design questions and the code

Optional. Common mistakes with real outputs, design questions for rehearsal, and the code at pinned versions, all closed.

Common mistakes, with real outputs (4)
Running an SSM model without its kernels and blaming the architecture for the speed
transformers 5.20.1 on a machine without CUDA kernels prints, for Mamba-130M (seen here):
[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.
Building the decay mask by subtracting cumulative sums, in low precision
Lij = exp(csi − csj) with cs the cumulative sum of log a is exact in algebra, but cs grows with position and the difference of two large numbers loses the small one. Measured (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.
Tuning RoPE on a hybrid whose attention has no positions
Nemotron-H's and Jamba's configs carry 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.
Mixing equation conventions between papers
DeltaNet and Gated DeltaNet write the state as dv × dk and update St−1(I − βkk⊤) + βvk⊤; RWKV-7 and Kimi write the transpose with row vectors; transformers' loops keep (dk, dv) and multiply on the left. A port that mixes them silently reads the state with the wrong side.
Design questions (interview rehearsal, 5)
What does Mamba-2 give up relative to Mamba, and what does it get?
A becomes a scalar per head per step instead of a diagonal per channel (less expressive decay). In exchange the layer equals masked linear attention, Y = (L ⊙ CB⊤)X, which trains with chunked matrix multiplies on tensor cores (2 to 8 times faster kernels) and affords a state 4 to 16 times larger (N 64 to 256).
Compute Nemotron-H 8B's recurrent state per sequence from its config.
24 Mamba-2 layers, dinner 8,192 (128 heads of 64), state 128, 8 groups, conv 4: per layer 8,192 × 128 + (8,192 + 2 × 8 × 128) × 3 = 1,079,296 numbers; × 24 × 4 bytes = 98.8 MiB. Its 4 attention layers add 16 KiB per token, so the cache matches the state at about 6,300 tokens.
Why do Jamba, Nemotron-H and Kimi Linear use no positional encoding?
The recurrent layers process tokens in order and carry recency through their decay, so the attention layers receive order already. Jamba measured no difference with RoPE; Kimi argue RoPE in the global layers "yields an overemphasis on short-range order" and NoPE eases long-context extension.
Design: a model for 1M-token contexts serving 32 concurrent users on 8 × 80 GB GPUs.
Budget: 640 GB minus weights. A pure-attention 70B-class model with GQA keeps about 320 KiB per token: 32 × 1M tokens ≈ 10 TiB: impossible. MLA (68.6 KiB per token) still needs about 2.1 TiB. So most layers must be recurrent: a 3:1 delta-rule hybrid with MLA or GQA in the attention layers (Kimi Linear style: 7 MLA layers of 27, 7.9 KiB per token, about 252 GiB for 32 × 1M plus 43 MiB of state per user) fits beside the weights. Keep fp32 states, NoPE or partial RoPE in attention, test retrieval at full length (RULER-style, Long context), and keep enough attention layers that multi-hop retrieval holds (MiniMax's warning).
Design: you must cut serving memory of an existing 8B transformer by 4× at 32K context without retraining from scratch. Options?
GQA or MLA conversion with uptraining (Attention variants child), sliding windows on most layers with a few global ones (Long context child), or distilling into a hybrid (replace most attention layers with Mamba-2 or Gated DeltaNet layers initialised from the attention weights and train briefly, as several 2024 and 2025 distillation papers do; not run here). Check recall probes and long-context retrieval after each, not only perplexity.
The code, at pinned versions (transformers and the tiny GPT, 9 excerpts)

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