◆ AI All-in-One

Level 3 In-Depth AI · Transformers and Language Models

State Space Models and Mamba

An alternative to attention that reads a sequence like an RNN, carrying a fixed-size state, yet trains in parallel like a Transformer. S4 made it work on very long sequences; Mamba made the state selective; hybrids mix it with attention.

Level
●●●●● Advanced
Reading
12 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Recurrent Neural NetworksThe Transformer

This leads to

—
The full path from zero — 28 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. Normalization Layers: BatchNorm and LayerNorm
  22. LSTMs and GRUs
  23. Residual Connections
  24. Sequence-to-Sequence Models
  25. Attention
  26. Self-Attention and Multi-Head Attention
  27. Positional Encodings
  28. The Transformer
  29. State Space Models and Mamba

Read them roughly in this order. See it on the concept map →

Why it matters

Transformers have two costs that grow with length. Attention compares every token with every earlier one, so compute grows with the square of the sequence length (Long Context and Efficient Attention). And at generation time each new token must look back over a KV cache that grows by one entry per token, so memory and per-token cost keep rising as the text gets longer.

Recurrent neural networks had neither problem. They read a sequence one step at a time and carry a fixed-size recurrent state: generating token one million costs the same as generating token ten. But classic RNNs (and LSTMs) can't be trained in parallel across the sequence, which made them slow to train on modern GPUs, and they struggled to remember things over long distances.

State space models (SSMs) are a family of sequence layers that aim for the best of both: fixed-size state and constant cost per generated token like an RNN, but parallel training like a Transformer. S4 (2021) showed they could model extremely long sequences. Mamba (December 2023) added input-dependent "selectivity" and became the first attention-free architecture to match Transformers of the same size on language modelling in its authors' experiments. Since 2024, hybrid models that mix a few attention layers with many Mamba-style layers have appeared from several labs.

The intuition

Imagine taking notes during a three-hour lecture with a single index card. You can't write down everything, so after each sentence you update the card: erase what no longer matters, add what does. At the end, the card is all you have. That card is the state.

A Transformer instead keeps a full transcript and re-reads all of it whenever it needs something. It never forgets, but the transcript, and the time to search it, keep growing.

The early SSMs updated the card by a fixed rule: every note fades at a fixed rate, whatever the sentence says. That is cheap and mathematically convenient, but it can't decide that this sentence is important and that one is filler. Mamba's key idea is selectivity: the update rule depends on the current input, so the model can choose to hold on to its notes through irrelevant material and overwrite them when something important arrives.

h₀ h₁ × A x₁ × B y₁ × C h₂ × A x₂ × B y₂ × C h₃ × A x₃ × B y₃ × C h₄ × A x₄ × B y₄ × C fixed-size state (N numbers per channel, at every step) hₜ = A·hₜ₋₁ + B·xₜ, yₜ = C·hₜ S4: A, B, C the same at every step. Mamba: Δₜ (how much to forget), Bₜ and Cₜ are computed from xₜ.
Fig. 1 A state space model as a recurrence. At each step the state h is multiplied by A (fading old information), the new input x is added through B, and the output y is read out through C. In Mamba, A's effective decay, B and C all depend on the current input, which lets the model choose what to keep.

Key idea An SSM layer carries a fixed-size state through the sequence with a linear update, ht=Aht−1+Bxt\mathbf{h}_t = \mathbf{A}\mathbf{h}_{t-1} + \mathbf{B}x_t. Linearity lets it train in parallel; the fixed size makes generation cost constant per token. Mamba makes the update depend on the input, so the state can choose what to remember.

How it works

A linear recurrence

An SSM maps an input sequence x1,x2,…x_1, x_2, \dots to outputs y1,y2,…y_1, y_2, \dots through a hidden state vector ht\mathbf{h}_t of size NN:

ht=A ht−1+B xt,yt=C ht\mathbf{h}_t = \mathbf{A}\,\mathbf{h}_{t-1} + \mathbf{B}\,x_t, \qquad y_t = \mathbf{C}\,\mathbf{h}_t

In words: the new state is the old state, transformed by A\mathbf{A}, plus the new input, written in through B\mathbf{B}; the output is read off the state through C\mathbf{C}. A\mathbf{A} is an N×NN \times N matrix (in practice usually diagonal), and B\mathbf{B} and C\mathbf{C} are vectors of length NN. In a real layer this runs independently for each of the model's dd channels.

