State Space Models for Language

Michael BrenndoerferNovember 17, 202638 min read

Learn how state space layers replace growing key-value caches with fixed recurrent state. Covers discretization, S4, Mamba, and SSD.

Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 133State Space Models for Language
Reading the full chapter · 13 sections · 38 min13 sections · 38 min

All 13 sections · 38 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

State Space Models for Language

When you generate the next token after a long document, a full causal attention layer can compare its query with the keys at every processed position. The layer keeps separate key and value vectors for those positions, so both the cache and the work to read from it grow with the prefix. At 100,000 positions, the same cache calculation that was cheap for a short prompt can dominate a memory budget.

A state space layer keeps a fixed-size state per sequence. Each new input updates that state, and a readout produces the layer's output. With the layer sizes and batch size fixed, the amount of recurrent state and the number of arithmetic operations for one recurrent update are independent of how many positions came before. A layer that needs to recall an old detail must recover it from the state its updates have retained. This chapter derives the update, computes a fixed system in two equivalent ways, then uses a small experiment to show how the history can fade when the update retains only a fraction of the previous state.

Two Memory Systems

Efficient Attention introduced methods for evaluating attention more cheaply. Here we compare one conventional full causal attention layer to a recurrent state space layer.

Key-Value Cache

For one attention head, let qk∈Rdkq_k \in \mathbb{R}^{d_k} be the query at position kk. The cache holds the matching keys kj∈Rdkk_j \in \mathbb{R}^{d_k} and values vj∈Rdvv_j \in \mathbb{R}^{d_v} for already processed positions. A causal attention output is ∑j≤kαkjvj\sum_{j\le k} \alpha_{kj} v_j, with αkj=softmaxj(qk⊤kj/dk)\alpha_{kj} = \mathrm{softmax}_j(q_k^\top k_j / \sqrt{d_k}). For a completed prefix of length LL, the cache of this head uses L(dk+dv)L(d_k + d_v) scalars. With equal key and value widths dd, that becomes 2Ld2Ld.

Recurrent State

A scalar-input state space layer updates xk∈RNx_k \in \mathbb{R}^N from xk−1x_{k-1} and its input at position kk. It reads an output from the resulting state. With HH parallel channels of this type, the recurrent state uses HNHN scalars per sequence.

An attention query can assign different weights to two occurrences of a name if their keys give it different scores. A recurrent state can track a statistic such as how often a specified name appears. That count alone cannot tell you where a particular occurrence appeared.

The recurrence introduces another practical question. Evaluating one update at a time creates a dependency chain of length LL. When the transition, write, readout, and direct-path coefficients are fixed and the initial state is zero, the layer's input contribution can be evaluated as a causal convolution. The rest of this chapter develops that equivalence and shows what to compute when the weights vary with the input.

The Continuous-Time State Space Model

Consider a system driven by a scalar signal u(t)u(t). At continuous time tt, the state x(t)x(t) is a vector of NN coordinates. A differential equation describes the change of that vector, and a readout produces a scalar output y(t)y(t).

ddtx(t)=Ax(t)+Bu(t),y(t)=Cx(t)+Du(t).\begin{aligned} \frac{d}{dt}x(t) &= Ax(t) + Bu(t), \\ y(t) &= Cx(t) + Du(t). \end{aligned}
  • A∈RN×NA \in \mathbb{R}^{N\times N} describes the dynamics of the state in the absence of input.
  • B∈RN×1B \in \mathbb{R}^{N\times1} distributes the scalar input over the state coordinates.
  • C∈R1×NC \in \mathbb{R}^{1\times N} takes a weighted sum of the state.
  • D∈RD \in \mathbb{R} scales the direct path from input to output.

With a diagonal AA, each coordinate moves independently in response to the same scalar input. If a coordinate has rate a<0a<0, its value in the absence of input changes by a factor of eate^{at} after time tt. Rates closer to zero decay more slowly. The write and readout vectors determine how strongly each mode participates in the input and output. More general state matrices can also mix state coordinates. Many deep sequence models build a vector-valued layer by applying scalar-input state space computations along several channels and using learned projections to mix channels around them. This development starts from the continuous state equation used by Gu, Goel, and Ré, sections 2 and 3.4.

Why Linearity Matters

The state equation is linear jointly in xx and uu. If the initial state is zero, the output due to a sum of input signals is the sum of the outputs due to the individual signals. You can therefore study how the system responds to individual impulses and add those responses together. When the coefficients stay fixed, an impulse at a later time produces a shifted copy of the same response. Together, those two properties give the convolution representation.

A standard recurrent neural network can apply a nonlinearity inside its update from the previous state. That generally invalidates superposition. State space networks can retain a linear state operator and introduce nonlinear operations around it, such as a gate computed from the layer input. We will use that distinction to understand what Mamba can parallelize.

What "Linear Time Invariant" Means

A linear time-invariant (LTI) state space layer uses the same matrices at every position, and its zero-state response is linear in the input. The contribution from an impulse then depends on the lag since it arrived. For a fixed input coordinate and output coordinate, the layer applies that same lag-dependent rule to each signal value it sees.

Discretization with a Zero-Order Hold

A sequence gives one input uku_k per position. Choose a step size Δ>0\Delta>0 and hold u(t)=uku(t)=u_k over [kΔ,(k+1)Δ)[k\Delta,(k+1)\Delta). This is a zero-order hold (ZOH). Name the state at the start of the interval xk−1x_{k-1} and the state at its end xkx_k, so input u0u_0 updates initial state x−1x_{-1}. We read out by combining the endpoint state with the held input uku_k before the next input replaces it. Integrating the linear equation across the interval gives

x((k+1)Δ)=eΔAx(kΔ)+∫0Δe(Δ−τ)ABuk dτ.x((k+1)\Delta) = e^{\Delta A}x(k\Delta) + \int_0^\Delta e^{(\Delta-\tau)A}Bu_k\,d\tau .

