This section ties the chapter together and then puts it to work. Every layer we have built reads a sequence one token at a time and carries a fixed-size summary of the past, its state, from each token to the next. We call such a layer recurrent. We will see that all these layers are one kind of matrix, and that they differ only in how the state forgets and how a token writes to it. Then we prove what a fixed state cannot do, and see why the strongest long-context open models of 2025 and 2026 mix many recurrent layers with a few attention layers.
The models make the stakes concrete. Qwen3.5-397B-A17B, released by Alibaba in February 2026, has 60 token-mixing layers, the layers that move information between positions (its feed-forward layers act on each token alone). Forty-five of them are recurrent layers called Gated DeltaNet. Their state takes 189 MB per sequence in 32-bit floats, whether the context holds a thousand tokens or 262,144. Moonshot's Kimi Linear (October 2025) uses about three recurrent layers per attention layer, and it reports that, trained with an identical recipe, it beats a model with attention in every layer. NVIDIA's Nemotron 3 Nano has 29 token-mixing layers, and only 6 of them are attention.
Not everyone agrees. In the same month as Kimi Linear, MiniMax published a note on why its new model M2 went back to attention in every layer. Its previous model, MiniMax-01, had used linear attention, a recurrent layer, in seven of every eight layers.
Three questions run through the section. What do all these recurrent layers have in common? What can a layer with a fixed-size state provably not do? And how many attention layers does a model need to make up for it? Here are the answers in plain words, before any symbols.
Every layer of this chapter multiplies the sequence by a lower-triangular matrix. Any block of that matrix that maps past inputs to future outputs has rank at most the state size. Mamba-2's layer is exactly linear attention with a forgetting factor.
The layers differ in how the state forgets (never, at a fixed rate, at a rate each token chooses, or at a different rate per channel) and in how a token writes (by adding to what is stored, or by correcting it).
A fixed state is a lossy memory. It cannot copy or recall more than it holds. If all its decays are positive, it cannot even tell whether it has seen an odd or an even number of ones.
Attention keeps an exact record of the context, at a cost that grows with the context. A few attention layers give a recurrent model that record, and their cache becomes the only memory in the model that grows.
By the end you will be able to derive Mamba-2 from linear attention, explain the delta rule as one step of learning, state the limits of a fixed state as theorems, and size the memory of a hybrid model at a million tokens. Interviewers at labs ask about all four.
Every linear-time layer is a structured matrix
Start with one channel of a layer, so that the input is a sequence of T numbers x∈RT and the output is another, y∈RT. A layer that is linear in this input computes y=Mx for some T×T matrix M, called the sequence-mixing matrix (§21.1). Entry Mts is how much input s contributes to output t. A causal layer may only read the past, so M is lower triangular. Attention fits the same picture. Its M is the table of masked softmax weights, which depends on the input itself. (In this chapter M never means the additive attention mask of §4.4.)
The simplest recurrent layer keeps one number of state. At step t it multiplies the old state by a decayat, adds the input xt with weight ut, and reads the state out with weight ct,
In plain words, input s enters the state with weight us, is multiplied by every decay between step s and step t, and is read out with weight ct. The product at:s of the decays in between is called a segment product. It leaves out as, because as acts on the state before input s arrives. Here is the matrix of a tiny recurrence, worked by hand.
That rank of 1 is no accident. Everything the first three inputs can tell the last two outputs has to pass through one number, the state h3. Each row of the block is "how this output reads h3" times "what each input left in h3". With a one-number state, all such rows are multiples of one row. §21.1 proved this rank-one property for any scalar recurrence. The rest of this part extends it to a state of N numbers and gives it a name.
A state of N numbers works the same way, with matrices in place of numbers. A time-varying linear state-space model (SSM) has, at each step t=1,…,T, a transition matrix At∈RN×N, an input vector Bt∈RN, and an output vector Ct∈RN. It runs
ht=Atht−1+Btxt,yt=Ct⊤ht,h0=0.
The layers of this chapter are special cases. In S4 the three matrices are the same at every step (§21.3). In Mamba At is diagonal, and all three are computed from the current token (§21.4). Unrolling exactly as in the scalar case gives ht=∑s≤tAtAt−1⋯As+1Bsxs, so
Mts=Ct⊤AtAt−1⋯As+1Bs(s≤t),Mts=0(s>t).
In plain words, input s enters the state through Bs, is carried forward by every transition between s and t, and is read out through Ct.
The four-token example had a block of rank 1 because its state had one number. The name for "every such block has rank at most N" is semiseparable.
Only T of these submatrices need checking. Write Mk:T,1:k for the block of rows k to T and columns 1 to k, the diagonal entry Mkk included. We call it the cut block at k. It holds everything that crosses from the past (inputs up to k) to the future (outputs from k on). Every submatrix in the lower triangle sits inside one of the T cut blocks. So M is N-semiseparable exactly when every cut block has rank at most N (the derivation below has the one-line argument).
In plain words, everything the past tells the future must pass through the N numbers of the state at the cut, so the block that maps one to the other has rank at most N.
∂ Why only the cut blocks matter, and the proof of the theorem
Reduction to cut blocks. Take any submatrix in the lower triangle, with rows I and columns J, and let k=minI. All its rows lie in {k,…,T} and, since minI≥maxJ, all its columns lie in {1,…,k}. So it sits inside the cut block Mk:T,1:k, and a submatrix never has larger rank than the matrix that contains it.
Proof of the theorem. Fix a cut k and take any t≥k≥s. Split the product of transitions at step k,
where an empty product of transitions is the identity. Stack the ut⊤ for t=k,…,T as the rows of U∈R(T−k+1)×N, and the ws⊤ for s=1,…,k as the rows of W∈Rk×N. Then the cut block is UW⊤, a product through an inner dimension of N, so its rank is at most N. By the reduction, M is N-semiseparable. The vector ws is what input s leaves in the state hk, and ut is how output t reads hk. ∎
The converse holds too. Every N-semiseparable matrix can be written in this form for some At, Bt, Ct. It can be stored in O(NT) numbers and multiplied by a vector in O(NT) time (Dao and Gu 2024, Proposition 3.4, citing the structured-matrix literature). So the layers that can run as a recurrence with N numbers of state are exactly the layers whose matrix is N-semiseparable. Softmax attention is not among them for any fixed N, because its cut blocks have whatever rank the content gives them.
This answers a common interview question, whether softmax attention can be rewritten as an RNN with a fixed state. It cannot, because a state of N numbers caps the rank of every cut block at N, and attention's cut blocks are not capped. The first cell repeats the worked example. The second compares a diagonal SSM with N=4 against causal softmax attention on T=64 tokens. The SSM is built the Mamba-1 way, with its own decay for each of the four state entries.
Python · cell 1
Python · cell 2
The SSM's matrix has full rank 64, so it is not a low-rank matrix. Yet no cut block has rank above 4. The attention matrix's middle cut block, 32 rows by 33 columns, has rank 32, the most it could have. That difference is the chapter in one number. A recurrence squeezes the past into N numbers at every cut, and attention does not.
Mamba-2 is masked linear attention
Two earlier layers meet here. The first is causal linear attention (§21.2). It drops the softmax and scores each earlier token by a plain dot product of the query with that token's key. Run as a recurrence, it keeps a matrix state St=St−1+ϕ(kt)vt⊤ and reads it out as ot=St⊤ϕ(qt). Here ϕ is a feature map, a fixed function applied to queries and keys, and the state's rows are indexed by key features and its columns by value channels. Its weakness was that the state never forgets.
The second is Mamba (§21.4), whose state forgets at a rate each token chooses. Each channel has its own state vector in RN with a diagonal transition, so each state entry has its own decay. The decays and the vectors Bt, Ct are computed from the token.
Mamba-2 (Dao and Gu 2024) makes two changes to Mamba, and together they turn it into linear attention with a forgetting factor. First, the transition becomes one number times the identity, At=atI, so all N entries of a state forget at the same rate. Second, a group of P channels, called a head, shares that number and the same Bt and Ct. Stack the P channels' state vectors side by side, and the state of a head becomes an N×P matrix.
The state's rows index the N state dimensions and its columns the P channels. That is the chapter's convention of rows for keys and columns for values. Now unroll the recurrence, and attention appears.
Proof. Each entry of St follows a scalar recurrence with decay at, so the closed form of §21.1, applied entry by entry, gives St=∑s=1tat:sBsxs⊤. (The induction step is at∑s≤t−1at−1:sBsxs⊤+Btxt⊤=∑s≤tat:sBsxs⊤, using atat−1:s=at:s and at:t=1.) Then
In plain words, token t scores every earlier token s by the dot product of its "query" Ct with that token's "key" Bs. It multiplies the score by how much the state has decayed between s and t, and adds up the earlier inputs with those weights. There is no softmax and no normalization. The decay takes the place of a positional encoding. It is how the layer knows how far back s is.
The four-token example above is this theorem with N=P=1. Its matrix was the decays times CtBs, entry by entry. The table translates every piece between the two views.
Why give up Mamba-1's diagonal transition for a single number? With At=diag(at), the matrix is Mts=∑n=1NCt,nat:s,nBs,n, with a different mask for every state dimension n. That cannot be written as one mask times one matrix of dot products. The quadratic form would need a T×T×N tensor, and no matrix multiplication computes it. With a scalar decay, all N dimensions share one mask, and CB⊤ is a single matrix product. Matrix products are what a GPU's tensor cores, its matrix-multiply units, do best, at about 15 times the speed of its ordinary arithmetic (§21.5).
The price is that every entry of a head forgets at the same rate. The paper spends the savings on a much larger state. The released models use N=128 and the experiments range from 64 to 256, against Mamba-1's 16. Heads have P=64 or 128 channels, where Mamba-1 ran one recurrence per channel. The cell checks the duality at the size of a real Mamba-2 head, N=P=64. Then it sets every decay to 1 and recovers linear attention.
Python · cell 3
Core
SSD's two forms and its rank
Implement one SSD head in both of its forms, then measure the rank that makes it a recurrence. Write three functions.
ssd_recurrent(X, a, B, C) runs St=atSt−1+Btxt⊤ and yt=St⊤Ct from S0=0. The inputs are X of shape (T, P), a of shape (T,), and B and C of shape (T, N). It returns Y of shape (T, P).
ssd_quadratic(X, a, B, C) returns the same Y by building the matrix L⊙CB⊤ and multiplying it by X.
cut_rank(M, cut, tol=1e-9) returns the numerical rank of the cut block M[cut:, :cut+1] (0-based), the number of singular values larger than tol times the largest.
Some decays may be exactly 0. A zero decay is a reset, and it is how a boundary between two documents packed into one training row is written mathematically. Your quadratic form must stay finite there.
import numpy as np
def ssd_recurrent(X, a, B, C):
raise NotImplementedError
def ssd_quadratic(X, a, B, C):
raise NotImplementedError
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
The chunked algorithm is a block decomposition of the matrix
Neither form is what Mamba-2 runs in training. The recurrence does O(TNP) work per head, but in small elementwise steps that leave the tensor cores idle. The quadratic form uses matrix products, but its work grows as T2. §21.5 derived the compromise for gated linear attention, the chunkwise algorithm. It cuts the sequence into chunks, handles each chunk with small matrix products, and passes one state from chunk to chunk. Under the dictionary of the duality (q→C, k→B, v→x, dk→N, dv→P), SSD is gated linear attention with a scalar decay, so the same algorithm applies. The semiseparable view shows why it is exact, and the block picture of §21.5 is the one to keep in mind.
Cut the sequence into chunks of Tc tokens, and cut M into a grid of Tc×Tc blocks. There are two kinds of block.
A diagonal block, chunk j against itself, is the matrix of the same layer run on that chunk alone from a zero state. It is computed in quadratic form, (L[j]⊙C[j]B[j]⊤)X[j], with a few small matrix products. Here [j] picks out the rows of chunk j.
An off-diagonal block, the outputs of chunk j against the inputs of an earlier chunk i, lies entirely below the diagonal. So the proof of the semiseparable theorem factors it through the state.
If chunk i ends at position e and chunk j starts at position b, then for t in chunk j and s in chunk i
In plain words, the three factors are three steps.
The right factor, applied to chunk i's inputs, gives ∑s∈[i]ae:sBsxs⊤. That is the state chunk i would leave if it started from zero.
The center factors chain those chunk states into the true state entering each chunk. This is a scan of length T/Tc, the only sequential part.
The left factor reads that state for every output of chunk j.
Steps 1 and 3 are matrix products of size Tc×N by N×P. The cell runs the algorithm on twelve tokens in chunks of four, then checks one off-diagonal block against its three factors.
Python · cell 4
The cost follows from the count in §21.5. Per head, the diagonal blocks take 2TTc(N+P) FLOPs (floating-point operations) in all. The chunk states and their read-out take 4TNP, plus a short scan. With N=P=Tc that is O(TN2), the same order as the recurrence, but nearly all of it is matrix multiplication.
In an interview, this is the answer to "why did Mamba-2 restrict the transition to a scalar?" The scalar decay makes every block of the matrix a masked matrix product, so training runs on tensor cores.
In PyTorch, with autograd
This part is for readers who will write or debug these kernels. The production version replaces the loop over chunks with einsum calls and keeps all decays in log space. Every product of decays comes from a cumulative sum inside a masked lower triangle or inside one short chunk. It never comes from a ratio of two long products, the stability rule of §21.5. That rule also makes a reset safe. A reset is logat=−∞, and a difference such as cum[-1] - cum[j] would then be −∞−(−∞), which is NaN. A masked sum is −∞, whose exponential is 0. The block checks outputs and gradients against the loop, then two resets, then a 4,096-step sequence in float32.
🔥 In PyTorchfor a machine with PyTorch
The official kernels fuse these einsums in Triton, a language for writing GPU kernels, and pick Tc=256 by default. The structure is the one above, four batched matrix products around one short scan.
The Mamba-2 block
A layer ships inside a block, the unit that is stacked to make the model. Mamba-2 redesigned the block around the SSD layer too. The goal was to make it look like an attention block, both to the GPU and to the tools that split a model across GPUs (Chapter 10). Three pieces of the definition need a word first. A depthwise convolution filters each channel with its own short filter and never mixes channels. SiLU is the smooth gate SiLU(z)=zσ(z), with σ the logistic sigmoid. RMSNorm divides a vector by the root mean square of its entries and multiplies by a learned scale (§5.2).
Three features of the block matter. The first two are changes from the Mamba-1 block of §21.4. Mamba-1 already had the third, but the Mamba-2 paper was the first to test it against the alternatives.
One projection instead of two in sequence. Mamba-1 computed Δ, B, and C from the SSM's input with a second projection. Mamba-2 produces everything from one projection of u, the way attention produces Q, K, and V side by side. That matters for tensor parallelism, which gives each GPU a slice of every weight matrix (§10.4). Each GPU can then hold whole heads, and the GPUs need to sum their partial results only once per block, as in an attention block.
An extra normalization. An RMSNorm before the output projection keeps larger models stable, much as output normalization does in modern linear attention (§21.2). At about 130M parameters, the single projection and the extra norm together lowered perplexity from 11.76 to 11.49 and saved 2.8 million parameters. (Perplexity is the exponential of the average next-token loss, so lower is better.)
Keys and queries shared across heads. All H heads share one B and one C (for G=1), while each head has its own x and its own decay. Mamba-1 shared them the same way, across all of its channels. In the attention dictionary, one key and one query serve many value heads. That is the mirror image of multi-query attention, where one key and one value serve many query heads (§12.5). Dao and Gu call it multi-value attention. At matched parameters and state, it beat the multi-query pattern (shared keys and values) and the multi-key pattern (shared queries and values), with a perplexity of 11.66 against 12.62 and 12.59 at 126.5M parameters. The G groups generalize it, as grouped-query attention generalizes multi-query attention.
The real-scale count makes the shapes concrete. Mamba-2 2.7B has d=2560, 64 layers, N=128, P=64, and G=1. Its embedding matrix is shared with the output layer (a tied embedding).
Python · cell 5
Packing puts several documents in one training row without padding (§4.4 built the masks that do this for attention). Mathematically, a reset at=0 at each document boundary zeroes every entry of L that connects two documents. That is the case tested in Exercise 21.6a. Kernels pass a document index instead (seq_idx or cu_seqlens in mamba_ssm, cu_seqlens in fla, the two main kernel libraries).
One family tree of update rules
Dozens of recurrent layers have been published since 2020, and they can look unrelated. They are not. Nearly all keep a matrix state, like linear attention, and each step does two things to it. First it forgets some of what is stored. Then it writes the new token in. The layers differ mainly in those two choices.
Here is the template. A matrix state St∈Rdk×dv, with rows indexed by keys and columns by values, is read out as ot=St⊤qt and updated by
St=how it forgetsGt(St−1)+how it writeswritet.
Here Gt is a linear map of the state chosen by the token, and the write is built from the token's key kt∈Rdk and value vt∈Rdv. Most papers store the transpose of St, so their equations look mirrored. Every equation below is converted to the book's convention.
A tiny case shows how much the choices matter. Store the value 3 at a key, wait 10 steps, and read it back. Linear attention returns 3, because it never forgets. A fixed decay of 0.9 per step returns 3⋅0.910≈1.05, whether or not anything else was written. A gate that the token sets can hold the value at 3 through 10 unimportant tokens, then clear it when a new topic starts. Here are the layers, from the simplest forgetting to the richest.
No forgetting. Linear attention (§21.2) uses St=St−1+ktvt⊤. The state only grows. The crosstalk between stored keys, the error a read picks up from other keys that are not exactly orthogonal to it, only accumulates, and nothing old is ever cleared.
A fixed decay per head. The state shrinks by the same constant factor at every step, St=γSt−1+ktvt⊤. This is RetNet (Sun et al. 2023). Head i=0,1,… uses γi=1−2−5−i, so the first eight heads have half-lives from 22 to 2,839 steps. (The half-life, ln2/(−lnγ), is the number of steps after which a stored value has shrunk to half, §21.1.) It forgets, but on a schedule that ignores the content.
A fixed decay per channel. Each key channel has its own constant decay, St=diag(w)St−1+ktvt⊤, plus a learned bonus weight for the current token. This is RWKV-5. RWKV-6 makes w depend on the token (Peng et al. 2024).
A data-dependent scalar gate. The token decides how much of the whole state to keep, St=atSt−1+Btxt⊤. This is Mamba-2.
A data-dependent gate per key channel. The token decides how much to keep along each key direction, St=diag(αt)St−1+ktvt⊤, with αt∈(0,1)dk computed from the token. This is Gated Linear Attention, or GLA (Yang et al. 2023), the layer whose chunked kernel §21.5 built.
An exponential input gate with a normalizer. The forget gate ft is a sigmoid, but the write is weighted by an exponential, it=exp(i~t) of a number i~t computed from the token. So one token can write far more strongly than any before it. A second state, the normalizernt, tracks the total write weight, and the read-out divides by it,
This is the mLSTM, the matrix-memory layer of xLSTM (Beck et al. 2024). The exponential needs a numerical guard, built in the next subsection.
A vector state with two gates. The recurrent layer of Griffin, called the RG-LRU (De et al. 2024), keeps a vector, not a matrix, ht=at⊙ht−1+1−at2⊙(it⊙xt). Both the input gate it and the decay at are computed from the token.
Correcting instead of adding. The token first reads what the state stores at its key, then writes only the difference, St=(I−βtktkt⊤)St−1+βtktvt⊤. This is the delta rule, used by DeltaNet, Gated DeltaNet, Kimi Delta Attention, and RWKV-7. The hybrids of Qwen and Moonshot use this branch, NVIDIA's and IBM's use Mamba-2, and the delta rule gets its own part below.
A state that rotates. Mamba-3 (Lahoti et al. 2026) keeps Mamba-2's scalar decay but makes the state complex, so it can rotate as well as shrink. That is the same as a rotary embedding on B and C whose angles depend on the data (§5.5). It gives the transition eigenvalues off the positive real axis, which the limits below show matter. At 1.5B parameters it beat Gated DeltaNet by 0.6 points of average downstream accuracy.
layer
year
state per head
forget term Gt(S)
write
parallel form
notable result
linear attention
2020
dk×dv
S
kv⊤
masked QK⊤, all-ones mask
up to 4000x faster autoregressive prediction of long sequences
RetNet
2023
dk×dv
γS, fixed per head
kv⊤
decay mask γt−s, set by the distance only
parallel, recurrent, chunked forms
RWKV-4 to 6
2023 to 2024
per channel (4), dk×dv (5, 6)
diag(w)S, data-dependent in 6
kv⊤, bonus u for the current token
chunked
RWKV-4 scaled to 14B, on par with Transformers of its size
GLA
2023
dk×dv
diag(αt)S
kv⊤
chunked, decays folded into Q, K
chunked kernels that run on tensor cores
Griffin RG-LRU
2024
vector of d
at⊙h
1−at2⊙it⊙xt
scan (sequential in fast memory)
hybrid with local attention matches Llama-2 on 6 times fewer tokens
Mamba-2 (SSD)
2024
N×P
atS, scalar
Btxt⊤
L⊙CB⊤, chunked
2 to 8x faster than Mamba-1's scan
mLSTM
2024
dk×dv, plus n
ftS
itkv⊤, it=ei~t
chunked with stabilizer
xLSTM 7B
DeltaNet
2021, 2024
dk×dv
(I−βtkk⊤)S
βtkv⊤
chunked with the WY form (below)
1.3B beats Mamba and GLA
Gated DeltaNet
2024
dk×dv
αt(I−βtkk⊤)S
βtkv⊤
chunked with WY and gates
Qwen3-Next and Qwen3.5
Kimi Delta Attention
2025
dk×dv
(I−βtkk⊤)diag(αt)S
βtkv⊤
chunked, a diagonal-plus-low-rank variant
hybrid beats attention in every layer
RWKV-7
2025
dk×dv
(diag(wt)−(at⊙κ^t)κ^t⊤)S
k~tvt⊤
chunked
claims all regular languages
Mamba-3
2026
N×P, complex
eΔtAtS with rotations
trapezoidal, two inputs, MIMO
chunked
beats Gated DeltaNet at 1.5B
Read down the forget column and the table is a story of finer control over forgetting, from never, to a fixed rate, to a rate each token sets for each channel. Read down the write column and there is one break, from adding to correcting. An interviewer who asks you to compare two of these layers wants exactly those two axes. Say how each one forgets, then how each one writes.
Exponential gates need a stabilizer
This part is for readers who will implement an exponentially gated layer. The rest of the section does not depend on it.
The mLSTM's exponential input gate lets one token write with weight ei~t, far more decisively than a sigmoid gate, which is at most 1. That is the reason it exists. It is also an overflow waiting to happen. In float32, ei~ is infinite once i~ exceeds about 88.7, and a product of many forget gates underflows toward 0. The fix rescales the state by a running maximum of the log weights. It is the same trick as the online softmax of §12.2, which subtracts the largest score seen so far before exponentiating.
The recipe has three steps.
Track mt=max(logft+mt−1,i~t) with m0=0.
Run the two recurrences with the rescaled gates ft′=elogft+mt−1−mt and it′=ei~t−mt. Both are at most 1 by the choice of mt.
Divide by max(∣nt′⊤qt∣,e−mt) instead of max(∣nt⊤qt∣,1).
This is the stabilized mLSTM of the xLSTM paper's appendix (Beck et al. 2024) and of the xLSTM kernels. In plain words, keep the states in units of the largest weight seen so far, and convert the floor of 1 in the denominator into those units too. Take i~=1000 at one step. The raw weight e1000 overflows, but the stored weight is e1000−mt=1, and the floor becomes e−1000. In the original units the floor of 1 is negligible next to a normalizer of size e1000, and in the new units it is just as negligible.
∂ Why the rescaled recurrence gives the same output
Store St′=e−mtSt and nt′=e−mtnt instead of the raw states. Multiply St=ftSt−1+itktvt⊤ by e−mt and write St−1=emt−1St−1′ to get
and the same steps give nt′=ft′nt−1′+it′kt. Since mt is at least each of logft+mt−1 and i~t, both exponents are at most 0, so ft′,it′≤1 and nothing overflows. For the output, substitute St=emtSt′ and nt=emtnt′, and divide the numerator and both arguments of the max by emt>0,
The output is exactly the unstabilized one, and the only trace of the rescaling is the floor, which becomes e−mt.
Core
Stabilized exponential gating (mLSTM)
The starter is the unstabilized mLSTM, and it overflows once an input gate is large. Rewrite mlstm_recurrent(Q, K, V, i_pre, f_pre) so that it is stable. The queries Q and keys K have shape (T, d_k), the values V have shape (T, d_v), and the gate pre-activations i_pre and f_pre have shape (T,). Return the outputs as a (T, d_v) array. Use these pieces.
The exponential input gate it=exp(i~t) and the sigmoid forget gate ft=σ(f~t), with logft=−log(1+e−f~t) computed stably.
The stabilizer mt=max(logft+mt−1,i~t) with m0=0, and the rescaled updates above from S0′=0 and n0′=0.
The output h~t=St′⊤qt/max(∣nt′⊤qt∣,e−mt).
Use the keys as given (assume the paper's 1/dk scaling is already done). The output must match the unstabilized formula, up to rounding, whenever that formula does not overflow. It must stay finite for input-gate pre-activations in the thousands.
import numpy as np
def mlstm_recurrent(Q, K, V, i_pre, f_pre):
T, d_v = V.shape
H = np.zeros((T, d_v))
S = np.zeros((K.shape[1], d_v)); n = np.zeros(K.shape[1])
for t in range(T): # unstabilized: overflows for large i_pre
f = 1 / (1 + np.exp(-f_pre[t])); i = np.exp(i_pre[t])
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
The delta rule corrects instead of adding
Every rule so far writes by adding. That fails as soon as a key comes back with a new value. Say a memory stores the value 3 at some key, and later the same key arrives with the value 5. An adding memory now returns 3+5=8 at that key, a value that was never written. A decay cannot fix this without also fading everything else stored.
What we want is to read what is stored at the key (3), and write only the difference (2). Then the memory returns 5, and nothing stored at other, orthogonal keys is touched. This is the delta rule. It is the least-mean-squares rule of Widrow and Hoff 1960, which nudges a linear model toward each new target by a fraction of its error. Schlag, Irie, and Schmidhuber 2021 proposed it for matrix memories written while the model runs, which they called fast weights, as the fix for the crosstalk that §21.2 measured.
The second form of the delta rule reads as a sentence. St−1⊤kt is the value currently stored at kt. vt−St−1⊤kt is the memory's error on this key. The update writes a fraction βt of that error. It is one step of learning.
Proof. Drop the subscript t and write ℓ=21∑j(∑iSijki−vj)2. Then ∂ℓ/∂Sij=ki(∑i′Si′jki′−vj)=ki(S⊤k−v)j, so ∇ℓ(S)=k(S⊤k−v)⊤. A step of size β gives S−βkk⊤S+βkv⊤, because k(S⊤k)⊤=kk⊤S, which is the delta rule. Replacing St−1 by αtSt−1 gives the gated rule.
For item 1, St⊤k=St−1⊤(I−βkk⊤)k+βv(k⊤k)=(1−β)St−1⊤k+βv, using k⊤k=1. For item 2, (I−βkk⊤)u=u because k⊤u=0. For item 3, (I−βkk⊤)k=(1−β)k and every u⊥k is fixed. The matrix is symmetric, so its spectral norm is its largest absolute eigenvalue, max(1,∣1−β∣), which is at most 1 exactly when 0≤β≤2. ∎
In plain words, each token trains the memory a little, by gradient descent on "when I see this key, produce this value" (the SGD step of §0.6), and the gate αt is weight decay on the memory. The normalization of k is not cosmetic. A key of norm r gives the eigenvalue 1−βr2, so a key of norm 3 with β=1 multiplies the stored component by −8 at every write, and the state explodes.
The same lens explains linear attention. Its write kv⊤ is a gradient step of size 1 on the loss −⟨S⊤k,v⟩, which rewards matching the value but never penalizes what is already stored, so repeated keys pile up. In an interview, the one-line answer to "why is DeltaNet better than linear attention at recall?" is that its write minimizes a squared error instead of maximizing an inner product.
The cell runs four write rules on a stream of 200 writes that keeps rewriting 8 orthonormal keys with fresh values. It measures how far each memory's answer is from the latest value of every key.
Python · cell 6
The four memories behave very differently.
The additive memory's error grows without bound (0.55, 2.38, 6.15), because every old value of a key is still in the state.
The decaying memory settles near 1.0. It forgets keys written long ago as surely as it forgets stale values.
The delta rule is exact, error 0.00 throughout. With orthonormal keys, each write replaces one value and leaves the other seven alone (items 1 and 2 of the theorem).
The gated delta rule at α=0.95 sits at 0.29. It pays for forgetting it did not need on this stream.
The gate earns its place on other streams. When most tokens are distractors, every one of them that DeltaNet writes disturbs the stored keys it is not orthogonal to. A selective gate keeps the state unchanged through those tokens. That is why the strongest layers have both a gate and a correction. The widget below runs six update rules on such a stream and two others, with dk=16, dv=8, a decay of 0.95, and β=1. In the distractor stream, an option lets the layers with input-dependent gates (Mamba-2, GLA, and Gated DeltaNet) skip the distractors, a stand-in for a learned gate that recognizes them. Click a rule's name to draw it bold, and press Play to replay the writes.
How do different update rules manage a fixed-size memory?
Six 16 by 8 memories take the same writes. Each line shows how far reads miss the latest values.
Loading interactive figure…
Interview
The delta rule as associative memory
Implement the memory of one Gated DeltaNet head in the book's convention, a state S of shape (d_k, d_v) with rows indexed by keys.
delta_step(S, k, v, beta) returns the state after one delta-rule write.
gated_delta_step(S, k, v, alpha, beta) returns the state after decaying by alpha and then writing.
retrieve(S, q) returns the value read at q.
All three must L2-normalize the key or query they receive, as the layer does. Do not modify S in place.
import numpy as np
def delta_step(S, k, v, beta):
return S + np.outer(k, v) # placeholder: additive linear attention
def gated_delta_step(S, k, v, alpha, beta):
return alpha * S + np.outer(k, v) # placeholder: decay plus additive write
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
The Gated DeltaNet block
A model ships a block, not a rule. The Gated DeltaNet block is what Qwen3-Next and Qwen3.5 put in three of every four layers. Its skeleton is the Mamba-2 block's. It has one wide input projection, a short convolution, a decay computed the way Mamba-2 computes it, a gated normalization (an RMSNorm whose output is multiplied by a SiLU gate), and an output projection. The difference is that it has separate queries and keys in place of the shared B and C.
Each piece has a reason.
The convolution gives every query, key, and value a view of the last few tokens. The fla implementation warns that it is crucial to performance.
The L2 normalization is item 3 of the delta-rule theorem made concrete, since a key of norm r gives the eigenvalue 1−βr2.
The gated RMSNorm plays the role of Mamba-2's extra norm.
Step 5 is Mamba-2's multi-value pattern, one query and key serving several value heads, which fla calls grouped value attention. Qwen3.5-397B-A17B uses nqk=16 and nv=64, and Qwen3-Next-80B-A3B uses 16 and 32.
Unlike Mamba-2, the block has no skip term Dxt.
The cell counts one Qwen3.5 layer from its published configuration, d=4096 and dk=dv=128. It compares the layer with one of the model's gated attention layers, which have 32 query heads and 2 KV heads of width 256.
Python · cell 7
So when an interviewer asks whether linear-time layers make a model smaller, the answer is no. They make its per-sequence memory constant, which is what limits serving at long context.
Training the delta rule in chunks
This part is for readers who will write or debug these kernels. The rest of the section does not depend on it.
The delta rule's transition is neither a scalar nor a diagonal, so the chunked algorithm of §21.5 does not apply as it stands. Take one chunk of r tokens, numbered 1,…,r inside the chunk, that enters with state S0. Unrolling the rule gives Si=PiS0+Hi. Here Pi=(I−βikiki⊤)⋯(I−β1k1k1⊤) is the product of the transitions, and Hi is the state the chunk would build from zero. Both are dense matrices. Building them token by token is a chain of r dependent rank-one updates that tensor cores cannot help with.
Yang et al. 2024 made DeltaNet trainable at scale with a classical identity from numerical linear algebra. Each factor I−βkk⊤ is a generalized Householder matrix (at β=2 it is the Householder reflection across the plane orthogonal to k), and the WY representation (Bischof and Van Loan 1987) writes a product of such factors as the identity minus a sum of r rank-one terms, all of which can be found at once with one triangular solve.
∂ Proof by induction on the number of tokens
Write K≤i⊤W≤i=∑j≤ikjwj⊤, a sum of outer products of rows. For i=1 the sums in the recurrences are empty, so w1=β1k1 and u1=β1v1. Indeed P1=I−β1k1k1⊤=I−k1w1⊤ and H1=β1k1v1⊤=k1u1⊤.
The last two terms are both ki times a row vector, and together they equal −ki[βi(ki−∑j<i(kj⊤ki)wj)]⊤=−kiwi⊤, so Pi=I−∑j≤ikjwj⊤. For H, the second form of the delta rule from a zero start gives Hi=Hi−1+βiki(vi−Hi−1⊤ki)⊤. By the hypothesis Hi−1⊤ki=∑j<iuj(kj⊤ki), so the new term is kiui⊤ and Hi=∑j≤ikjuj⊤. Substituting both into Si=PiS0+Hi gives the formula for Si.
For the matrix form, move the sum in the recurrence for wi to the left, wi+∑j<iβi(ki⊤kj)wj=βiki. Row i of AW is wi⊤+∑j<iAijwj⊤ with Aij=βiki⊤kj for j<i. So the r recurrences are exactly the rows of AW=diag(β)K, and the same argument gives AU=diag(β)V. A is lower triangular with ones on its diagonal, so it is invertible, and solving the system by forward substitution is the recurrence itself. ∎
The outputs inside the chunk come from the same formula. Since oi=Si⊤qi and Si=S0+∑j≤ikj(uj−S0⊤wj)⊤, stacking the queries as the rows of Q and the outputs as the rows of O gives
O=QS0+tril(QK⊤)(U−WS0),Sr=S0+K⊤(U−WS0),
where tril keeps the diagonal, because output i reads the state after token i's own write. In plain words, row j of U−WS0 is what token j really writes once the incoming state and the chunk's earlier tokens are accounted for, and a chunk changes the state only along its own r keys.
Every step is a matrix product. Per chunk, KK⊤ and QK⊤ cost O(r2dk), the two triangular solves O(r2(dk+dv)), and the products with S0 cost O(rdkdv). So T tokens cost O(Tr(dk+dv)+Tdkdv), the same order as chunked gated linear attention in §21.5, and only the pass of states from chunk to chunk stays sequential. The cell checks the theorem on a chunk of five tokens.
Python · cell 8
Gated DeltaNet folds its decays into the same representation. Let γi=α1⋯αi be the decay accumulated inside the chunk, and let Γij=γi/γj for j≤i (0 above the diagonal) be the decay between two positions. Dividing the state by γi turns the gated rule into the plain delta rule with values vi/γi, so the theorem applies to it. Multiplying back gives
where AΓ is A with each key product ki⊤kj multiplied by Γij. The state leaving the chunk is γrS0+K⊤diag(γr/γ)(U−WS0). In plain words, every interaction between positions j and i is scaled by the decay between them, and the incoming state is scaled by the decay since the chunk began. Yang, Kautz, and Hatamizadeh measured the training throughput as essentially equal to DeltaNet's and slightly below Mamba-2's, the cost of a more expressive transition.
Research
The chunkwise delta rule with the UT transform
Implement the chunked algorithm that a DeltaNet training kernel runs, chunked_delta_rule(Q, K, V, beta, T_c, S0=None).
The inputs are queries and keys of shape (T, d_k), values of shape (T, d_v), writing strengths beta of shape (T,), a chunk size T_c, and an incoming state S0 of shape (d_k, d_v), zeros when it is None. When T_c does not divide T, the last chunk is shorter.
L2-normalize every query and key, as the layer does.
Inside each chunk, build A, get W and U with one solve each, and compute the chunk's outputs and the next state with the two matrix formulas above, with no loop over tokens.
Return (O, S), the outputs ot=St⊤qt as a (T, d_v) array and the final state. Do not modify S0 in place.
The result must match the token-by-token delta rule for every chunk size. Two calls that hand the state from one piece of the sequence to the next must match one call on the whole.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
What a fixed state provably cannot do
Every layer so far keeps a state of fixed size, however long the context. That is what makes it cheap, and it is also a hard limit. §21.1 gave the intuition. A state that can take only so many values cannot tell apart more prompts than that, by the pigeonhole principle. §21.2 measured how many key-value pairs an additive matrix memory holds before crosstalk swamps them.
Here are the theorems, in two families. Copying and recall are limited by how much the state holds. State tracking, following a quantity that every token can change, is limited by the eigenvalues of the transitions, however large the state. These are the results behind the interview question of what an SSM cannot do.
Copying and associative recall
Proof. Let σ(z) be the state after reading z. Everything the model does afterward depends on z only through σ(z), so there is one output distribution p(⋅∣σ) per state value. Then
where the middle inequality holds because, for each fixed σ, the probabilities p(z∣σ) of distinct strings sum to at most 1. ∎
In plain words, if the state has fewer possible values than there are strings, some strings must leave the same state. From then on the model cannot tell them apart. For example, a state of 1,000 bits copies a random 1,100-bit string with probability at most 2−100. The theorem needs bounded precision, since one real number of infinite precision could encode any string. Real models store states in float32 or bf16, so it applies.
A Transformer's KV cache grows with n, so the theorem says nothing about it. Jelassi et al. 2024 prove the matching positive result. A two-layer Transformer can copy strings whose length is exponential in its size, while any model of the class above is capped by its state. They also measured the gap in pretrained models, where Transformers copy and retrieve from context far better than state-space models of similar size.
Associative recall obeys the same count. Multi-query associative recall (MQAR), introduced by Arora et al. 2023, is the test. The model reads n key-value pairs (κ1,ν1),…,(κn,νn) with distinct keys and with values drawn from a vocabulary of c symbols. Then it receives queries κj and must answer each with its νj. In "A 4 B 3 C 6, then A ? C ?", the answers are 4 and 6. (The Greek letters keep these task keys and values apart from the layer's own kt and vt.)
∂ Proof, the copying argument again
The keys and the queries are fixed, so after the pairs everything the model does depends on the values ν=(ν1,…,νn) only through the state σ(ν). Answering every query correctly means emitting the string ν, one of cn equally likely strings. The copying argument applies word for word with 2n replaced by cn, so Pr(all correct)=c−n∑νp(ν∣σ(ν))≤c−n2s. Setting the bound to 1 or to 21 and taking log2 gives the two corollaries. ∎
Attention escapes both bounds because its cache grows with n. The bounds themselves are modest. A thousand associations over a 50,000-symbol vocabulary need at least 1,000log250,000≈15,600 bits, about 2 KB.
The bit count is only a ceiling. §21.1 computed that Mamba-2 2.7B's state is 688 million bits in bf16. That is enough in principle to store a 131,072-token context verbatim many times over, and yet such models fail recall tasks long before that. The binding limits are the structure of the state and the timing. Each head is a small matrix (64×128 numbers) written by a fixed, simple rule, and the layer must decide what to keep before it knows the question.
State tracking and parity
The second limit has nothing to do with memory size. Parity asks whether a bit string contains an odd number of ones, and it needs only one bit of state. A small nonlinear RNN computes it exactly. Yet Mamba-1 and Mamba-2 cannot compute it for every length in one forward pass, and the reason is the sign of their decays. Parity is the simplest case of state tracking. Evaluating code, following chess moves, and keeping track of who holds what in a story are harder cases of the same thing.
An eigenvalue that is not a nonnegative real number is either negative or complex. Mamba-1 and Mamba-2's decays eΔA lie in (0,1). DeltaNet with βt∈(0,1) has eigenvalues 1−βt∈(0,1) and 1. So all of them fall under the theorem. The full proof uses the Jordan form of a matrix and a careful model of rounding. Its heart is a special case we can prove completely.
∂ Proof by counting the zeros of an exponential sum
Solve the recurrence coordinate by coordinate. If an=1, hk,n=1−anbn+(h0,n−1−anbn)ank, and if an=1, hk,n=h0,n+kbn. So for k≥1, f(k)=c⊤hk+d is a constant, plus a multiple of k if some an=1, plus a sum of terms γnank=γneklnan over the coordinates with 0<an=1 (terms with an=0 vanish for k≥1). Group equal bases. Then f extends to the real line as g(x)=∑m=1Mpm(x)eλmx with distinct real λm and polynomials pm. The total count D=∑m(degpm+1) is at most N+1, one for the constant and one more for the term in k only if a coordinate with an=1 exists, in which case that coordinate contributes no exponential.
Lemma. If g≡0, it has at most D−1 real zeros. The proof is by induction on D. If D=1, g=ceλx with c=0 has no zeros. Otherwise multiply by e−λ1x, which does not move zeros, to get g~=p1(x)+∑m≥2pm(x)e(λm−λ1)x, and differentiate. The derivative is p1′+∑m≥2(pm′+(λm−λ1)pm)e(λm−λ1)x. For m≥2 the degree is unchanged because λm=λ1, and p1′ has one degree less (it vanishes if p1 is constant), so the count drops to D−1. If g~′≡0, then g~ is a nonzero constant with no zeros. Otherwise, by Rolle's theorem, between two zeros of g~ lies a zero of g~′. So if g~ had Z zeros, g~′ has at least Z−1, and the induction hypothesis gives Z−1≤D−2, so Z≤D−1. ∎
Now fix any horizon K. Lower d by an ε>0 smaller than every positive value among f(1),…,f(K). That leaves every y^k unchanged, keeps the form of g and its count D (only the constant moves), and makes f(k)=0 for k≤K. Then each change of y^k between consecutive integers k and k+1 means f(k) and f(k+1) have strictly opposite signs, so g has a zero in the open interval (k,k+1), and these intervals are disjoint. With D≤N+1, there are at most N changes up to K, for every K (if g≡0 the output never changes). Being right on 11,…,1K requires K−1 changes, so K≤N+1, and the layer errs at some k≤N+2.
The special case shows the mechanism. With positive decays, the state's path on a run of ones is a sum of decaying (or growing) exponentials. Such a path can cross a threshold only a bounded number of times, while parity flips forever. Grazzi et al.'s theorem extends this to non-diagonal transitions, many layers, and any decoder. The price is a finite-precision model of arithmetic, under which the state on 1k eventually stops changing at all.
The constructive direction is one line, the recurrence of the hand example. Let the decay be 1−2xt∈{1,−1} and start at h0=1. Then ht=∏s≤t(1−2xs)=(−1)x1+⋯+xt. So parity is 1[ht<0] for every length, and the state never leaves {1,−1}.
The same idea works as a rotation. Rotate a 2-vector by the angle πxt at each step, and it points left exactly when the parity is odd. A rotation by 2πxt/m counts modulo m in the same way. For m=2 the rotation is the matrix −I, so parity needs only the real eigenvalue −1. Counting modulo 3 needs the complex eigenvalues e±2πi/3. Grazzi et al. (Theorem 2) prove that this is necessary. A layer whose transitions and their products have only real eigenvalues, even negative ones, cannot count modulo any m that is not a power of two. The cell runs both constructions for 10,000 steps, then tries 2,000 random positive-decay layers on runs of ones.
Python · cell 9
So how do real layers get negative or complex eigenvalues? There are three routes.
Widen the range. Grazzi et al. widened Mamba's decay range from [0,1] to [−1,1], and DeltaNet's βt range from (0,1) to (0,2), which allows the eigenvalue 1−βt<0 (item 3 of the delta-rule theorem). That solved parity and improved other state-tracking tasks, and the modified models still trained stably at 1.3B parameters.
Take several delta steps per token. Grazzi et al. also proved that a product of several identity-minus-rank-one matrices per token, each with eigenvalues in [−1,1], can recognize every regular language with enough layers. (A regular language is any set of strings that a machine with finitely many states can recognize, parity being the simplest.) DeltaProduct (Siems et al. 2025) builds exactly such products. RWKV-7 (Peng et al. 2025) claims all regular languages with its generalized delta rule.
Rotate. Mamba-3 gets rotations, and so complex eigenvalues, from its complex state.
Two caveats keep these results honest. First, they concern a single forward pass with bounded precision. A model that writes intermediate results into its output (chain of thought) can track state with any of these layers. That is the same escape from one-pass limits that §4.7 and §18.1 discuss for Transformers. Second, whether pretrained language models need this expressivity on natural text is an open empirical question. An interviewer who asks why Mamba cannot do parity wants the eigenvalue argument, then the fix, then these caveats.
Research
Parity needs a negative eigenvalue
Build both parity constructions, then check the limit on positive decays numerically. Write three functions.
parity_negative(bits) runs ht=(1−2xt)ht−1 from h0=1. It returns (h, parity), the (T,) states and the (T,) integer parities read from the state alone.
parity_rotation(bits) runs Ht=R(πxt)Ht−1 from H0=(1,0), where R(θ) is the 2 by 2 rotation by θ. It returns (H, parity) with H of shape (T, 2).
output_flips(a, b, c, d, h0, K) runs the diagonal recurrence hk=a⊙hk−1+b on a run of ones from h0. With fk=c⊤hk+d, it returns the number of k∈{1,…,K−1} with fkfk+1<0.
In a comment, explain why output_flips can never exceed N when every an≥0, and what changes when one an is negative.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
Hybrids, a few attention layers in a recurrent stack
The two limits point to the same remedy. Recurrent layers are cheap, they carry order and long context, and they compress well, but they cannot keep an exact copy of what they have seen. Attention keeps an exact copy in its KV cache, the keys and values of every past token, stored so that decoding never recomputes them (§6.5). That cache grows with the context. So mix the two. A hybrid uses recurrent layers for most of the stack and a few attention layers for retrieval. Its KV cache grows only in the attention layers, and the recurrent layers add a constant.
This closes a loop that runs through the book. §3.6 and §4.7 explained why attention replaced recurrence. Attention connects any two tokens in one hop, while an RNN passes information one step at a time, and attention trains in parallel over the sequence, while an RNN trains in T sequential steps. This chapter made recurrence parallel and fast again. Hybrids keep what each side does best, the cheap state of recurrence and the exact lookup of attention.
The evidence that a few are enough
The controlled experiments agree on the shape of the curve.
The authors' reading is that the SSM layers do general sequence mixing and the attention layers act as retrieval, so the model need not compress everything into its states.
Jamba (Lieber et al. 2024) found the same at 1.3B parameters. One attention layer per three Mamba layers and one per seven were about equally good, and both beat pure attention and pure Mamba. The failure of pure Mamba was telling. On few-shot prompts, which show a few solved examples before the question, it often broke the output format. It answered "Very Good" or "3/10" when the choices were "Positive" and "Negative". The hybrid kept the format, and its attention heads attended to the labels of the examples in the prompt. That is the induction behavior of §6.8, where a head finds an earlier match and copies what came after it.
At larger scale, Waleffe et al. 2024 trained 8B models on the same 3.5 trillion tokens. A hybrid with 43% Mamba-2, 7% attention, and 50% MLP layers beat the Transformer on all 12 standard tasks, by 2.65 points on average. It was predicted to generate up to 8 times faster. Kimi Linear (Kimi Team 2025) compared a hybrid with three Kimi Delta Attention layers per attention layer against attention in every layer, under one recipe on 1.4 trillion tokens. It reported the hybrid ahead on short-context, long-context, and RL tasks. Its attention is multi-head latent attention (MLA), which caches a compressed vector per token instead of full keys and values (§12.5).
The design space
A hybrid's designer makes six choices.
Ratio. Published hybrids sit between one attention layer in 3 and one in 10. More attention buys recall at the price of cache. The Mamba-2 sweep suggests that quality is flat over a wide range, so memory drives the choice.
Placement. Spread the attention layers evenly and keep them away from the very first and last layers. In Dao and Gu's small-scale tests, the exact positions mattered little once the layers were spaced out. Jamba puts attention at position 4 of every 8 layers, and Granite 4.0-H Small at layers 5, 15, 25, and 35 of 40 (counting from 0).
Positions. The recurrent layers know the order of tokens through their decays. So several hybrids drop rotary embeddings (RoPE, §5.5) from their attention layers entirely, among them Jamba, Granite 4.0-H, and Kimi Linear. That also avoids the work of extending RoPE to long contexts (§12.7).
Local or global attention. Sliding-window attention attends only to a fixed number of recent tokens (§12.6), so its cache is bounded too. Griffin uses it, with two recurrent blocks and then one local attention block with a 1,024-token window, and so does Samba (Ren et al. 2024). Griffin solved a phonebook lookup up to its window and degraded beyond it, which is the limit of that choice. The 2025 and 2026 frontier hybrids use global attention, because long-range retrieval is the reason the attention layers are there.
Stacked or side by side. Most hybrids alternate layer types. Falcon-H1 (Zuo et al. 2025) and Hymba (Dong et al. 2024) instead run attention heads and SSM heads side by side inside each layer and combine their outputs. Bae et al. 2025 compare the two designs.
Mixture of experts. Most of the large hybrids since Jamba use mixture-of-experts (MoE) feed-forward layers, which send each token to a few of many expert MLPs (§13.5). The two choices are independent. Recurrent layers mix information across tokens, and MoE layers mix it within one token.
Each lab has made the six choices differently, and the released models are the best record of what works at scale. The box lists them in order of release, with their layouts and their main reported results.
Read down the list and watch the ratio. Count only the token-mixing layers. The hybrids of 2024 kept attention in one of every eight (Jamba) or seven (Mamba-2-Hybrid). Most large models of 2025 and 2026 keep more, about one in four or five, while IBM's Granite 4.0-H keeps one in ten.
The architectures of closed frontier models are not public, and nothing here says whether any of them uses recurrent layers. Not every open lab agrees either. MiniMax went back to full attention for M2, after MiniMax-01 had been a hybrid. DeepSeek cuts attention's cost with sparse attention, which reads only a selected subset of past tokens (§12.6), rather than with recurrent layers. Even inside the hybrid camp the attention layers keep changing. Qwen's August 2026 design report on Qwen3.8-Flash-Next (Qiu et al. 2026) keeps Gated DeltaNet in three of every four layers. During continued pretraining, it replaces the full-attention layers by a sparse attention.
model
date
layers
attention fraction
recurrent layer
MoE
context
KV per token, bf16
Llama 3.1 8B (reference)
2024-07
32
100%
none
no
128K
128 KiB
Jamba v0.1
2024-03
32
4 of 32
Mamba-1, N=16
16 experts, top-2
256K
16 KiB
Mamba-2-Hybrid 8B
2024-06
56 blocks
4 attention, 24 Mamba-2
Mamba-2
no
4K to 128K
not listed
Granite 4.0-H Small
2025-10
40
4 of 40
Mamba-2, N=128
72 experts, top-10
128K
16 KiB
Kimi Linear 48B-A3B
2025-10
27
7 of 27 (MLA)
KDA
256 experts, top-8
1M
7.9 KiB
Nemotron 3 Nano 30B-A3B
2025-12
52 blocks
6 attention, 23 Mamba-2
Mamba-2, N=128
128 experts, top-6
1M
6 KiB
Qwen3.5-397B-A17B
2026-02
60
15 of 60
Gated DeltaNet
512 experts, top-10
262K
30 KiB
Memory at real scale
A serving engineer sizes a deployment by one question, how many sequences of a given length fit in the memory left after the weights. The arithmetic is short. Each global attention layer with nkv KV heads of width dk stores 2nkvdk numbers per token, the keys and the values, at 2 bytes each in bf16. Each recurrent layer stores a fixed state plus a convolution cache of three past inputs. The cell computes both from the published configurations.
Python · cell 10
The widget below lays out the token-mixing layers of seven published models and counts the cache one sequence needs, with KV entries and convolution caches in bf16, recurrent states in fp32, and weights not counted. When you move the slider, the remaining layers become the model's recurrent type, a hypothetical Mamba-2 layer for Llama 3.1 8B. The memory left for caches is 80 GiB.
How many attention layers can you afford, and what do they cost at long context?
Each square is one token-mixing layer. Bars are the cache one sequence needs, beside 80 GiB of memory.
Loading interactive figure…
Interview
Memory planner for hybrid models
Write the cache planner a serving engineer uses to size a deployment. A config is a dict with a pattern string, one character per block, and one entry of dimensions per layer type present. The characters are * for global attention, M for Mamba-2, m for Mamba-1, G for Gated DeltaNet, and E or - for an MoE or MLP block that caches nothing.
layer_memory(cfg, T, batch=1, kv_bytes=2, state_bytes=4) returns a dict with integer byte counts kv, state, conv, and total for batch sequences of T tokens.
max_context(cfg, budget, batch=1, kv_bytes=2, state_bytes=4) returns the largest integer T whose total fits in budget bytes (total at most budget). It returns None if even T = 0 does not fit, and math.inf if the model has no attention layer and its state fits.
Each layer type stores the following.
Attention stores keys and values, 2nkvdhead numbers per token.
Mamba-2 stores nheadsdheadN state numbers and a convolution cache of (dconv−1)(nheadsdhead+2GN) numbers.
Mamba-1 stores dinnerN state numbers and (dconv−1)dinner convolution numbers.
Gated DeltaNet stores nvdkdv state numbers and (dconv−1)(2nqkdk+nvdv) convolution numbers.
States use state_bytes, while keys, values, and convolution caches use kv_bytes. Use Python integers, so that a million tokens times a batch of 64 does not overflow.
Tests, hints, verified solutions, and AI help, with Pro at $7.99 a month.
The case against
The serving points are concrete. A KV cache is a list of per-token blocks. Two requests that share a prompt prefix can reuse its blocks by pointer, which is called prefix caching (§20.6). In speculative decoding, a cheap draft proposes several tokens and the model verifies them in one pass (§20.5). When a guessed token is rejected, the KV cache is just truncated.
A recurrent state is one matrix that every token overwrites, so neither trick comes for free. Reusing a prefix means storing snapshots of the state at chosen positions. Rolling back a rejected draft means keeping the states from before it, or recomputing them. Both are solvable, and serving engines now ship them, but they are engineering that full attention never needed. The gap is closing from the model side too. Nemotron 3 Super ships multi-token-prediction layers, extra heads that propose the next few tokens, for speculative decoding on its Mamba-attention backbone.
The table puts the options side by side, as a design review would.
token mixer
training cost per layer
decode cost per token
memory at long context
exact recall
state tracking in one pass
kernels and serving
full softmax attention
O(T2d), FlashAttention
grows with T
KV cache grows with T
yes
limited to TC0
mature
sliding-window attention
O(Twd) for window w
bounded by w
bounded
within the window
limited
mature
sparse attention (DeepSeek Sparse Attention)
a small scorer picks the top k past tokens
grows slowly
full cache kept
mostly
limited
maturing
Mamba-2 (SSD)
O(TNP) per head, matmuls
constant
constant
degrades with load
no parity (positive decays)
good
Gated DeltaNet, KDA
O(Tdkdv) plus WY, matmuls
constant
constant
better than Mamba-2, still bounded
parity only if β may exceed 1 (not as shipped)
good, newer
hybrid, 1 attention in 4 to 10
mostly linear
small growing part
cache of the attention layers only
yes, through attention
limited, as for its parts
prefix caching and rollback need work
What is still open
Several questions were unsettled as of late 2026.
The right ratio of attention to recurrent layers, as models and contexts grow, is still found by sweeps. No theory predicts it.
Long multi-hop reasoning was MiniMax's failure case. Whether it is a fundamental weakness of hybrids or an artifact of particular designs has not been settled by a public, controlled study at scale.
State tracking in pretrained models, as opposed to synthetic tasks, is barely measured.
Richer memories in the test-time-regression family (TTT, Titans, DeltaProduct) are early.
Sparse attention (§12.6) is a competing way to cut attention's cost, and Qwen's 2026 design report already combines the two.
Reasoning models that generate tens of thousands of tokens per answer make decode cost dominate (§18.7), and so do agents that run for many steps. That is the strongest argument that cheap recurrent decoding will matter more, not less.
🎬 On the Tradeoffs of State Space Models · Simons Institute for the Theory of ComputingAlbert Gu on the state as compression, SSD, and what fixed states trade against attention, which motivates the hybrids.🎬 Linear Attention and Beyond (Interactive Tutorial with Songlin Yang) · Sasha RushThe author of DeltaNet and Gated DeltaNet on gating, the delta rule, and chunked training, the core of this section's family tree.🎬 Lecture 60: Optimizing Linear Attention · GPU MODEHow chunkwise linear-attention and delta-rule kernels are built on GPUs, the systems side of the chunked algorithm and the WY representation.🎬 The Mamba in the Llama: Distilling and Accelerating Hybrid Models · Sasha RushTurning a pretrained Transformer into a hybrid that keeps a quarter of its attention layers, and decoding it speculatively.