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 , by zero-order hold, deriving and , and compare it with the bilinear rule.
- Show that the same layer is a recurrence and a convolution with kernel , and compare their costs for training ( with the FFT) and for generation ( per token).
- Relate memory length and oscillation to the eigenvalues of , 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 , indexed by continuous time , drives an -dimensional state , and a linear readout gives the output:
A sequence of tokens or audio samples is treated as samples of such a signal, taken every units of time. The step size is learned, and it separates two things: sets what the system remembers in continuous time, and sets how fast it reads. Turning the differential equation into a recurrence is discretization.
Take a single mode, with and (a diagonalizable is of these). Over one step, from to , the variation-of-constants formula solves it exactly:
The zero-order hold assumes the input stays constant during the step, . The integral is then elementary:
The same computation with matrices gives the general rule, exact whenever the input is piecewise constant:
The bilinear (Tustin) rule approximates the integral instead, and maps the stable half-plane exactly onto the unit disk; S4 used it, and most later models use zero-order hold. To first order in both reduce to Euler's step, and :
A mode has and the step size is . What does zero-order hold give for ?
Show the answer
B.
, and . The state keeps about 82% of itself per step: a memory of steps to fall by a factor .
One layer, two algorithms
Unroll the recurrence from . Each output is a weighted sum of past inputs with weights that do not depend on , which is a causal convolution:
| Computation | Training on steps | One more token at generation | Memory while generating |
|---|---|---|---|
| Recurrence (diagonal ) | , but sequential steps | the state: numbers per channel | |
| Convolution | kernel in , then FFT in , fully parallel | (needs the whole input) | — |
| Attention, for comparison | at position | KV cache: grows with |
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().realTaking 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 . In the eigenbasis every mode evolves on its own, and the kernel becomes a sum of geometric sequences, one per eigenvalue of :
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 . 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 and .
With , and real eigenvalues, the kernel is proportional to . At which step does it first fall below 10% of its value at ?
Show the answer
47
when , so from step 47 on, as in the widget. The memory in steps is ; multiplying by converts "fall by " 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 gives poorly spread time scales, and computing the kernel for a dense costs . 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 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 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 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:
| Model | State matrix | Computed as | What it showed |
|---|---|---|---|
| S4 (2022) | HiPPO initialization; normal plus low rank | convolution, kernel through a Cauchy kernel | long memory that trains; first to solve Path-X |
| DSS, S4D (2022) | diagonal complex, e.g. (S4D-Lin) | convolution, kernel through a Vandermonde product | a diagonal suffices with the right initialization |
| S5 (2023) | diagonal; one multi-input, multi-output system per layer | parallel scan | the recurrence itself can be trained in parallel |
| LRU (2023) | diagonal complex, , initialized on a ring just inside the unit circle | parallel scan | a well-initialized linear RNN matches S4 on these benchmarks |
| Mamba (2023) | diagonal real; , , depend on the input | hardware-aware selective scan | content-dependent memory (next step) |
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.
With and changing every step there is no single kernel and no FFT. But each step is still an affine map of the state, with , and composing two such maps gives another:
Composition of functions is associative, so all prefix compositions, and with them every state , come out of a parallel scan in parallel steps with total work (Blelloch, 1990). With diagonal each composition costs per channel.
The obstacle left is memory traffic: the expanded states have times as many numbers as the input. Mamba's kernel loads , , , 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 , 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 with a learned step ; zero-order hold gives and .
- With fixed parameters the layer is both a recurrence ( per generated token, constant memory) and a global convolution with kernel (parallel training with the FFT in ).
- Memory is set by the moduli of the discrete eigenvalues , about steps; their angles make the kernel oscillate. HiPPO initialization made long memory trainable (S4), and diagonal turned out to suffice.
- Selective SSMs make , and 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 .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why can a selective SSM not be trained with an FFT convolution, as S4 is?
- Its state is complex-valued
- Its parameters change from token to token, so there is no single kernel shared by all positions
- Its kernel is too long to fit in memory
- 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 must be the same for every . With , and depending on the input, the weight on is , different at every . A parallel scan computes the time-varying recurrence instead.
A model generates token after reading tokens. How do an SSM layer and an attention layer compare in the memory they must keep?
- Both keep all previous inputs
- The SSM keeps a cache that grows with ; attention keeps a fixed-size state
- Neither keeps anything: both recompute from the input
- The SSM keeps a state whose size does not depend on ; attention keeps keys and values for all positions
Show the answer
D. The SSM keeps a state whose size does not depend on ; attention keeps keys and values for all positions
The recurrence carries everything forward in , numbers per channel, so each new token costs per channel whatever is. Attention's KV cache grows linearly with , 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.
Four candidate discrete eigenvalues for one mode of . Which gives the longest memory while staying stable?
Show the answer
C.
Memory is set by the modulus: is the closest to one from inside the unit disk, so the mode decays slowest (by a factor in about 100 steps); its angle only makes the kernel oscillate.
You halve the step size of an LTI SSM and keep fixed. What happens to its memory measured in steps?
- It doubles
- It halves
- It is unchanged, since is unchanged
- It squares
Show the answer
A. It doubles
Each mode decays as , so the number of steps needed for the same decay is proportional to : halving doubles it. In the widget the 10% length goes from 47 to 93 steps. The memory in continuous time, , is what stays fixed.
Go deeper
- Structured State Spaces: HiPPO & S4 · Continuous-time memory, discretization and long convolution kernels.
- Selective State Spaces: Mamba · Input-dependent dynamics, parallel scans and hardware-aware kernels.
- Hybrid Models & the Limits of Fixed-Size Memory · Why recall needs attention, and architectures that mix it with recurrence.
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).