The first term propagates the initial state. The integrand propagates the contribution made at each instant τ\tau for the remaining time Δ−τ\Delta-\tau. Reversing the integration variable and pulling the constant input outside the integral gives the recurrence below.

xk=Aˉxk−1+Bˉuk,Aˉ=eΔA,Bˉ=(∫0ΔeτA dτ)B.x_k = \bar A x_{k-1} + \bar B u_k,\qquad \bar A = e^{\Delta A},\qquad \bar B = \left(\int_0^\Delta e^{\tau A}\,d\tau\right)B.

With our endpoint convention, the output is yk=Cxk+Duky_k=Cx_k+Du_k. The step changes the transition and the write map. The readout CC and direct path DD already act on instantaneous values.

The Integral and Singular Matrices

For invertible AA, the integral equals A−1(eΔA−I)A^{-1}(e^{\Delta A}-I). The integral itself works for singular matrices too. To see why, integrate the matrix exponential's power series term by term.

∫0ΔeτA dτ=∑j≥0Δj+1(j+1)!Aj.\int_0^\Delta e^{\tau A}\,d\tau = \sum_{j\ge 0}\frac{\Delta^{j+1}}{(j+1)!}A^j .

The factorial in the denominator gives convergence for any finite square matrix. For A=0A=0, the only nonzero term is ΔI\Delta I, so each step adds ΔBuk\Delta Bu_k.

A Diagonal Example You Can Compute by Hand

Take N=1N = 1 and a single stable rate a<0a < 0. The continuous system is x′=ax+bux' = a x + b u. Then

aˉ=eΔa,bˉ=b⋅eΔa−1a.\bar{a} = e^{\Delta a}, \qquad \bar{b} = b \cdot \frac{e^{\Delta a} - 1}{a}.

Since a<0a < 0 and Δ>0\Delta > 0, the factor Δa\Delta a is negative, so aˉ∈(0,1)\bar{a} \in (0, 1). The discrete system is a geometric decay. Two sanity checks are worth doing.

First, as a→0a \to 0 the fraction (eΔa−1)/a(e^{\Delta a} - 1)/a tends to Δ\Delta, so bˉ→Δb\bar{b} \to \Delta b. With a zero rate, the state simply accumulates the input. Mamba's reference implementation also uses Δb\Delta b, as a first-order approximation to the write at finite rates.

Second, the continuous half-life is ln⁡2/∣a∣\ln 2 / |a| in units of time. The discrete half-life in units of steps is

h1/2=ln⁡2Δ ∣a∣.h_{1/2} = \frac{\ln 2}{\Delta\, |a|}.

For a single mode, Δ∣a∣\Delta |a| sets the half-life in step units. This scale can be fractional. The first whole update at which the magnitude is at or below half its starting value is ⌈h1/2⌉\lceil h_{1/2}\rceil.

When the rate stays fixed, increasing the step size makes one update cover more continuous time. The contribution decays more in each step. Later we will let the input determine the step size separately at each position.

PythonIn [3]
CollapseExpand
import numpy as np

rate_grid = -np.logspace(np.log10(0.01), np.log10(4.0), 240)  # a in [-4, -0.01]
step_grid = np.logspace(
    np.log10(0.01), np.log10(2.0), 240
)  # Delta in [0.01, 2]
persistence = np.exp(
    np.multiply.outer(step_grid, rate_grid)
)  # shape (step, rate)

halflife_steps = np.log(2.0) / np.multiply.outer(step_grid, -rate_grid)

We now have a grid of aˉ=eΔa\bar{a} = e^{\Delta a} over a range of continuous rates and step sizes. The map below makes the joint dependence visible.

VisualizationOut [4]
CollapseExpand
Heatmap of discrete persistence over continuous decay rate and step size.
The remaining fraction of an existing state after one held-input interval. The contours connect decay rates and step sizes that give the same half-life in steps.

A point near the upper left combines a large step with a strongly negative rate. Little of the previous state survives that step. As you move toward the lower right, the rate and the step produce a multiplier closer to one. The contour lines pick out combinations with the same half-life.

Linear Time Invariance and the Convolution View

Now set the initial state to zero, x−1=0x_{-1} = 0, and unroll the recurrence for a few steps to see the pattern.

x0=Bˉu0x1=AˉBˉu0+Bˉu1x2=Aˉ2Bˉu0+AˉBˉu1+Bˉu2\begin{aligned} x_0 &= \bar{B} u_0 \\ x_1 &= \bar{A}\bar{B} u_0 + \bar{B} u_1 \\ x_2 &= \bar{A}^2 \bar{B} u_0 + \bar{A}\bar{B} u_1 + \bar{B}u_2 \end{aligned}

At each step the state receives another input and propagates every earlier contribution through one more application of the transition. An input from jj therefore passes through k−jk-j transitions by position kk. The general form is

xk=∑j=0kAˉ k−jBˉ uj.x_k = \sum_{j=0}^{k} \bar{A}^{\,k-j} \bar{B}\, u_j .

Apply the readout to that state.

yk=∑j=0kCAˉ k−jBˉ uj+D uk.y_k = \sum_{j=0}^{k} C \bar{A}^{\,k-j} \bar{B}\, u_j + D\, u_k .

Define the state-mediated impulse response taps

Kˉj=CAˉ jBˉfor j≥0.\bar{K}_j = C \bar{A}^{\,j} \bar{B} \quad \text{for } j \ge 0 .

With zero initial state, a unit input at position zero produces the state-mediated response Kˉj\bar K_j at lag jj. An input of amplitude uju_j at position jj contributes ujKˉk−ju_j\bar K_{k-j} to the state-mediated output at position k≥jk\ge j. Summing these scaled, shifted responses gives the causal convolution. The direct path adds DukD u_k.

yk=∑j=0kKˉj uk−j+D uk.y_k = \sum_{j=0}^{k} \bar{K}_j\, u_{k-j} + D\, u_k .

Three things are doing work here.

