Architectures/State-Space Models and Mamba

Lesson 6.92,749 words

State-Space Models and Mamba

A state-space model carries a continuous linear hidden state through a sequence, and that linearity buys two equivalent algorithms from one set of weights: a recurrence that runs in linear time with constant memory, and a global convolution that trains in parallel. Long-range memory comes from how the transition matrix is initialized (HiPPO) and parameterized (S4's diagonal-plus-low-rank form).

╌╌╌╌

A recurrent network runs in time but trains through a product of Jacobians that vanishes or explodes, so long-range signal is hard to learn. The Transformer learns any-distance dependencies directly through attention, but pays in time and memory. A state-space model (SSM) targets the corner neither reaches: cost and stable long-range memory. It does so by making the recurrence linear in the hidden state, a restriction that turns out to expose two equivalent computations from one set of weights.1

ModelTrain costInference cost / stepLong-range memory
RNN / LSTM sequential statehard (vanishing gradient)
Transformer parallel KV-cachedirect (attention)
State-space model or parallel stateby construction (HiPPO)

The continuous linear state-space

The starting point is not a neural network but a linear dynamical system from control theory: a hidden state driven by a scalar input signal , evolving by a linear ordinary differential equation and read out linearly.

The term is a plain residual, so we drop it from the derivations and restore it at the end. What matters is how the state integrates the past of and how reads it out.

The continuous SSM as a block diagram. The input drives an integrator through ; state feeds back through and is read out through , with as a direct skip.

Solving the linear ODE gives an explicit integral: the state at time is a convolution of the input's past against the matrix exponential of .

The output is a convolution against the kernel . Every efficient algorithm in this lesson exploits this fact.

Discretization

Sequences are sampled, not continuous, so we discretize the ODE at a step size . The standard choice is the zero-order hold (ZOH): assume the input is constant across each interval and integrate the dynamics exactly over that interval. This converts into discrete matrices .

The derivation is the continuous solution applied over one step. Integrate from to with pulled out of the integral:

which is exactly and , matching the ZOH formula after grouping the . The step size is a learned parameter: it sets the timescale at which the continuous system is sampled.

For example, take a scalar state () with , , and step size . Then

The recurrence is a leaky integrator: each step keeps of the old state and admits of the new input. Halving the step to gives , retaining more per step so the state persists longer, exactly the long-memory regime the remark describes. Notice : the ZOH split conserves mass, which is why the discrete system inherits the continuous system's stability.

In an -dimensional state the same formulas apply with matrices. is the matrix exponential, and is ; when is diagonal (the S4D case below) the exponential is elementwise, , so discretization costs rather than the of a dense matrix exponential.

With the discrete matrices fixed, the SSM is now an ordinary linear recurrence, identical in shape to an RNN cell but with no nonlinearity inside the state update. That linearity is what we exploit next.

Algorithm:SsmRecurrent(u1:n,A,B,C)\textsc{SsmRecurrent}(u_{1:n}, \overline{A}, \overline{B}, C) — linear-time, constant-state inference
  1. 1
    x00x_0 \gets 0
    hidden state, O(N)O(N) memory
  2. 2
    for k1k \gets 1 to nn do
  3. 3
    xkAxk1+Bukx_k \gets \overline{A}\,x_{k-1} + \overline{B}\,u_k
    one matrix-vector update
  4. 4
    ykCxky_k \gets C\,x_k
    read out the output
  5. 5
    return y1:ny_{1:n}

Two views of one model

Unrolling the recurrence from writes each output as a weighted sum of past inputs. Expand step by step:

so reading out gives a convolution of the input against a fixed kernel whose taps are .

Continuing the scalar example (, ) with , the kernel taps are :

a decaying exponential filter. Both algorithms must give the same . Feed the impulse : the recurrence gives , then , then , so reproduces tap for tap. The kernel is literally the SSM's impulse response, and convolving any input against it is the parallel restatement of running the recurrence, taps computed once and reused for every position.

The same weights describe two algorithms, and either can be used as the task requires. Training has the whole sequence in hand, so it materializes the kernel once and convolves in parallel; autoregressive inference has tokens arriving one at a time, so it steps the recurrence and keeps only the state.

One SSM, two equivalent algorithms. The recurrence (left) is sequential, state; the convolution (right) is parallel over the length, both computed from .
PropertyRecurrent viewConvolutional view
Update
Parallelismsequential in parallel over the sequence
Memory state kernel + FFT buffers
Best forautoregressive generationtraining, full-sequence encoding
Cost via FFT

The convolution is global: has one tap per position, so the kernel is as long as the sequence. Computing it naively costs a matrix power per tap, and convolving a length- kernel by FFT costs . The open problem the early SSM work solved was making that kernel both cheap to compute and good at remembering, which is entirely a question about .

Dimensions of a deep SSM layer

The definition above is a single-input-single-output (SISO) system: it maps one scalar channel to one scalar output. A real layer processes a batch of sequences with many channels, so the SISO system is replicated. For a batch of sequences, each of length , with feature channels and state size per channel, the tensors are:

TensorShapeRole
input one scalar signal per channel per position
one state matrix per channel (diagonal: )
, input / output maps per channel
one step size per channel (S4); in Mamba
state carried across steps in the recurrence
kernel one length- convolution filter per channel
output same shape as the input

The channels are independent SSMs: channel has its own and never sees the others inside the SSM. Mixing across channels happens outside the recurrence, in the linear projections that sandwich the layer, exactly as attention mixes across positions and a following MLP mixes across channels. The state that inference must carry is numbers, independent of , which is the constant-memory claim made concrete.

Tensor-shape flow through one deep SSM layer, dimensions labeled. Input splits into independent SISO systems, each an -state recurrence, then recombines to .

Long-range memory: HiPPO

A random does not remember. Its kernel taps decay like the eigenvalues of raised to the , so the same geometric forgetting that plagues the vanilla RNN reappears unless is chosen deliberately. The fix is HiPPO (high-order polynomial projection operators): pick so that the hidden state holds the optimal coefficients of a polynomial that approximates the entire input history.

For the (scaled Legendre) HiPPO measure the state matrix has an explicit lower-triangular form, with entries growing with the row index :

which is what lets the high-order coefficients capture fine recent detail while the low-order ones retain the distant past. Initializing this way is the difference between a model that forgets in a dozen steps and one that carries signal across thousands.

Memory decay of the kernel taps with sequence distance. Random (red) forgets geometrically; HiPPO-initialized (blue) holds a near-flat, reconstructable summary of the past.

The remaining obstacle is cost. HiPPO's is dense, so each kernel tap needs a dense matrix power, and materializing becomes , far too expensive. S4 (structured state spaces) makes the kernel cheap by writing as a diagonal-plus-low-rank (DPLR) matrix, , whose powers can be summed with a fast Cauchy-kernel computation rather than naive matrix powers. Two simplifications followed almost immediately: the diagonal SSM (DSS / S4D) drops the low-rank term and keeps only a diagonal , which is far simpler and nearly as accurate, and S5 uses a single multi-input-multi-output system computed with a parallel associative scan instead of a convolution.

ParameterizationForm of Kernel costMemory quality
HiPPO (dense)full optimal, but slow
S4 (DPLR)matches HiPPO
S4D / DSS (diagonal)diagonal nearly matches
S5 (MIMO + scan)diagonal, scanned parallelmatches, simpler

Selective state spaces: Mamba

Every model so far shares one limitation: are fixed once trained, so the convolution kernel is the same for every input. That is what makes the convolution possible, and it is also a ceiling. A linear time-invariant system cannot do content-based reasoning: it cannot decide to ignore a filler word or to specifically remember a name, because its dynamics do not depend on what the input is.

This is the selection mechanism of Mamba. Input-dependent acts as a learned gate: a large resets the state toward the current token (remember this), a small holds the existing state (skip this). Input-dependent decide what gets written into and read out of memory.

QuantityTime-invariant SSM (S4)Selective SSM (Mamba)
fixed, varies via
fixed projected from
fixed scalar per token (a gate)
Convolutionavailable (static kernel)none (kernel changes per step)
Memory behavioruniform over the sequencecontent-selective

This sacrifices the convolution. Once the kernel depends on the input, it is different at every step, so there is no single to FFT. Mamba is back to a sequential recurrence, which on a GPU would be slow. The fix is algorithmic: the linear recurrence is an associative scan, and associative scans parallelize.

Mamba's contribution past the scan itself is to make it hardware-aware: the state is expanded only inside fast GPU SRAM, the scan runs there, and only the outputs are written back to slow HBM, so the large intermediate state never touches main memory.

The selective scan. Per-token projections set (gating); a parallel prefix scan over the recurrence fuses them in depth inside fast on-chip memory.

A full Mamba block wraps the selective scan in a gated structure reminiscent of a gated MLP: the input is projected up, passed through a short causal convolution and the selective SSM on one branch, multiplied by a SiLU-gated branch, and projected back down. Mamba-2 later simplified this by showing that selective SSMs and attention are two views of one operation (a structured masked matrix product), a duality called state-space duality (SSD) that lets the scan be cast as a matrix multiplication and run even faster on tensor-core hardware.

Concretely, a residual input of shape enters. An input projection widens it to with an expansion factor (typically ), splitting into two branches of width . The main branch runs a short depthwise causal convolution (kernel width , mixing a few neighboring positions) and a SiLU nonlinearity, then the selective SSM with channels and state size (often ). The gate branch is a SiLU applied to its half, multiplied into the main branch elementwise. A final projection contracts back to for the residual add.

One Mamba block, dimensions labeled. An input projection expands to and splits it; the main branch runs a causal conv, SiLU, and the selective SSM (state size ), gated by a SiLU branch, then a projection contracts back to .
Algorithm:SelectiveScan(u1:n,A)\textsc{SelectiveScan}(u_{1:n}, A) — Mamba's input-dependent linear recurrence
  1. 1
    for k1k \gets 1 to nn do
    per-token selection (parallel)
  2. 2
    Δksoftplus(WΔuk)\Delta_k \gets \softplus(W_\Delta\, u_k)
    input-dependent step size
  3. 3
    BkWBukB_k \gets W_B\, u_k;   CkWCuk\;C_k \gets W_C\, u_k
    input-dependent in/out maps
  4. 4
    Akexp(ΔkA)\overline{A}_k \gets \exp(\Delta_k A);   BkΔkBk\;\overline{B}_k \gets \Delta_k B_k
    discretize per step
  5. 5
    x1:nParallelScan((Ak,Bkuk))x_{1:n} \gets \textsc{ParallelScan}\parens{(\overline{A}_k,\, \overline{B}_k u_k)}
    O(logn)O(\log n) depth, on-chip
  6. 6
    for k1k \gets 1 to nn do
  7. 7
    ykCkxky_k \gets C_k\, x_k
    selective read-out
  8. 8
    return y1:ny_{1:n}

Cost and quality versus the Transformer

The cost comparison is the main argument for SSMs. Self-attention spends to form an score matrix and caches a growing key-value buffer at inference. An SSM never builds an object: training is work (linear, with an scan depth), and inference carries a fixed-size state independent of how long the context already is.

Inference cost per generated token versus context length. Attention grows linearly with the KV-cache (blue); the SSM stays flat at a constant-size state (black).

Quality is measured on the Long Range Arena (LRA), a benchmark of six tasks built to demand dependencies over thousands of tokens, where Transformers struggle both in accuracy and in the memory cost of long sequences. S4 was the first model to clear all six tasks by a wide margin, including the Path-X task that every prior Transformer variant had failed outright, and selective SSMs carried the gains to language modeling.

ModelMechanismTrainInference stateLRA / long-range
LSTMgated nonlinear recurrence sequentialweak past ~
Transformerfull attention parallel KV-cachequadratic memory wall
S4structured LTI SSMfirst to solve all LRA tasks
Mambaselective SSM + scan parallelmatches Transformers, faster gen

The trade-off: attention keeps a perfect, addressable record of every past token and pays for it with quadratic compute and a context-length-bounded cache; an SSM compresses the past into a fixed state and pays for that with a lossy summary. The selection mechanism makes the compression content-aware, so the loss falls on the tokens weighted as unimportant. For very long sequences, linear time and constant state are decisive.

The deep SSM lineage

Deep state-space models are entirely post-2016, so every result here rests on the recent literature rather than the standard references.

  • The primary line. HiPPO (Gu et al., NeurIPS 2020) derived the transition matrix that lets a fixed-size state hold an optimal polynomial memory of the whole past. S4 (Gu, Goel & Ré, Efficiently Modeling Long Sequences with Structured State Spaces, ICLR 2022) made that kernel cheap with the diagonal-plus-low-rank form and cleared the Long Range Arena. Mamba (Gu & Dao, Linear-Time Sequence Modeling with Selective State Spaces, 2023) added input-dependent parameters and the hardware-aware scan, matching Transformers on language at a fraction of the generation cost. The simplifications — diagonal-only S4D (Gu et al., 2022) and S5 (Smith et al., ICLR 2023) — are what made the models easy to implement.
  • One family, many names. The linear recurrence at the core of an SSM is the same object as linear attention (attention with the softmax removed, which makes it associative and therefore expressible as a recurrence) and as the RWKV and RetNet architectures. Reading all of these as attention without softmax, run as a scan unifies a scattered literature: the price of dropping the softmax is losing the perfect content-addressable lookup, and the selection mechanism in Mamba is one way to buy back the content-awareness the softmax provided.
  • Hybrids in practice. The clean trade — attention's exact recall versus the SSM's linear cost — pushed production models toward interleaving the two: a few full-attention layers for precise copying and lookup, many SSM layers for cheap long-context mixing (Jamba, Lieber et al., 2024). The lesson mirrors ViT and Graph Transformers: the strongest architectures rarely pick one primitive outright.

Takeaways

  • A state-space model carries a continuous linear state, , , and its solution is a convolution of the input against the kernel — every algorithm below follows from this linearity.
  • Zero-order-hold discretization turns the ODE into a linear recurrence with ; the learned step size sets the memory timescale.
  • One set of weights yields two equivalent algorithms: a sequential recurrence ( state, ideal for generation) and a global convolution with (, ideal for training).
  • Long-range memory comes from HiPPO, which initializes so the state holds the optimal polynomial approximation of all the past; a random forgets geometrically. S4 makes that kernel cheap with a diagonal-plus-low-rank (simplified to diagonal in S4D/DSS and S5).
  • Mamba makes input-dependent (selectivity), gaining content-based gating at the cost of the static convolution, and recovers speed with a hardware-aware parallel scan ( depth, on-chip).
  • Against the Transformer, an SSM trains in linear time and generates with a constant-size state rather than a growing KV-cache; on the Long Range Arena S4 and its selective successors win the long-context tasks attention cannot reach.

Footnotes

  1. Goodfellow, Deep Learning, Ch. 10 — Sequence Modeling: the recurrent baseline ( but vanishing-gradient-bound) against which linear state-space models are the modern alternative; deep SSMs postdate the 2016 text.

╌╌ END ╌╌