The name comes from control theory, where the same equations describe physical systems in continuous time, h′(t)=Ah(t)+Bx(t)\mathbf{h}'(t) = \mathbf{A}\mathbf{h}(t) + \mathbf{B}x(t). Deep-learning SSMs start from that continuous form and discretise it with a step size Δ\Delta: roughly, A‾=eΔA\overline{\mathbf{A}} = e^{\Delta \mathbf{A}}. A small Δ\Delta means "little time passes, keep the state"; a large Δ\Delta means "a lot of time passes, let the old state fade and take in the new input".

Compared with a classic RNN, the crucial difference is that there is no nonlinearity inside the recurrence. A vanilla RNN computes ht=tanh⁡(Wht−1+Uxt)\mathbf{h}_t = \tanh(\mathbf{W}\mathbf{h}_{t-1} + \mathbf{U}x_t), and that tanh⁡\tanh forces you to go step by step. Nonlinearities in an SSM-based network live between layers, not inside the recurrence.

Two ways to compute the same thing

Because the recurrence is linear, you can unroll it. Starting from h0=0\mathbf{h}_0 = 0:

yt=CB xt+CAB xt−1+CA2B xt−2+…y_t = \mathbf{C}\mathbf{B}\,x_t + \mathbf{C}\mathbf{A}\mathbf{B}\,x_{t-1} + \mathbf{C}\mathbf{A}^2\mathbf{B}\,x_{t-2} + \dots

So the output is a convolution of the input with the fixed kernel K=(CB,CAB,CA2B,… )\mathbf{K} = (\mathbf{C}\mathbf{B}, \mathbf{C}\mathbf{A}\mathbf{B}, \mathbf{C}\mathbf{A}^2\mathbf{B}, \dots). That gives two modes:

  • Training: the whole sequence is known, so compute all outputs at once as a convolution, in parallel (fast Fourier transforms make long convolutions cheap).
  • Generation: run the recurrence, one step at a time, with a fixed-size state and constant cost per token. No growing cache.

Worked example. Take a one-number state with A=0.5A = 0.5, B=1B = 1, C=1C = 1, and inputs x=(1,0,0,2)x = (1, 0, 0, 2).

  • Recurrence: h1=1h_1 = 1, h2=0.5h_2 = 0.5, h3=0.25h_3 = 0.25, h4=0.125+2=2.125h_4 = 0.125 + 2 = 2.125. Outputs y=(1,0.5,0.25,2.125)y = (1, 0.5, 0.25, 2.125).
  • Convolution: the kernel is (CB,CAB,CA2B,CA3B)=(1,0.5,0.25,0.125)(CB, CAB, CA^2B, CA^3B) = (1, 0.5, 0.25, 0.125). Then y4=1⋅2+0.5⋅0+0.25⋅0+0.125⋅1=2.125y_4 = 1 \cdot 2 + 0.5 \cdot 0 + 0.25 \cdot 0 + 0.125 \cdot 1 = 2.125. Same answer.

Notice that the first input fades by half each step. With A=0.5A = 0.5, it is almost gone after 10 steps. Remembering across thousands of steps requires a well-chosen A\mathbf{A}.

S4: making long memory work

The breakthrough paper was S4 ("Efficiently Modeling Long Sequences with Structured State Spaces", Albert Gu, Karan Goel and Christopher Ré, 2021). It initialised A\mathbf{A} with a mathematically derived matrix (from the earlier HiPPO theory) designed so the state optimally summarises the recent history, and found a structured form of A\mathbf{A} whose convolution kernel could be computed efficiently. On the Long Range Arena benchmark, S4 was the first model to solve the "Path-X" task, which requires reasoning over sequences of 16,384 elements, where earlier Transformer variants performed no better than chance. Simpler follow-ups (such as S4D, with a diagonal A\mathbf{A}) worked about as well.

But on language, these models still lagged behind Transformers.

Mamba: selective state spaces

S4 is time-invariant: A\mathbf{A}, B\mathbf{B}, C\mathbf{C} and Δ\Delta are the same at every step, regardless of the input. That is what allows the convolution trick, but it also means the layer can't decide what to remember based on content. Language needs exactly that kind of content-based choice: keep the subject of the sentence in mind, skip the filler words, reset at the start of a new document.

Mamba (Albert Gu and Tri Dao, December 2023) made the parameters functions of the input. For each token, small linear layers compute that token's Δt\Delta_t, Bt\mathbf{B}_t and Ct\mathbf{C}_t from its hidden vector. This is a selective state space model:

  • A large Δt\Delta_t means "this token matters": the old state is largely forgotten and the new input is written in strongly.
  • A small Δt\Delta_t means "ignore this token": the state passes through almost unchanged.