Zero initial state. For x−1≠0x_{-1}\ne0, add CAˉk+1x−1C\bar A^{k+1} x_{-1} to the convolution output at position kk. This term propagates the existing state over the same k+1k+1 updates.

Causal truncation. The sum at kk includes only lags 00 through kk. For the first LL outputs, it is exact to build a length-LL kernel and retain the first LL entries of the full linear convolution. Later taps would apply only at later outputs.

The direct path. The direct contribution changes the lag-zero tap to CBˉ+DC\bar B+D. The later taps stay at CAˉjBˉC\bar A^j\bar B. The example below folds the direct path into the lag-zero tap.

For a known sequence, the convolution can evaluate the LL outputs together. During autoregressive decoding, an implementation can use the recurrence to update its last state as each new input arrives. For a diagonal transition, updating and reading a state of width NN uses O(N)O(N) arithmetic per channel.

The equality between convolution and recurrence holds in exact arithmetic. A numerical comparison needs a tolerance because the two evaluation orders accumulate rounding differently.

Building the Kernel and Applying It

Building a length-LL kernel and applying it are separate computations.

  • Build the taps. In a diagonal system of state size NN, you can start with Bˉ\bar B and multiply elementwise by the diagonal of Aˉ\bar A for each lag. A dot product with CC gives each tap. That uses O(NL)O(NL) arithmetic for one channel.
  • Apply the kernel. Direct convolution over the causal pairs takes O(L2)O(L^2) arithmetic per channel. FFT convolution with padding for a linear convolution takes O(Llog⁡L)O(L\log L) for that length. Keep the first LL outputs for the causal readout.

S4 builds its kernel by evaluating the finite generating function at the LL roots of unity and transforming those evaluations back to coefficients. For a complex evaluation point zz, the finite sum is

K^(z)=∑j=0L−1Kˉjzj=C(∑j=0L−1(zAˉ)j)Bˉ.\widehat K(z) = \sum_{j=0}^{L-1}\bar K_j z^j = C\left(\sum_{j=0}^{L-1}(z\bar A)^j\right)\bar B .

When I−zAˉI-z\bar A is invertible, summing the matrix geometric series gives

K^(z)=C(I−zAˉ)−1(I−(zAˉ)L)Bˉ.\widehat K(z) = C(I-z\bar A)^{-1}\bigl(I-(z\bar A)^L\bigr)\bar B .

At the roots of unity the last factor is I−AˉLI-\bar A^L. This factor preserves the exact finite kernel, including modes that still carry substantial weight at lag LL. It can be merged into the readout because it commutes with (I−zAˉ)−1(I-z\bar A)^{-1}. This leaves an expression that a structured matrix algorithm can compute across the evaluation points. See S4, section 3.2 and Appendix C.

S4 and Structured State Matrices

The Structured State Space model (S4) makes long convolution kernels practical to compute from a recurrent state space representation. The revised paper reports 86.09% average accuracy for the updated S4 model across its Long Range Arena suite, including 96.35% on Path-X. Those are sequence benchmark results from the evaluated model and tasks. Gu, Goel, and Ré, Table 2 and Appendix D.2 Table 4.

  • HiPPO initialization. S4 initializes the state dynamics from HiPPO matrices. At each time, HiPPO projects the signal history onto a finite span of polynomials. The measure for that time assigns weights to different parts of the history. The orthogonal projection minimizes the weighted squared approximation error within the span. The construction supplies an initialization for S4. HiPPO, section 2.2 and S4, sections 2.2 and 4.4.
  • Normal plus low rank. S4 exploits a decomposition of the state matrix into a normal part VΛV∗V\Lambda V^* and a low-rank correction −PQ⊤-PQ^\top. The columns of the unitary matrix VV provide a stable change of basis that makes the normal part diagonal. In that basis the full state matrix is diagonal plus low rank. The Woodbury identity reduces the inverse of a diagonal matrix with a low-rank correction to diagonal inverses and a small inner solve, when the relevant inverses exist. The resulting kernel evaluations reduce to structured Cauchy matrix products. Gu, Goel, and Ré, section 3.2 and Appendix C.3.
  • Bilinear discretization. The original S4 paper computes its discrete transition and write matrices using the bilinear transform. This choice supports an efficient structured recurrent update. Gu, Goel, and Ré, section 2.3 and Appendix C.2.

In the bilinear formula, Δ\Delta is the step size and AA and BB are the continuous-time matrices. The formulas require I−(Δ/2)AI-(\Delta/2)A to be invertible. This holds for Δ>0\Delta>0 when every eigenvalue of AA has negative real part.

Aˉ=(I−Δ2A)−1(I+Δ2A),Bˉ=(I−Δ2A)−1ΔB.\bar A = \left(I-\frac{\Delta}{2}A\right)^{-1} \left(I+\frac{\Delta}{2}A\right),\qquad \bar B = \left(I-\frac{\Delta}{2}A\right)^{-1}\Delta B .

For a negative scalar rate aa and a positive step, the discrete pole is (1+Δa/2)/(1−Δa/2)(1+\Delta a/2)/(1-\Delta a/2). Its magnitude is less than one because the magnitude of the numerator is strictly less than the denominator. The ZOH pole eΔae^{\Delta a} is also stable under these conditions. Both transitions are 1+Δa+O(Δ2)1+\Delta a+O(\Delta^2) near Δ=0\Delta=0, so they agree through the linear term in the step size. The worked example in this chapter uses the exact hold formulas for a diagonal system.

Mamba and Input-Dependent Selection

The fixed S4 kernel gives two inputs at the same lag the same weight before reading their values. An input-conditioned update gives the layer a second way to distinguish them. The Mamba paper motivates this with a selective copying task. The sequence places relevant symbols among distractors with variable spacing, so the location of the information that needs to survive changes from one example to the next.

The Three Projections

In Mamba-1's selective layer, let uk∈RHu_k \in \mathbb{R}^H be the channel vector being processed at position kk. Three learned projections of that vector give a step size for each channel, a write vector, and a read vector. A simplified expression is

