Simple Algorithm
Deep Learning · Representation · 24 min

State Space Models

Linear recurrences that train in parallel: S4, Mamba and their kin.

A recurrent network updates its state through a nonlinearity, so training must walk the sequence one step at a time. A transformer trains in parallel but drags along a cache that grows with every token. State space models take a third road: a linear recurrence, derived from a continuous-time system, that unrolls into one long convolution for parallel training and runs as a constant-memory RNN for generation. Here you derive the discretization, the kernel and the conditions for long memory, and see why the newest models let the input steer the recurrence.

What you’ll learn

  • Discretize the linear system h′=Ah+Bx\mathbf h'=A\mathbf h+Bx, y=Chy=C\mathbf h by zero-order hold, deriving Aˉ=eΔA\bar A=e^{\Delta A} and Bˉ=(ΔA)−1(eΔA−I)ΔB\bar B=(\Delta A)^{-1}(e^{\Delta A}-I)\Delta B, and compare it with the bilinear rule.
  • Show that the same layer is a recurrence and a convolution with kernel Kk=CAˉkBˉK_k=C\bar A^k\bar B, and compare their costs for training (O(Tlog⁡T)\order{T\log T} with the FFT) and for generation (O(N)\order{N} per token).
  • Relate memory length and oscillation to the eigenvalues of Aˉ\bar A, and explain how S4 and its diagonal successors made long memory trainable.
  • Explain why input-dependent (selective) parameters break the convolution, how a parallel scan keeps training parallel, and what Mamba gains from it.

A linear system in continuous time

Start from the workhorse of control theory, a linear state space model. A scalar input signal x(τ)x(\tau), indexed by continuous time τ\tau, drives an NN-dimensional state h(τ)\mathbf h(\tau), and a linear readout gives the output:

h′(τ)=A h(τ)+B x(τ),y(τ)=C h(τ)+D x(τ),A∈RN×N, B∈RN×1, C∈R1×N\mathbf h'(\tau)=A\,\mathbf h(\tau)+B\,x(\tau),\qquad y(\tau)=C\,\mathbf h(\tau)+D\,x(\tau),\qquad A\in\R^{N\times N},\ B\in\R^{N\times1},\ C\in\R^{1\times N}
One such single-input, single-output system per channel: a layer of width dd runs dd of them side by side, each with its own state of size NN, and the network mixes channels with linear layers and nonlinearities between SSM layers. The skip term DxDx is a per-channel scalar; take D=0D=0 below.

A sequence of tokens or audio samples x1,x2,…x_1,x_2,\dots is treated as samples of such a signal, taken every Δ\Delta units of time. The step size Δ\Delta is learned, and it separates two things: AA sets what the system remembers in continuous time, and Δ\Delta sets how fast it reads. Turning the differential equation into a recurrence is discretization.

DerivationZero-order hold, one mode at a time
  1. h(τ+Δ)=eaΔ h(τ)+∫0Δea(Δ−s) b x(τ+s) dsh(\tau+\Delta)=e^{a\Delta}\,h(\tau)+\int_0^{\Delta}e^{a(\Delta-s)}\,b\,x(\tau+s)\,ds

    Take a single mode, h′=ah+bxh'=ah+bx with a∈Ca\in\mathbb C and Re⁡a<0\operatorname{Re}a<0 (a diagonalizable AA is NN of these). Over one step, from τ\tau to τ+Δ\tau+\Delta, the variation-of-constants formula solves it exactly:

  2. ∫0Δea(Δ−s) ds=eaΔ−1a⟹ht=eaΔ⏟aˉ ht−1+eaΔ−1a b⏟bˉ xt\int_0^{\Delta}e^{a(\Delta-s)}\,ds=\frac{e^{a\Delta}-1}{a}\quad\Longrightarrow\quad h_t=\underbrace{e^{a\Delta}}_{\bar a}\,h_{t-1}+\underbrace{\frac{e^{a\Delta}-1}{a}\,b}_{\bar b}\,x_t

    The zero-order hold assumes the input stays constant during the step, x(τ+s)=xtx(\tau+s)=x_t. The integral is then elementary:

  3. Aˉ=eΔA,Bˉ=(ΔA)−1(eΔA−I) ΔB\bar A=e^{\Delta A},\qquad\bar B=(\Delta A)^{-1}\big(e^{\Delta A}-I\big)\,\Delta B

    The same computation with matrices gives the general rule, exact whenever the input is piecewise constant:

  4. Aˉbil=(I−Δ2A)−1(I+Δ2A),Bˉbil=(I−Δ2A)−1ΔB\bar A_{\text{bil}}=\big(I-\tfrac{\Delta}{2}A\big)^{-1}\big(I+\tfrac{\Delta}{2}A\big),\qquad\bar B_{\text{bil}}=\big(I-\tfrac{\Delta}{2}A\big)^{-1}\Delta B

    The bilinear (Tustin) rule approximates the integral instead, and maps the stable half-plane Re⁡a<0\operatorname{Re}a<0 exactly onto the unit disk; S4 used it, and most later models use zero-order hold. To first order in Δ\Delta both reduce to Euler's step, Aˉ≈I+ΔA\bar A\approx I+\Delta A and Bˉ≈ΔB\bar B\approx\Delta B:

Check your understanding

A mode has a=−2a=-2 and the step size is Δ=0.1\Delta=0.1. What does zero-order hold give for aˉ\bar a?

  1. 0.80.8
  2. e−0.2≈0.819e^{-0.2}\approx0.819
  3. 0.20.2
  4. e0.2≈1.221e^{0.2}\approx1.221
Show the answer

B. e−0.2≈0.819e^{-0.2}\approx0.819

aˉ=eaΔ=e−0.2≈0.819\bar a=e^{a\Delta}=e^{-0.2}\approx0.819, and bˉ=(e−0.2−1)/(−2)⋅b≈0.091 b\bar b=(e^{-0.2}-1)/(-2)\cdot b\approx0.091\,b. The state keeps about 82% of itself per step: a memory of 1/(∣a∣Δ)=51/(|a|\Delta)=5 steps to fall by a factor ee.

One layer, two algorithms

Unroll the recurrence from h0=0\mathbf h_0=\mathbf 0. Each output is a weighted sum of past inputs with weights that do not depend on tt, which is a causal convolution:

ht=Aˉht−1+Bˉxt,  yt=Cht⟺yt=∑k=0t−1Kk xt−k,K=(CBˉ, CAˉBˉ, CAˉ2Bˉ, …, CAˉT−1Bˉ)\mathbf h_t=\bar A\mathbf h_{t-1}+\bar Bx_t,\ \ y_t=C\mathbf h_t\qquad\Longleftrightarrow\qquad y_t=\sum_{k=0}^{t-1}K_k\,x_{t-k},\qquad K=\big(C\bar B,\ C\bar A\bar B,\ C\bar A^2\bar B,\ \dots,\ C\bar A^{T-1}\bar B\big)
The kernel KK is as long as the sequence: a global convolution, whose receptive field is the whole past. This holds because Aˉ\bar A, Bˉ\bar B and CC are the same at every step; such a system is linear time-invariant (LTI).
ComputationTraining on TT stepsOne more token at generationMemory while generating
Recurrence (diagonal Aˉ\bar A)O(TN)\order{TN}, but TT sequential stepsO(N)\order{N}the state: NN numbers per channel
Convolutionkernel in O(TN)\order{TN}, then FFT in O(Tlog⁡T)\order{T\log T}, fully parallel(needs the whole input)—
Attention, for comparisonO(T2d)\order{T^2d}O(td)\order{td} at position ttKV cache: grows with tt
Per channel for the SSM rows. The duality is why state space models entered deep learning: an LTI SSM layer trains like a convolutional network and generates like a recurrent one.
python
import torch

def ssm_kernel(lam, B, C, dt, T):
    """Diagonal SSM with complex modes lam, B, C of shape (N,): real kernel K_k for k < T."""
    Bbar = (torch.exp(dt * lam) - 1) / lam * B                # zero-order hold
    k = torch.arange(T)
    powers = torch.exp(dt * lam[:, None] * k)                  # Abar^k = exp(k dt lam), (N, T)
    return (C[:, None] * powers * Bbar[:, None]).sum(0).real   # (T,)

def ssm_conv(x, K):                                            # training: parallel, O(T log T)
    T = x.shape[-1]
    n = 2 * T                                                  # zero-pad: linear, not circular
    return torch.fft.irfft(torch.fft.rfft(x, n) * torch.fft.rfft(K, n), n)[..., :T]

