AI / ML Theory
Chapter 8 · 24 min

8.7 — State Space Models (Mamba) — brief

Goal: Derive the continuous-time linear state space model y(t) = C h(t), h'(t) = A h(t) + B x(t), discretise it to a recurrence, and motivate Mamba's selective SSM where A, B, C are input-dependent. Understand why SSMs achieve O(n) inference (no KV cache) and where they sit relative to attention in 2026.

1. Why this session exists

Every architecture in Chapter 8 so far is a Transformer with one sub-module modified. State space models (SSMs), and their leading instantiation Mamba (Gu & Dao, 2023[3], arXiv:2312.00752), are different: they replace attention entirely with a recurrent sequence operator. Per token they need no KV cache, and per generated token they run in O(d2)O(d^2) time instead of attention's O(Td)O(T d) (with the cached-K, V matmul). For long-context inference this is a substantial wall-clock advantage.

The question is whether SSMs can match attention on quality at scale. As of 2026 the answer is: pure SSMs are competitive but not strictly better than Transformers at the frontier. Hybrid architectures (§8.8) that combine SSM and attention layers are an active research direction and have produced models that match dense Transformers at iso-compute. So SSMs matter both as a standalone variant and, more importantly, as the recurrent half of every hybrid model.

This session is brief on purpose. We define the continuous SSM, discretise it to a recurrence, motivate the selective (input-dependent) version that became Mamba, count its compute and memory, and place it in the 2026 architectural landscape. The Mamba paper is dense; we will skim its hardware-aware "parallel scan" details and refer the reader to the paper for the kernel-level implementation.


2. The continuous-time SSM