Δk=softplus(WΔuk+bΔ),Bk=WBuk,Ck=WCuk.\Delta_k = \mathrm{softplus}(W_\Delta u_k+b_\Delta),\qquad B_k=W_B u_k,\qquad C_k=W_C u_k .

Here Δk∈RH\Delta_k \in \mathbb{R}^H, Bk,Ck∈RNB_k,C_k \in \mathbb{R}^N, and bΔb_\Delta is a learned bias. The projections are shared across positions. Mamba-1 shares the resulting BkB_k and CkC_k vectors across the HH channels. Each channel has its own learned diagonal continuous-time rates in AA, which are shared across positions. The input-dependent step size makes the discrete transition Aˉk\bar A_k vary by position. The reference block implements the step-size projection through a low-rank intermediate. Mamba, Algorithm 2 and section 3.6. Mamba-1 reference block, v2.2.4.

For a negative rate aa in a particular channel, eΔkae^{\Delta_k a} is the multiplier on the previous state. A small positive Δk\Delta_k brings it close to one. A larger Δk\Delta_k makes the multiplier smaller, so less of the old state carries through. The step size also affects the write strength. BkB_k controls which coordinates receive the input, and CkC_k controls which coordinates the readout uses.

The Recurrence

For one channel, write its scalar input as uku_k and its state as xkx_k. The channel index is suppressed in the step size and the transition matrix. After discretization the computation takes the form

xk=Aˉkxk−1+Bˉkuk,yk=Ck⊤xk+Duk.x_k=\bar A_k x_{k-1}+\bar B_k u_k,\qquad y_k=C_k^\top x_k+Du_k .

After computing the coefficients for a given input sequence, the write at position jj contributes Aˉk⋯Aˉj+1(Bˉjuj)\bar A_k\cdots\bar A_{j+1}(\bar B_j u_j) to xkx_k. For a coordinate with continuous rate ana_n, the intervening multipliers are ∏i=j+1keΔian\prod_{i=j+1}^k e^{\Delta_i a_n}. When j=kj=k, the product has no factors and equals one. The readout then takes the dot product of CkC_k with the state. Editing an input can change both its own write and the transition that carries earlier writes forward.

Once those coefficients have been computed, the update is affine in the previous state. The full map from an input sequence to its outputs is generally nonlinear because the coefficients themselves depend on the input. A different input sequence can have a different matrix of lag interactions, so the fixed-kernel convolution from the LTI case gives way to a scan.

The Reference Implementation's Discretization

The Mamba v2.2.4 selective scan reference computes the transition with the same exponential as exact ZOH and uses a first-order approximation for the write. In one channel, for state coordinate nn, the code implements the following recurrence.

xk,n=eΔkanxk−1,n+ΔkBk,nuk.x_{k,n}=e^{\Delta_k a_n}x_{k-1,n}+\Delta_k B_{k,n}u_k .

The exact held-input term uses Bk,n(eΔkan−1)/anB_{k,n}(e^{\Delta_k a_n}-1)/a_n as its coefficient on uku_k for an≠0a_n\ne0. Expanding the exponential around Δk=0\Delta_k=0 gives Δk+12anΔk2+O(Δk3)\Delta_k+\tfrac12a_n\Delta_k^2+O(\Delta_k^3) for the fraction at fixed ana_n. This is why the implementation's Δk\Delta_k coefficient agrees through first order. In a numerical replication, use the discrete update from the code version you intend to match.

The Affine Map and Associative Composition

For scan, represent one update by a pair (Tk,wk)(T_k,w_k), where Tk=AˉkT_k=\bar A_k is the transition and wk=Bˉkukw_k=\bar B_k u_k is the input contribution. The pair acts on a state as x↦Tkx+wkx\mapsto T_k x+w_k. Applying update 11 and then update 22 gives

T2(T1x+w1)+w2=(T2T1)x+(T2w1+w2).T_2(T_1 x+w_1)+w_2=(T_2T_1)x+(T_2w_1+w_2).

The whole segment has the same form as a single update, with transition T2T1T_2T_1 and write term T2w1+w2T_2w_1+w_2. Define composition with the later pair on the left.

(T2,w2)∘(T1,w1)=(T2T1,T2w1+w2).(T_2,w_2)\circ(T_1,w_1)=(T_2T_1,T_2w_1+w_2).

Composition is associative in exact arithmetic since it is just composition of the represented affine maps. It is generally order-sensitive. The identity pair (I,0)(I,0) leaves a state unchanged. A prefix scan can group the compositions in a tree while preserving the order. Applying the resulting pair for each prefix to x−1x_{-1} gives the state at the end of that prefix.

With diagonal transitions, each product of matrices becomes an elementwise product of their diagonals. Each pair composition uses O(N)O(N) arithmetic for one channel. A dense implementation can still use the same pair formula but composes its dense transitions with matrix multiplication.

Work and Depth of a Scan

Keep the state width fixed and count each affine composition as one unit of work. Span counts levels along the longest chain of dependencies. The plot shows the levels used by each schedule, including any wait between phases. The sequential baseline starts from the identity pair and composes one new pair into the running prefix at each position. Under this convention it uses LL compositions in LL levels.

  • Hillis–Steele. In round rr, positions with a predecessor 2r2^r places away combine the two ordered results from the previous round. Round r=0r=0 starts at offset one. Over ⌈log⁡2L⌉\lceil\log_2 L\rceil rounds, work is O(Llog⁡L)O(L\log L) and span is O(log⁡L)O(\log L).
  • Blelloch. An up-sweep combines each adjacent pair of subtrees. A down-sweep distributes the prefix to each position. On a power-of-two input, the exclusive scan schedules the sweeps in order, each with L−1L-1 compositions and log⁡2L\log_2 L levels. An exclusive prefix omits the current update. Composing it with that update yields the inclusive prefix and adds at most LL compositions on one more level. The work stays O(L)O(L) and the span stays O(log⁡L)O(\log L).