def ssm_step(h, x_t, lam, B, C, dt):                           # generation: O(N) per token
    Abar = torch.exp(dt * lam)
    h = Abar * h + (Abar - 1) / lam * B * x_t
    return h, (C * h).sum().real

Taking the real part of each complex mode's output, as the widget below does, makes each mode stand for a conjugate pair. Starting from h = torch.zeros_like(lam), looping ssm_step over a sequence gives the same outputs as ssm_conv(x, ssm_kernel(...)), up to rounding.

Memory lives in the eigenvalues

Diagonalize A=VΛV−1A=V\Lambda V^{-1}. In the eigenbasis every mode evolves on its own, and the kernel becomes a sum of NN geometric sequences, one per eigenvalue λn\lambda_n of AA:

Kk=∑n=1Nc~n b~n ekΔλn,∣ekΔλn∣=e−kΔ∣Re⁡λn∣,memory≈1Δ ∣Re⁡λn∣ stepsK_k=\sum_{n=1}^{N}\tilde c_n\,\tilde b_n\,e^{k\Delta\lambda_n},\qquad\big|e^{k\Delta\lambda_n}\big|=e^{-k\Delta|\operatorname{Re}\lambda_n|},\qquad\text{memory}\approx\frac{1}{\Delta\,|\operatorname{Re}\lambda_n|}\ \text{steps}
b~=V−1Bˉ\tilde{\mathbf b}=V^{-1}\bar B and c~=CV\tilde{\mathbf c}=CV. Stability needs Re⁡λn<0\operatorname{Re}\lambda_n<0, so that the discrete eigenvalue eΔλne^{\Delta\lambda_n} lies inside the unit disk. Its modulus sets how long the mode remembers; its angle, ΔIm⁡λn\Delta\operatorname{Im}\lambda_n per step, makes the kernel oscillate.

Long memory therefore needs discrete eigenvalues just inside the unit circle: a mode that should keep 10% of its signal for 1,000 steps needs ∣eΔλ∣≥0.11/1000≈0.9977|e^{\Delta\lambda}|\ge0.1^{1/1000}\approx0.9977. That is the same condition that governs vanishing gradients in an RNN (Recurrent Neural Networks), but in a linear system it is exact, and it can be set directly through Re⁡λ\operatorname{Re}\lambda and Δ\Delta.

Predict before you look

With τ=1\tau=1, Δ=0.05\Delta=0.05 and real eigenvalues, the kernel is proportional to e−kΔ/τe^{-k\Delta/\tau}. At which step kk does it first fall below 10% of its value at k=0k=0?

Show the answer

47

e−0.05k<0.1e^{-0.05k}<0.1 when k>20ln⁡10≈46.05k>20\ln10\approx46.05, so from step 47 on, as in the widget. The memory in steps is τ/Δ=20\tau/\Delta=20; multiplying by ln⁡10≈2.3\ln10\approx2.3 converts "fall by ee" into "fall to 10%".

Making long memory trainable: S4 and its descendants

Knowing that long memory needs eigenvalues near the unit circle is not the same as training a model that has them. A randomly initialized AA gives poorly spread time scales, and computing the kernel CAˉkBˉC\bar A^k\bar B for a dense AA costs O(N2T)\order{N^2T}. The Long Range Arena (Tay et al., 2021) made the problem concrete: six tasks with sequences of 1,000 to 16,000 steps, on which efficient transformers struggled. On its hardest task, Path-X, the input is an image of 128×128=16,384128\times128=16{,}384 pixels fed one pixel at a time, and the model must say whether two marked points are joined by a path. Every model in the original benchmark stayed at chance, 50%.

S4 (Gu, Goel & Ré, 2022) fixed both problems. It initializes AA with a HiPPO matrix, derived so that the state holds the coefficients of the best polynomial approximation of the entire input history, which spreads the time scales from very short to very long. And it writes AA as a normal matrix plus a low-rank correction, which lets the kernel be computed stably in nearly linear time. S4 was the first model to solve Path-X, at 88% accuracy. Simpler successors followed quickly:

ModelState matrixComputed asWhat it showed
S4 (2022)HiPPO initialization; normal plus low rankconvolution, kernel through a Cauchy kernellong memory that trains; first to solve Path-X
DSS, S4D (2022)diagonal complex, e.g. λn=−12+iπn\lambda_n=-\tfrac12+i\pi n (S4D-Lin)convolution, kernel through a Vandermonde producta diagonal AA suffices with the right initialization
S5 (2023)diagonal; one multi-input, multi-output system per layerparallel scanthe recurrence itself can be trained in parallel
LRU (2023)diagonal complex, λ=e−ν+iθ\lambda=e^{-\nu+i\theta}, initialized on a ring just inside the unit circleparallel scana well-initialized linear RNN matches S4 on these benchmarks
Mamba (2023)diagonal real; Δ\Delta, BB, CC depend on the inputhardware-aware selective scancontent-dependent memory (next step)
Gupta, Gu & Berant (2022) for DSS; Gu, Gupta, Goel & Ré (2022) for S4D; Smith, Warrington & Linderman (2023) for S5; Orvieto et al. (2023) for the linear recurrent unit (LRU). Structured State Spaces: HiPPO & S4 derives the HiPPO matrix and the fast kernel.

Selectivity: letting the input steer

An LTI layer applies the same kernel to every input. It cannot decide from content what to keep: a kernel long enough to carry a word across a gap of filler also sums up the filler. Language is full of such cases, where whether a token matters depends on what it is, not where it is. Gu and Dao (2023) made the recurrence depend on the input.

DerivationNo kernel, but still parallel
  1. (Aˉ2,b2)∘(Aˉ1,b1)=(Aˉ2Aˉ1, Aˉ2b1+b2)(\bar A_2,\mathbf b_2)\circ(\bar A_1,\mathbf b_1)=\big(\bar A_2\bar A_1,\ \bar A_2\mathbf b_1+\mathbf b_2\big)

    With Aˉt\bar A_t and Bˉt\bar B_t changing every step there is no single kernel and no FFT. But each step is still an affine map of the state, h↦Aˉth+bt\mathbf h\mapsto\bar A_t\mathbf h+\mathbf b_t with bt=Bˉtxt\mathbf b_t=\bar B_tx_t, and composing two such maps gives another:

  2. ht=((Aˉt,bt)∘⋯∘(Aˉ1,b1))(h0)\mathbf h_t=\big((\bar A_t,\mathbf b_t)\circ\dots\circ(\bar A_1,\mathbf b_1)\big)(\mathbf h_0)

    Composition of functions is associative, so all prefix compositions, and with them every state ht\mathbf h_t, come out of a parallel scan in O(log⁡T)\order{\log T} parallel steps with O(T)\order{T} total work (Blelloch, 1990). With diagonal Aˉt\bar A_t each composition costs O(N)\order{N} per channel.

  3. work O(TdN),memory traffic O(Td) instead of O(TdN)\text{work }\order{TdN},\qquad\text{memory traffic }\order{Td}\ \text{instead of}\ \order{TdN}

    The obstacle left is memory traffic: the expanded states have NN times as many numbers as the input. Mamba's kernel loads Δ\Delta, AA, BB, CC into fast on-chip SRAM, discretizes and scans there, writes only the outputs back to HBM, and recomputes the states in the backward pass instead of storing them. Training is linear in TT, and generation keeps a state of fixed size.

In the paper's language-modeling experiments, Mamba models matched or beat transformers of similar size, and a 3-billion-parameter Mamba matched transformers about twice its size; as of the mid-2020s, how far such results hold at much larger scales, and on tasks that need precise recall from a long context, is examined in the Emergence lessons.

Key takeaways

  • An SSM layer discretizes h′=Ah+Bx\mathbf h'=A\mathbf h+Bx with a learned step Δ\Delta; zero-order hold gives Aˉ=eΔA\bar A=e^{\Delta A} and Bˉ=(ΔA)−1(eΔA−I)ΔB\bar B=(\Delta A)^{-1}(e^{\Delta A}-I)\Delta B.
  • With fixed parameters the layer is both a recurrence (O(N)\order{N} per generated token, constant memory) and a global convolution with kernel Kk=CAˉkBˉK_k=C\bar A^k\bar B (parallel training with the FFT in O(Tlog⁡T)\order{T\log T}).
  • Memory is set by the moduli of the discrete eigenvalues eΔλne^{\Delta\lambda_n}, about 1/(Δ∣Re⁡λn∣)1/(\Delta|\operatorname{Re}\lambda_n|) steps; their angles make the kernel oscillate. HiPPO initialization made long memory trainable (S4), and diagonal AA turned out to suffice.
  • Selective SSMs make Δ\Delta, BB and CC depend on the input, so the model can reset or hold its state by content; this breaks the convolution, and a parallel scan with a hardware-aware kernel keeps training parallel and linear in TT.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can a selective SSM not be trained with an FFT convolution, as S4 is?

  1. Its state is complex-valued
  2. Its parameters change from token to token, so there is no single kernel shared by all positions
  3. Its kernel is too long to fit in memory
  4. The FFT cannot be differentiated
Show the answer

B. Its parameters change from token to token, so there is no single kernel shared by all positions

The convolution form needs a time-invariant system: the weight on xt−kx_{t-k} must be the same KkK_k for every tt. With Δt\Delta_t, BtB_t and CtC_t depending on the input, the weight on xt−kx_{t-k} is CtAˉt⋯Aˉt−k+1Bˉt−kC_t\bar A_t\cdots\bar A_{t-k+1}\bar B_{t-k}, different at every tt. A parallel scan computes the time-varying recurrence instead.

Question 2

A model generates token t+1t+1 after reading tt tokens. How do an SSM layer and an attention layer compare in the memory they must keep?

  1. Both keep all tt previous inputs
  2. The SSM keeps a cache that grows with tt; attention keeps a fixed-size state
  3. Neither keeps anything: both recompute from the input
  4. The SSM keeps a state whose size does not depend on tt; attention keeps keys and values for all tt positions
Show the answer

D. The SSM keeps a state whose size does not depend on tt; attention keeps keys and values for all tt positions

The recurrence carries everything forward in ht\mathbf h_t, NN numbers per channel, so each new token costs O(N)\order{N} per channel whatever tt is. Attention's KV cache grows linearly with tt, and so does the cost of each new query. The fixed state is also the SSM's limitation: what it has not stored, it cannot look up.

Question 3

Four candidate discrete eigenvalues for one mode of Aˉ\bar A. Which gives the longest memory while staying stable?

  1. 0.50.5
  2. 0.90.9
  3. 0.99 eiπ/40.99\,e^{i\pi/4}
  4. 1.011.01
Show the answer

C. 0.99 eiπ/40.99\,e^{i\pi/4}

Memory is set by the modulus: ∣0.99 eiπ/4∣=0.99|0.99\,e^{i\pi/4}|=0.99 is the closest to one from inside the unit disk, so the mode decays slowest (by a factor ee in about 100 steps); its angle only makes the kernel oscillate.

Question 4

You halve the step size Δ\Delta of an LTI SSM and keep AA fixed. What happens to its memory measured in steps?

  1. It doubles
  2. It halves
  3. It is unchanged, since AA is unchanged
  4. It squares
Show the answer

A. It doubles

Each mode decays as e−kΔ∣Re⁡λ∣e^{-k\Delta|\operatorname{Re}\lambda|}, so the number of steps needed for the same decay is proportional to 1/Δ1/\Delta: halving Δ\Delta doubles it. In the widget the 10% length goes from 47 to 93 steps. The memory in continuous time, 1/∣Re⁡λ∣1/|\operatorname{Re}\lambda|, is what stays fixed.

Go deeper

Further reading

  • A. Gu, K. Goel & C. Ré, "Efficiently modeling long sequences with structured state spaces," ICLR (2022).
  • A. Gu & T. Dao, "Mamba: Linear-time sequence modeling with selective state spaces," arXiv:2312.00752 (2023); Conference on Language Modeling (COLM) (2024).
  • Y. Tay, M. Dehghani, S. Abnar, Y. Shen, D. Bahri, P. Pham, J. Rao, L. Yang, S. Ruder & D. Metzler, "Long Range Arena: A benchmark for efficient transformers," ICLR (2021).
  • A. Orvieto, S. L. Smith, A. Gu, A. Fernando, C. Gulcehre, R. Pascanu & S. De, "Resurrecting recurrent neural networks for long sequences," ICML (2023).