This is close in spirit to the gates of an LSTM, but the recurrence stays linear in h\mathbf{h}.

Selectivity breaks the convolution trick, since the kernel now changes from step to step. Mamba instead uses a parallel scan: because each step is a linear map h↦A‾th+B‾txt\mathbf{h} \mapsto \overline{\mathbf{A}}_t\mathbf{h} + \overline{\mathbf{B}}_t x_t, and composing linear maps is associative, the whole sequence can be combined in a tree of log⁡2T\log_2 T rounds instead of TT sequential steps (like computing a running total by adding pairs, then pairs of pairs). Mamba implements this as a fused GPU kernel that keeps the expanded state in fast on-chip memory, the same idea as FlashAttention.

A Mamba block wraps the selective SSM with a linear projection, a short convolution, a gating branch and an output projection, and the network stacks these blocks with no attention and no separate MLP. The paper reported that Mamba-3B matched Transformers about twice its size on language modelling, and that its generation throughput was about five times higher than a Transformer of similar size.

Mamba-2 (Tri Dao and Albert Gu, 2024) showed that a restricted selective SSM is mathematically equivalent to a form of linear attention with a particular mask ("structured state space duality"), which allowed a faster algorithm built on matrix multiplications and larger states.

What SSMs are bad at

A fixed-size state is a bottleneck. A Transformer can copy a long phone number from 50,000 tokens ago because it still has that token in its cache. An SSM has to have decided, when it read the number, to keep it in a finite state. Studies in 2024 found that pure SSMs do worse than Transformers on tasks that need exact recall or copying from long contexts, such as retrieving a specific line from a long document or in-context learning that depends on looking up earlier examples.

Hybrids

That is why many recent SSM-based language models are hybrid architectures: mostly SSM layers, with a few attention layers mixed in to handle precise retrieval.

  • Jamba (AI21 Labs, March 2024) interleaved Transformer and Mamba layers at about one attention layer per seven Mamba layers, added Mixture of Experts layers, and supported a 256,000-token context.
  • Through 2024 and 2025, other labs released hybrid models with similar mixes, reporting faster long-context inference and smaller caches than comparable pure Transformers.
Transformer attention attention attention attention attention attention attention attention cache grows in every layer Pure SSM (Mamba) SSM SSM SSM SSM SSM SSM SSM SSM fixed state in every layer Hybrid SSM SSM SSM attention SSM SSM SSM attention growing cache in only 2 of 8 layers memory each layer keeps at long context: KV cache (∝ length) fixed state
Fig. 2 Three ways to build a sequence model. A Transformer keeps a KV cache that grows with every token; an SSM keeps a fixed-size state; a hybrid mixes many SSM layers with a few attention layers, so only those few layers keep a growing cache.

In code

First, check that a linear SSM gives the same outputs whether run as a recurrence or as a convolution. Then see why selectivity matters: a fixed-decay state forgets a value seen 990 steps ago, while an input-dependent one keeps it.

import numpy as np
rng = np.random.default_rng(0)

# 1) A linear time-invariant SSM: run it as a recurrence and as a convolution
N, T = 4, 12                                   # state size, sequence length
A = np.diag([0.9, 0.7, 0.5, 0.2])              # how fast each state channel forgets
B, C = rng.standard_normal(N), rng.standard_normal(N)
x = rng.standard_normal(T)

h, y_rec = np.zeros(N), []
for t in range(T):                             # recurrence: O(1) work and memory per step
    h = A @ h + B * x[t]
    y_rec.append(C @ h)

K = np.array([C @ np.linalg.matrix_power(A, j) @ B for j in range(T)])   # CB, CAB, CA²B, ...
y_conv = [sum(K[j] * x[t - j] for j in range(t + 1)) for t in range(T)]  # convolution
print("recurrence == convolution:", np.allclose(y_rec, y_conv))

# 2) Selectivity: let the input decide how much to forget
def run(signal, flags, selective):
    h = 0.0
    for s, f in zip(signal, flags):
        if selective:
            keep = 0.0 if f else 1.0           # flagged token: overwrite; otherwise hold
        else:
            keep = 0.9                         # fixed decay, the same for every token
        h = keep * h + (1 - keep) * s
    return h

signal = rng.standard_normal(1000)
flags = np.zeros(1000, bool); flags[10] = True  # only token 10 matters
print(f"value to remember: {signal[10]:.3f}")
print(f"fixed-decay SSM after 1000 steps: {run(signal, flags, False):.3f}")
print(f"selective SSM after 1000 steps:   {run(signal, flags, True):.3f}")