For a power-of-two LL, there are L−2rL-2^r Hillis–Steele compositions in round rr, which sum to Llog⁡2L−L+1L\log_2 L-L+1. The plot counts operations and levels in these schedules. Elapsed time also depends on how hardware schedules the work and moves intermediate arrays.

PythonIn [5]
CollapseExpand
scan_lengths = np.array([2**k for k in range(4, 19)], dtype=float)
hillis_steele_levels = np.log2(scan_lengths)
hillis_steele_work = scan_lengths * hillis_steele_levels - scan_lengths + 1
blelloch_levels = 2.0 * hillis_steele_levels
blelloch_work = 2.0 * (scan_lengths - 1)
VisualizationOut [6]
CollapseExpand
Log-log plot of scheduled levels and total compositions. A shared sequential curve shows that its two counts coincide.
Scheduled levels and pair-composition counts on power-of-two inputs. The Blelloch counts show the exclusive scan before forming inclusive prefixes.

One curve shows both sequential counts. The number of scheduled levels grows logarithmically for both parallel scans. Hillis–Steele revisits overlapping prefixes in each round, while Blelloch uses a two-sweep tree and does less work as sequence length grows.

A Teaching Reference and a Fused Kernel

A NumPy loop can implement the recurrence exactly as written and makes a useful reference for checking a faster implementation. Accelerator kernels also need to control which intermediate arrays they write to high-bandwidth memory (HBM).

An implementation that keeps every intermediate state builds an array of shape (B,H,L,N)(B,H,L,N) for batch size BB, channel width HH, sequence length LL, and state dimension NN. At B=1B=1, H=2048H=2048, L=8192L=8192, and N=16N=16, one such float32 array holds 2282^{28} scalars. At four bytes each, it occupies 2302^{30} bytes, or 11 GiB.

Mamba-1's fused design combines discretization, an associative scan, and readout in the same kernel. It works on chunks in fast on-chip memory and carries the scan state across chunk boundaries. The forward implementation can thereby avoid saving the full expanded state array to HBM. Recomputing intermediates in the backward pass reduces the amount that must be saved for differentiation. Compared with an implementation that writes the full state trajectory to HBM, the fused forward pass avoids that write. The backward pass trades some saved intermediates for recomputation. Both evaluate the same recurrence, subject to rounding differences from arithmetic order or precision. Mamba, section 3.3 and Appendix D.

Mamba-2 and Structured State Space Duality

Mamba-2 uses a structured state space duality (SSD) layer. The discrete transition for a head is Ak=akIA_k=a_k I, so each state coordinate within that head has the same multiplier. Suppress the head index and look at one value channel with zero initial state. Let BjB_j denote the discrete write vector at input position jj and CiC_i the read vector at output position ii. The sequence mixing matrix for fixed coefficients has entries