Fix state dimension nn and signal dimension (here we treat single-channel input; multi-channel SSMs are a per-channel collection of single-channel models). A linear time-invariant state space model is the continuous-time system

 h′(t)=A h(t)+B x(t),y(t)=C h(t), \boxed{\ \begin{aligned} h'(t) &= A\, h(t) + B\, x(t), \\ y(t) &= C\, h(t), \end{aligned} \ }

with state h(t)∈Rnh(t) \in \mathbb{R}^n, input x(t)∈Rx(t) \in \mathbb{R}, output y(t)∈Ry(t) \in \mathbb{R}, and matrices A∈Rn×n,B∈Rn×1,C∈R1×nA \in \mathbb{R}^{n \times n}, B \in \mathbb{R}^{n \times 1}, C \in \mathbb{R}^{1 \times n}. This is the canonical control-theory SSM (Kalman 1960; not specific to deep learning)[1].

The matrix AA defines the intrinsic dynamics of the hidden state — how it evolves in the absence of input. BB defines how new input enters the state. CC defines what part of the state is observed as output.

2.1 The convolutional view

Solving the ODE (assuming h(0)=0h(0) = 0):

h(t)=∫0teA(t−s)B x(s) ds,y(t)=∫0tCeA(t−s)B⏟=:K(t−s) x(s) ds.h(t) = \int_0^t e^{A(t - s)} B\, x(s)\, ds, \qquad y(t) = \int_0^t \underbrace{C e^{A(t-s)} B}_{=: K(t-s)}\, x(s)\, ds.

So yy is the convolution of xx with the kernel K(τ)=CeAτBK(\tau) = C e^{A \tau} B. The kernel is determined entirely by (A,B,C)(A, B, C). This is the operative observation that links SSMs to convolutions and, by Fourier, to fast algorithms.


3. Discretisation

To use SSMs on discrete token sequences, we discretise the ODE with step size Δ\Delta. The Zero-Order Hold (ZOH) discretisation, which Mamba uses:

 Aˉ=exp⁡(ΔA),Bˉ=(ΔA)−1(exp⁡(ΔA)−I)⋅ΔB, \boxed{\ \begin{aligned} \bar A &= \exp(\Delta A), \\ \bar B &= (\Delta A)^{-1} (\exp(\Delta A) - I) \cdot \Delta B, \end{aligned} \ }

so the recurrence becomes

ht=Aˉ ht−1+Bˉ xt,yt=C ht.h_t = \bar A\, h_{t-1} + \bar B\, x_t, \qquad y_t = C\, h_t.

This is a linear recurrent network. Given the state ht−1h_{t-1} and input xtx_t, the new state hth_t requires one n×nn \times n matrix-vector multiply (cost n2n^2) plus one n×1n \times 1 matrix-vector multiply (cost nn); the output requires one 1×n1 \times n multiply (cost nn). Per-step cost: O(n2)O(n^2).

The crucial structural difference from a standard RNN (5.5) is that the recurrence is linear — no per-step non-linearity inside the state update. Non-linearity is added externally (a SwiGLU-like block applied to yty_t). Linearity is what enables the parallel-scan formulation of §5.

3.1 Structured AA: from S4 to Mamba

The naive n×nn \times n matrix AA has n2n^2 free parameters per channel, which is impractical at the channel counts (dmodel=4096d_\text{model} = 4096, etc.) of LLM-scale models. The S4 paper (Gu et al., 2022, arXiv:2111.00396)[2] introduced structured AA matrices — diagonal-plus-low-rank — that have O(n)O(n) parameters and admit fast convolutional evaluation via FFTs.

Mamba uses a simpler structured form: AA is diagonal with negative real entries, so the recurrence is a per-state-coordinate exponential decay:

A=diag(a1,…,an),ai<0.A = \text{diag}(a_1, \dots, a_n), \quad a_i < 0.

This has only nn parameters per channel, and each coordinate of the state evolves independently: ht(i)=eΔaiht−1(i)+(input term)ih_t^{(i)} = e^{\Delta a_i} h_{t-1}^{(i)} + (\text{input term})_i. Different coordinates capture different timescales of state retention — small ∣ai∣|a_i| means slow decay (long memory), large ∣ai∣|a_i| means fast decay (short memory). Empirically, training discovers a spread of timescales without needing explicit constraints.


4. Selective SSM: Mamba

The S4 line gave good signal-processing models but lost to Transformers on language tasks. The Mamba paper's diagnosis: a time-invariant SSM (with fixed A,B,CA, B, C) cannot do content-dependent state updates. For language, the model often needs to decide "keep this token's information in state" vs "forget it" based on the token itself — what attention's content-based addressing does, and what a content-blind SSM cannot.

Selective SSM (Mamba's contribution): make Δ,B,C\Delta, B, C functions of the input.

 Δt=softplus(LinearΔ(xt)),Bt=LinearB(xt),Ct=LinearC(xt). \boxed{\ \begin{aligned} \Delta_t &= \text{softplus}(\text{Linear}_\Delta(x_t)), \\ B_t &= \text{Linear}_B(x_t), \\ C_t &= \text{Linear}_C(x_t). \end{aligned} \ }

The recurrence becomes

ht=exp⁡(ΔtA) ht−1+Bˉt xt,yt=Ct ht,h_t = \exp(\Delta_t A)\, h_{t-1} + \bar B_t\, x_t, \qquad y_t = C_t\, h_t,

with Bˉt\bar B_t the input-dependent discretised BtB_t. The matrix AA stays time-invariant (so the eigenstructure is preserved); only the coupling into and out of state, and the time step, vary per token.

The interpretation: Δt\Delta_t controls "how much time has passed" between tokens — large Δt\Delta_t means strong decay of past state (fast forgetting), small Δt\Delta_t means weak decay (long memory). BtB_t controls how the current token's content enters the state — the model can choose to gate the token in (large BtB_t) or skip it (small BtB_t). CtC_t controls what part of the state is read out at this step.

This is the SSM analogue of attention's content-addressed gathering: per token, the model dynamically chooses what to remember, how strongly, and what to output.

4.1 Why this destroys the convolutional structure

Time-invariant SSMs are convolutions (§2.1), so they can be computed in O(Tlog⁡T)O(T \log T) via FFT. Selective SSMs are time-varying convolutions — the kernel depends on the input — and admit no direct FFT trick.

Mamba's solution is the parallel scan: the linear recurrence ht=Aˉtht−1+Bˉtxth_t = \bar A_t h_{t-1} + \bar B_t x_t is an "associative scan" over the sequence (the operator (h,c)↦Aˉc+h(h, c) \mapsto \bar A c + h is associative when you collect the Aˉt,Bˉt,xt\bar A_t, \bar B_t, x_t correctly into pairs). Associative scans can be computed in O(log⁡T)O(\log T) depth with O(T)O(T) work using the standard parallel-prefix-sum algorithm. The Mamba paper implements this with a hardware-aware CUDA kernel that minimises HBM↔SRAM transfers, similar in spirit to FlashAttention but for the scan operation.

Per-token training compute: O(d⋅n)O(d \cdot n) for state update, O(d⋅n)O(d \cdot n) for output projection — same per-token cost as a Transformer FFN of width dd (no quadratic-in-TT term, because there is no attention matrix to compute).


5. Compute and memory: the headline comparison

Per-layer cost comparison for a single token at position TT:

| Operator | Train: FLOPs per token | Inference: FLOPs per generated token | KV cache | |---|---|---|---| | MHA (with FlashAttention) | Θ(Td)\Theta(T d) | Θ(Td)\Theta(T d) | 4dT4 d T bytes | | GQA-88 | Θ(Td)\Theta(T d) | Θ(Td)\Theta(T d) | 4(d/8)T4 (d/8) T bytes | | MLA | Θ(Td)\Theta(T d) | Θ(Td+rd)\Theta(T d + r d) | 2(r+dhR)T2 (r + d_h^R) T bytes | | Selective SSM | Θ(dn)\Theta(d n) | Θ(dn)\Theta(d n) | 00 (state is dnd n scalars, fixed not growing) |

The headline: SSM compute per generated token is constant in TT. There is no cache that grows with sequence length. The hidden state has fixed dimension d⋅nd \cdot n, independent of TT.

This is the structural reason for SSMs' interest in long-context generation:

  • At T=1,000T = 1{,}000, a Transformer reads ∼10\sim 10 MB of KV cache per generated token (LLaMA-7B-class). An SSM reads ∼100\sim 100 KB of state. The SSM is ∼100×\sim 100\times faster at the memory-bandwidth level.
  • At T=100,000T = 100{,}000, the Transformer reads ∼1\sim 1 GB per generated token. The SSM still reads ∼100\sim 100 KB. The SSM is ∼10,000×\sim 10{,}000\times faster.
  • The crossover point at which an SSM is "free" is essentially at T=0T = 0; the constant cost is small enough that SSMs are competitive with attention even at short sequences.

5.1 But quality?

The Mamba paper's main empirical claim: at iso-parameters, Mamba matches Transformer perplexity on Pile-style pretraining and outperforms on long-context benchmarks (where the Transformer's effective context degrades). Subsequent work (Mamba-2, Dao & Gu 2024[4]; Hymba; etc.) has confirmed and extended this at the 1B–3B scale.

But at the frontier (∼100\sim 100B+ activated parameters), pure SSMs have not yet matched dense Transformer LLMs on standard benchmarks. The leading hypotheses for the residual gap:

  1. In-context retrieval. Attention's content-addressed lookup is exact (or nearly so, modulo softmax); an SSM's state is a lossy compression of the past. Tasks that require pulling a specific past token verbatim (e.g., needle-in-haystack) are easier for attention.
  2. Heuristic inductive biases of attention. Decades of attention-related architectural tuning have given the field a host of small improvements (RoPE, GQA, sliding-window) that SSMs have not yet seen full attention to.
  3. Training stability. SSMs at very large scale have known numerical-stability issues that the field has not fully worked through.

The current state of the art is to combine attention and SSM, which is the subject of §8.8 (hybrids).


6. The block

A Mamba block, in shape, is

x ── RMSNorm ── linear up-proj (to 2*d) ── split ──┐
                                                    │
       ┌── Selective SSM (with selective Δ, B, C) ──┤
       │                                            │
       └── SiLU ──────────── elementwise * ────────┘──── linear down-proj (back to d) ── + (residual) ── x_out

In words: pre-norm, up-project to 2d2d, split into two halves of width dd. Apply the selective SSM to one half. Apply SiLU to the other half. Elementwise-multiply (a gating like SwiGLU). Down-project back to dd. Residual add. There is no separate FFN block: the SSM block already includes its own non-linearity and gating, so a Mamba layer is one block (not the two of attention + FFN in a Transformer).

This means a Mamba "layer" at fixed parameter count corresponds to about 2× the number of layers in a Transformer with the same parameters. Mamba-3B has 64 layers; a Transformer-3B has ∼32\sim 32. The depth doubles but each layer is cheaper.


7. What we keep going forward

  1. An SSM is a linear (or near-linear) recurrent operator ht=Aˉht−1+Bˉxth_t = \bar A h_{t-1} + \bar B x_t, yt=Chty_t = C h_t. Discretised from a continuous-time linear ODE. With diagonal AA, the state coordinates evolve at independent timescales.

  2. Selective SSM (Mamba) makes Δ,B,C\Delta, B, C input-dependent. This is the SSM analogue of attention's content-addressed lookup. Time-invariant SSMs (S4) lost to Transformers on language; selective SSMs are competitive.

  3. SSMs have O(1)O(1) KV-like state, not O(T)O(T). Decode per token is constant in TT, vs Transformer's O(T)O(T). The wall-clock advantage at long TT is enormous.

  4. At iso-parameters, Mamba matches Transformer at ≲3\lesssim 3B and underperforms slightly at frontier scale. The leading hypothesis is that exact in-context retrieval needs attention; a lossy state compression does not suffice.

  5. The 2026 frontier uses hybrids. Interleave Mamba and attention layers (Jamba, Samba) to combine the per-token-throughput advantage of SSMs with the recall accuracy of attention. This is the subject of §8.8.

Self-test

(a) Write the continuous-time SSM of §2. Derive the convolutional form y(t)=(K∗x)(t)y(t) = (K * x)(t) with K(τ)=CeAτBK(\tau) = C e^{A\tau} B. Why is this only valid if AA is time-invariant?

(b) State the ZOH discretisation of §3. Derive the per-step cost O(n2)O(n^2) for naive AA and O(n)O(n) for diagonal AA. What's lost by restricting to diagonal?

(c) Explain in your own words why a time-invariant SSM cannot do "selective forgetting" of input tokens. Why is making Δ,B,C\Delta, B, C input-dependent (the Mamba contribution) the natural fix?

(d) Compute the per-generated-token bandwidth cost for (i) MHA on LLaMA-7B at T=32kT = 32k, (ii) Mamba-7B-class with state dim n=16,d=4096n = 16, d = 4096, both fp16. Which is more memory-traffic-efficient?

(e) A Mamba block has one sub-module that combines SSM and gating; a Transformer block has two sub-modules (attention + FFN). Argue why this means a Mamba "layer" at fixed parameters corresponds to roughly 2× the layer count of a Transformer.

(f) State the leading hypothesis (§5.1, item 1) for why pure SSMs underperform Transformers at frontier scale. Why do hybrid architectures (§8.8) plausibly close the gap?


References

  1. [1]

    Kalman, R. E. (1960). "A new approach to linear filtering and prediction problems". Trans. ASME—J. Basic Eng., 82, 35–45. — Canonical state-space formulation of linear filtering, ancestor of all SSM architectures (8.7 §2).

    ↩
  2. [2]

    Gu, A., Goel, K., & Ré, C. (2022). "Efficiently modeling long sequences with structured state spaces" (S4). arXiv:2111.00396 — Structured (diagonal-plus-low-rank) AA for efficient long-sequence SSM (8.7 §3.1).

    ↩
  3. [3]

    Gu, A., & Dao, T. (2023). "Mamba: Linear-time sequence modeling with selective state spaces". arXiv:2312.00752 — Selective SSM with input-dependent Δ,B,C\Delta, B, C; hardware-aware parallel scan (8.7 §4).

    ↩
  4. [4]

    Dao, T., & Gu, A. (2024). "Transformers are SSMs: Generalized models and efficient algorithms through structured state space duality" (Mamba-2). arXiv:2405.21060 — SSM-attention duality; Mamba-2 architecture (8.7 §5.1).

    ↩