# recurrence == convolution: True
# value to remember: -1.010
# fixed-decay SSM after 1000 steps: 0.087
# selective SSM after 1000 steps:   -1.010

In real Mamba the "keep" amount is not a hand-written rule but eΔtAe^{\Delta_t A} with Δt\Delta_t computed from the token by a learned layer, so the model learns which tokens to write and which to skip. The official implementation is the mamba-ssm package (it needs an NVIDIA GPU), and Hugging Face transformers includes Mamba and Mamba-2 model classes.

Common pitfalls

  • Expecting free long-context recall. Constant memory means lossy memory. For tasks that need exact retrieval from long inputs, check pure SSMs carefully, or use a hybrid.
  • Comparing on short sequences only. SSMs' speed advantage shows at long sequence lengths and long generations; at a few hundred tokens a well-optimised Transformer may be as fast.
  • Ignoring the kernels. Selective scans need specialised GPU code to be fast. A naive Python loop is fine for learning but hopeless for training.
  • Assuming tooling parity. Serving engines, quantisation tools and fine-tuning libraries have matured fastest for Transformers. Check support before committing to an SSM in production.

Watch out "Linear-time" claims are about sequence length. They say nothing about quality. Always compare models of similar size and training data on the tasks you care about, including ones that need recall from far back in the input.

Variations

  • Linear attention (2020) and RetNet (2023) replace the softmax in attention with forms that can be computed as a recurrence; Mamba-2 showed how closely these relate to SSMs.
  • RWKV is an open-source RNN-style language model family with a linear recurrence and Transformer-like training.
  • Gated linear RNNs such as Griffin (Google DeepMind, 2024) combine a gated linear recurrence with local attention.
  • Hybrids: attention plus SSM, often with MoE.
  • For the attention-side approaches to long sequences, see Long Context and Efficient Attention; for the memory problem SSMs avoid, see The KV Cache and Fast Inference.

A bit of history

State space models are a staple of control engineering and signal processing (the Kalman filter of 1960 is one). Their deep-learning version came from Albert Gu and colleagues in Christopher Ré's group at Stanford: HiPPO (2020) gave a principled way to compress history into a state, LSSL (2021) combined it with deep networks, and S4 (2021, published at ICLR 2022) made it efficient and beat everything else on long-range benchmarks. H3 and Hyena (2022–2023) pushed SSM-like layers towards language.

In December 2023 Gu, by then at Carnegie Mellon, and Tri Dao, the author of FlashAttention, released Mamba, which caught wide attention by matching Transformers on language modelling. In 2024 AI21 released Jamba (March), an early large hybrid of attention, Mamba and mixture-of-experts layers, and Dao and Gu published Mamba-2 (May). Whether SSMs replace attention, complement it, or remain a niche is still an open question as of late 2026, but hybrids are a serious contender for efficient long-context models.

Try it

  1. Redo the worked example with A=0.9A = 0.9. What is y4y_4? How many steps until the first input's contribution drops below 1% of its starting value?
  2. In the code, change the fixed decay to 0.999. Does the fixed SSM now remember token 10? What has it lost instead? (Look at how much each new token can change the state.)
  3. Harder: implement a parallel scan for the scalar recurrence ht=atht−1+bth_t = a_t h_{t-1} + b_t by combining pairs (a,b)(a, b) with the rule (a1,b1)∘(a2,b2)=(a1a2, a2b1+b2)(a_1, b_1) \circ (a_2, b_2) = (a_1 a_2,\ a_2 b_1 + b_2). Check it against the sequential loop.

Hint for 1: 0.9k<0.010.9^k < 0.01 when k>ln⁡(0.01)/ln⁡(0.9)≈43.7k > \ln(0.01)/\ln(0.9) \approx 43.7.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. What is the key advantage of an SSM over a Transformer when generating very long text?

  2. A one-number SSM has A = 0.5, B = 1, C = 1 and inputs x = (1, 0, 0, 2). What is y₄?

  3. What does Mamba's selectivity add compared with S4?

  4. Your task requires copying an exact phone number from 50,000 tokens earlier. Why might a pure SSM struggle?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tutorial

The Annotated S4

Sasha Rush & Sidd Karamcheti · Advanced · Free

The S4 paper re-implemented line by line in JAX, with the maths explained along the way.

Article

Lil'Log

Lilian Weng · Advanced · Free

Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/state-space-models.md