Mij={Ci⊤Bj∏k=j+1iak,i≥j,0,i<j.M_{ij} = \begin{cases} C_i^\top B_j\displaystyle\prod_{k=j+1}^i a_k, & i\ge j,\\ 0, & i< j. \end{cases}

The product equals one when i=ji=j. If the discrete inputs in that channel form the vector uu, the outputs are MuMu before any direct path. The inner product Ci⊤BjC_i^\top B_j resembles a query-key score. SSD multiplies this score by a causal mask of decay products without softmax normalization. In standard scaled dot-product attention, softmax normalizes the scaled scores over each query's allowed positions.

Consider the block of entries with inputs j≤bj\le b and outputs i>bi>b, for a time boundary after position bb. Split each decay product at bb. The factors through bb carry the write at jj into the state xbx_b. The later factors propagate that state to the readout at ii. The entire block factors through the NN coordinates of xbx_b, so its rank is at most NN. SSD uses this semiseparable structure to apply matrix multiplications within chunks and carry state summaries between chunks. The resulting implementation can use accelerator matrix multiplication units. Mamba-2 also uses a larger head dimension PP than Mamba-1's single value channel per head. Dao and Gu, sections 2.4, 3.2 and 6.

For the plot, sample the write and read vectors for a synthetic sequence with 32 positions and state size four. Build its dense mixing matrix directly from the positive decay factors. For LL positions, the mixing matrix has L2L^2 entries. The code allocates a second L2L^2 array for decay products. The decay loop visits (L3−L)/6(L^3-L)/6 factors, since the product for indices (i,j)(i,j) has i−ji-j factors. SSD's chunked algorithm applies the mixing through within-chunk products and recurrent boundary states.

PythonIn [7]
CollapseExpand
import numpy as np

ssd_L = 32
ssd_N = 4
ssd_rng = np.random.default_rng(7)

ssd_C = ssd_rng.normal(size=(ssd_L, ssd_N))
ssd_B = ssd_rng.normal(size=(ssd_N, ssd_L))
ssd_step_decay = 0.90 + 0.07 * np.sin(np.linspace(0.0, 3.0 * np.pi, ssd_L))

ssd_scale = np.ones((ssd_L, ssd_L))
for i in range(ssd_L):
    for j in range(i):
        ssd_scale[i, j] = np.prod(ssd_step_decay[j + 1 : i + 1])

ssd_matrix = np.zeros((ssd_L, ssd_L))
for i in range(ssd_L):
    ssd_matrix[i, : i + 1] = ssd_C[i] @ (
        ssd_scale[i, : i + 1] * ssd_B[:, : i + 1]
    )

ssd_abs_max = np.abs(ssd_matrix).max()
ssd_diagonal = np.array([0, ssd_L - 1])
VisualizationOut [8]
CollapseExpand
Heatmap with input position on the horizontal axis and output position increasing upward. The area below the dashed diagonal is zero.
Synthetic SSD mixing matrix for 32 positions and four state coordinates. Future input positions have zero weight. Since output indices increase upward, those entries appear below the dashed diagonal.

Worked Example

The first NumPy example verifies that a fixed layer's recurrence and causal convolution give the same output within tolerance. The second uses a scalar state to show what happens when a programmed write must survive several updates.

A Fixed Linear SSM, Computed Two Ways

We construct a diagonal system with four stable modes, sample it with a zero-order hold, and then compute the output by (a) running the recurrence and (b) building the kernel and convolving. If the algebra in the previous sections is right, the two outputs agree to floating-point precision.

PythonIn [9]
CollapseExpand
import numpy as np

rng = np.random.default_rng(11)
N, L = 4, 24

# Draw four rate magnitudes from a log-uniform range.
a = -np.exp(rng.uniform(np.log(0.05), np.log(2.0), size=N))
B = rng.normal(size=N)
C = rng.normal(size=N)
D = 0.25
step = 0.1
ConsoleOut [10]
CollapseExpand
continuous rates a: [-0.0803 -0.3154 -0.4598 -0.0556]
input map B:        [-0.298 -0.527  0.57  -0.056]
readout map C:      [ 0.747 -1.847  1.567 -0.096]
direct path D:      0.25
step size Delta:    0.1

The rates are all negative, so every mode is stable and every discrete pole lies strictly inside the unit circle. Next we discretize with the zero-order hold from the earlier derivation.

PythonIn [11]
CollapseExpand
Abar = np.exp(step * a)  # diagonal of exp(Delta A)
Bbar = np.expm1(step * a) / a * B  # (integral of exp(tau A) dtau) B
ConsoleOut [12]
CollapseExpand
mode 0: a=-0.0803  Abar=0.9920  half-life=86.27 steps
mode 1: a=-0.3154  Abar=0.9690  half-life=21.98 steps
mode 2: a=-0.4598  Abar=0.9551  half-life=15.07 steps
mode 3: a=-0.0556  Abar=0.9945  half-life=124.71 steps

The printed half-lives tell you how quickly an existing contribution fades in each mode. Next, draw an input sequence and apply the recurrence from zero initial state.

PythonIn [13]
CollapseExpand
u = rng.normal(size=L)

x = np.zeros(N)
y_recurrent = np.empty(L)
for k in range(L):
    x = Abar * x + Bbar * u[k]
    y_recurrent[k] = C @ x + D * u[k]

The second computation builds the kernel taps Kˉj=CAˉ jBˉ\bar{K}_j = C\bar{A}^{\,j}\bar{B} and folds the direct path into the j=0j = 0 tap. Then it evaluates the causal convolution directly, in O(L2)O(L^2) fashion, which is fine at this scale.

PythonIn [14]
CollapseExpand
kernel = np.empty(L)
example_positions = np.arange(L)
power = np.ones(N)  # Abar^0
for j in range(L):
    kernel[j] = C @ (power * Bbar)
    power = power * Abar  # Abar^(j+1)
kernel[0] += D  # direct path lives on the first tap

y_conv = np.zeros(L)
for k in range(L):
    for j in range(k + 1):
        y_conv[k] += kernel[j] * u[k - j]

kernel_conv_matches = np.allclose(y_recurrent, y_conv, atol=1e-12, rtol=0.0)
assert kernel_conv_matches
ConsoleOut [15]
CollapseExpand
max |recurrent - convolution| = 4.441e-16
first six kernel taps: [0.4115 0.1548 0.1483 0.1421 0.1362 0.1305]
  of which the j=0 tap contains D = 0.25
recurrence matches causal convolution: True

The recurrence and causal convolution agree within the absolute tolerance of 10−1210^{-12}. In this run the maximum difference is about 4.44×10−164.44\times10^{-16} because the computations accumulate floating-point terms in a different order.

The plots show the first LL kernel taps and both output sequences. The model can use additional taps if it processes a longer sequence.

VisualizationsOut [16]
CollapseExpand
Bar chart of decaying convolution kernel taps.
Full taps $\bar{K}_j + D\,\mathbb{1}\{j=0\}$ of the discretized four-mode system.
Line plot of recurrent and convolution outputs whose curves overlap at the plot scale.
Output computed by the recurrence and by causal convolution. The two agree to floating-point precision.

The lag-zero bar includes the direct contribution D=0.25D=0.25. At other lags the bar is a signed sum of decaying modes. The recurrence and convolution output curves overlap at this plot scale.

A Hand-Programmed Read/Write Toy

A single state coordinate makes the effect of retention visible. Program a write at one position and multiply the state by a chosen retention factor at the other positions.

The scalar recurrence is xk=rkxk−1+wkx_k = r_k x_{k-1} + w_k, where rkr_k controls how much of the old state survives and wkw_k is the additive write. We program two actions.

  • Overwrite. At the write position, set rk=0r_k=0 and wk=vw_k=v so the new state equals vv.
  • Retain. At every other position, set wk=0w_k=0 and multiply the state by the chosen retention factor rkr_k.
PythonIn [17]
CollapseExpand
def run_toy(retain, write_at=8, tokens=64, value=1.0):
    """Overwrite a scalar state once and apply retention at all other positions."""
    x = 0.0
    trace = np.empty(tokens)
    for k in range(tokens):
        if k == write_at:
            x = value  # programmed overwrite
        else:
            x = retain * x  # zero write, retain part of the state
        trace[k] = x
    return trace


positions = np.arange(64)
retain_values = [1.0, 0.99, 0.95, 0.90]
traces = {r: run_toy(r) for r in retain_values}
trace_recent = run_toy(0.90, write_at=56)
ConsoleOut [18]
CollapseExpand
 retention    readout at k=63    relative to write
      1.00           1.000000              100.0%
      0.99           0.575355               57.5%
      0.95           0.059539                6.0%
      0.90           0.003043                0.3%

recent write at k=56 with retention 0.90: 0.478297 (47.8% of the written value)

The write at position 8 has 55 updates left before the readout at position 63. The remaining value is r55r^{55} for retention rr. At r=0.99r=0.99 about 58% survives, and at r=0.90r=0.90 about 0.3% survives. A write at position 56 undergoes only seven updates, so 0.9070.90^7 leaves about 48%.

In a learned selective layer, varying the step size changes the corresponding retention factor for that channel. For finite a<0a<0 and finite Δk>0\Delta_k>0, the exact exponential is strictly between zero and one. A small positive step brings it close to one. The toy uses both endpoints: rk=0r_k=0 discards the old state during an overwrite, and rk=1r_k=1 preserves it exactly when the write is zero.

VisualizationOut [19]
CollapseExpand
State traces after writes at positions 8 and 56. The retention-one trace remains level.
Four traces show retention after an overwrite at position 8. The dashed trace places the overwrite at position 56 and uses retention 0.90.

At position 8, each solid curve rises to one. Once written, its state declines geometrically at the selected retention factor, or stays at one for the ideal hold. The dashed curve moves the write to position 56.

Prefill, Decode, and What "Constant Memory" Counts

The complexity discussion so far has been about arithmetic. Practical deployment cares about three separate quantities, and they scale differently.

  • Prefill work. The cost of processing a prompt of length LL in one pass.
  • Decode work. The cost of a single update. The attention row below counts the query at the LLth processed position, with L−1L-1 earlier keys plus its own.
  • Persistent storage. The bytes held per sequence after processing LL positions.

Starting a new step with a cache of LL positions gives L+1L+1 eligible keys once the new key is added. Repeated decode steps can dominate a long completion, depending on the prompt, the completion length, and the implementation. When device memory is the bottleneck, the amount of persistent storage per sequence helps determine how many concurrent sequences fit.

Use a single-sequence calculation with 24 layers, state dimension N=16N=16, and width 1024 on each side. The attention side has 1024 total dimensions for keys and 1024 for values, and matches query and key heads one to one. The state space mixer has 1024 inner channels. These equal widths give a worked comparison of core operations rather than a parameter-matched pair of model configurations.

PythonIn [20]
CollapseExpand
d_model = 1024  # summed head width and SSM inner width in this example
n_state = 16  # SSM state dimension per channel
n_layers = 24  # number of blocks
L = 4096  # processed positions and eligible keys for query L
bytes_per_scalar = 2  # fp16

# Attention products, counting two FLOPs per multiply-add.
attn_prefill_flops = (
    2 * L * (L + 1) * d_model
)  # QK^T and weighted V over causal pairs
attn_decode_flops = 4 * L * d_model  # one query over L keys, including its own

# Per-layer SSM core: update with a precomputed write, then read out the state.
ssm_prefill_flops = 4 * n_state * d_model * L
ssm_decode_flops = 4 * n_state * d_model

# Persistent per-sequence storage
kv_elements = 2 * L * d_model * n_layers  # K and V
ssm_elements = n_state * d_model * n_layers  # one state per channel
conv_elements = 4 * d_model * n_layers  # depthwise conv buffer, width 4

kv_bytes = kv_elements * bytes_per_scalar
ssm_bytes = ssm_elements * bytes_per_scalar
conv_bytes = conv_elements * bytes_per_scalar
ssm_total_bytes = ssm_bytes + conv_bytes

expanded_state_bytes = (
    1 * 2048 * 8192 * 16 * 4
)  # batch, channels, length, state, fp32
ConsoleOut [21]
CollapseExpand
configuration: d=1024, N=16, layers=24, L=4096

quantity                                                attention             SSM
prefill arithmetic (FLOPs per layer)               34,368,126,976     268,435,456
decode arithmetic at L (FLOPs per layer)               16,777,216          65,536
persistent storage (bytes per sequence)               402,653,184         983,040

ratio, prefill arithmetic: 128.0x
ratio, decode arithmetic:  256.0x
ratio, persistent storage: 409.6x

SSM storage across 24 layers: 786,432 bytes of recurrent state + 196,608 bytes of convolution buffer
Expanded float32 state array at batch 1: 1.00 GiB

The table counts the two main attention products. Computing the query-key dot product and adding a weighted value uses roughly 4d4d FLOPs per allowed pair when a multiply-add is counted as two FLOPs and dd is the sum of key widths over the heads, equal here to the sum of value widths. A length-LL causal prefill has L(L+1)/2L(L+1)/2 pairs. At the LLth processed position the decode count uses LL allowed pairs. For the SSM core, take the write vector wk=Bˉkukw_k=\bar B_k u_k as given. The diagonal update xk=Aˉkxk−1+wkx_k=\bar A_k x_{k-1}+w_k uses 2N2N FLOPs per channel, and the state readout CxkCx_k uses 2N−12N-1, so the proxy rounds to 4N4N. The literal worked-example loop also computes Bˉkuk\bar B_k u_k and adds DukDu_k. Both operations are outside this estimate.

The table reports arithmetic per layer and persistent storage per sequence across all 24 layers. It counts the attention cache after LL positions and includes both the recurrent state and the convolution buffer on the SSM side. Each uses two bytes per element. Model weights, temporary activations, allocator overhead, and cache compression are outside the storage count. For the arithmetic comparison, projections, softmax, discretization, and scan overhead are outside the count. The plots therefore describe the scaling of these selected operations rather than wall-clock inference time.

The arithmetic table above is easier to read as scaling curves. The next two cells reuse the fixed dimensions from that configuration and plot the per-layer work as the prefix length grows.

PythonIn [22]
CollapseExpand
import numpy as np

scale_lengths = np.array([2**k for k in range(6, 19)], dtype=float)
attention_prefill_curve = 2 * scale_lengths * (scale_lengths + 1) * d_model
ssm_prefill_curve = 4 * n_state * d_model * scale_lengths
attention_decode_curve = 4 * scale_lengths * d_model
ssm_decode_curve = np.full_like(scale_lengths, 4 * n_state * d_model)
VisualizationOut [23]
CollapseExpand
Log-log plot of attention and SSM prefill and decode arithmetic versus length.
Per-layer arithmetic for the attention products and SSM core from 64 to 262,144 positions. The length counts prompt positions for prefill and eligible keys for the attention decode query. Attention prefill grows quadratically, attention decode grows linearly, and the SSM core is linear for prefill and flat for decode.

The Mamba-1 implementation has a causal convolution before the state space layer. Its v2.2.4 default buffer length is four entries per inner channel. At the same dtype as the state, the buffer uses 4/N4/N as many bytes as the state, independent of prefix length. Mamba-1 reference block, v2.2.4.

PythonIn [24]
CollapseExpand
prefix_lengths = np.array([2**k for k in range(6, 19)], dtype=float)
kv_storage = 2 * prefix_lengths * d_model * n_layers * bytes_per_scalar
ssm_storage = np.full_like(prefix_lengths, ssm_bytes)
ssm_storage_with_conv = np.full_like(prefix_lengths, ssm_total_bytes)
VisualizationOut [25]
CollapseExpand
Per-sequence KV cache grows with prefix length. Recurrent state stays flat, and including the convolution buffer raises that flat line.
Persistent per-sequence storage between decode steps, as a function of prefix length, for the same width and layer count. The key-value cache grows linearly. The SSM state and its convolution buffer are flat.

For the plotted dimensions, the SSM state and convolution buffer stay constant and the full attention cache grows in proportion to the processed prefix length. At the same per-head key and value widths and dtype, fewer key-value heads lower the cache payload. At the same number of cached elements, fewer bytes per element also lower it.

Limitations and Impact

The state carries the information the model needs later. A state that records a running total can preserve that statistic even when many tokens have passed. A model answering arbitrary queries about exact spans has a harder job. At fixed precision a fixed-size recurrent decoder has finitely many carried configurations. Count every buffer that can distinguish histories, including the convolution history. If more equal-length prefixes are possible than complete carried configurations, two prefixes must reach the same state. After processing the same nonempty continuation from that state with identical auxiliary inputs, the decoder computes the same next-token distribution for both histories. The two histories can still call for different answers. The practical question is whether collisions affect the kinds of recall your task needs.

Gu and Dao reported empirical comparisons in specific training and evaluation settings. In their Table 1, Mamba-2.8B averaged 63.3 across six zero-shot accuracy benchmarks, versus 59.1 for Pythia-2.8B and 63.0 for GPT-J-6B. The larger GPT-J comparison used a different tokenizer, and the mean hides which benchmarks favored which model. Treat this as evidence about those evaluations at those scales. To test recall separately, score exact value retrieval on held-out sequences of key-value pairs. Vary the distance from the target pair to the query, and vary the number, positions, and similarity of distractors. Mamba, section 4.2 and Table 1.

Math also leaves an implementation question. The exponentials, products and sums in a long recurrence can round differently across precisions and arithmetic order. Very small retained contributions can underflow, and a stored state in float32 uses twice as many bytes as the same state in float16. Separately, memory traffic and hardware support affect whether a scan is fast. Measure latency and peak memory for the exact workload, including how serving requests are batched and how long the prompts and completions are.

Summary

  • A recurrent state space layer stores the state from its last update. In a fixed-width, purely recurrent layer, storage and per-step recurrent work stay constant as the processed prefix grows.
  • Exact zero-order hold gives the transition eΔAe^{\Delta A} and write map Bˉ=(∫0ΔeτA dτ)B\bar B=(\int_0^\Delta e^{\tau A}\,d\tau)B. The integral handles singular AA. For a negative scalar rate, shorter steps preserve more of the previous state.
  • A zero-initial-state LTI recurrence can evaluate the same outputs by causal convolution with taps CAˉjBˉC\bar A^j\bar B, plus the direct path at lag zero. Constructing the taps and applying them are distinct operations. S4's structured state matrix makes construction more efficient.
  • Mamba-1 conditions the step size, write vector, and read vector on the input. Once those quantities are computed, the state updates can be composed as affine maps and evaluated by an ordered parallel scan.
  • Mamba-2's scalar transition within each head yields a mixing matrix built from unnormalized dot products and a causal decay mask. SSD exploits low rank in blocks across chunk boundaries. It uses matrix multiplication inside chunks and propagates the recurrent state between them.

The next chapter looks at using attention and state space layers in one architecture and at what changes when you move either type of layer.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about state space models for language.

State Space Models for Language

Question 1 of 80 of 8 completed
During autoregressive decoding, what is the main memory difference between a full causal attention layer and a fixed-width recurrent state space layer?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 6

Comparing Architecture Families Fairly

Learn how to compare Transformer, SSM, and hybrid architectures fairly with matched compute, bits per byte, roofline cost models, and clustered uncertainty.

64 min read
Language AI Handbook · Vol. 6

Blockwise and Semi-Autoregressive Generation

Explore semi-autoregressive block generation, blockwise parallel decoding, and exact speculative sampling with acceptance and residual repair rules.

42 min read
Language AI Handbook · Vol. 6

Token-Free and Byte-Level Language Models

Explore token-free byte-level language models: UTF-8 encoding, byte factorization, patching architectures like ByT5, CANINE, MEGABYTE, BLT, and fair evaluation.

54 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026statespace, author = {Michael Brenndoerfer}, title = {State Space Models for Language}, year = {2026}, url = {https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-11-25} }
APAAcademic
Michael Brenndoerfer (2026). State Space Models for Language. Retrieved from https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state
MLAAcademic
Michael Brenndoerfer. "State Space Models for Language." 2026. Web. November 25, 2026. <https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state>.
CHICAGOAcademic
Michael Brenndoerfer. "State Space Models for Language." Accessed November 25, 2026. https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state.
HARVARDAcademic
Michael Brenndoerfer (2026) 'State Space Models for Language'. Available at: https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state (Accessed: November 25, 2026).
SimpleBasic
Michael Brenndoerfer (2026). State Space Models for Language. https://mbrenndoerfer.com/writing/state-space-models-language-fixed-recurrent-state
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy