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
- Builds on
- 28 concepts →
- Quiz
- 4 questions ↓
This leads to
—The full path from zero — 28 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- 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.
Key idea An SSM layer carries a fixed-size state through the sequence with a linear update, . 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 to outputs through a hidden state vector of size :
In words: the new state is the old state, transformed by , plus the new input, written in through ; the output is read off the state through . is an matrix (in practice usually diagonal), and and are vectors of length . In a real layer this runs independently for each of the model's channels.
The name comes from control theory, where the same equations describe physical systems in continuous time, . Deep-learning SSMs start from that continuous form and discretise it with a step size : roughly, . A small means "little time passes, keep the state"; a large 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 , and that 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 :
So the output is a convolution of the input with the fixed kernel . 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 , , , and inputs .
- Recurrence: , , , . Outputs .
- Convolution: the kernel is . Then . Same answer.
Notice that the first input fades by half each step. With , it is almost gone after 10 steps. Remembering across thousands of steps requires a well-chosen .
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 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 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 ) worked about as well.
But on language, these models still lagged behind Transformers.
Mamba: selective state spaces
S4 is time-invariant: , , and 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 , and from its hidden vector. This is a selective state space model:
- A large means "this token matters": the old state is largely forgotten and the new input is written in strongly.
- A small 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 .
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 , and composing linear maps is associative, the whole sequence can be combined in a tree of rounds instead of 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.
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 with 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
- Redo the worked example with . What is ? How many steps until the first input's contribution drops below 1% of its starting value?
- 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.)
- Harder: implement a parallel scan for the scalar recurrence by combining pairs with the rule . Check it against the sequential loop.
Hint for 1: when .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Mamba: Linear-Time Sequence Modeling with Selective State Spaces
A selective state-space model that rivals Transformers with linear cost in sequence length.
The Annotated S4
The S4 paper re-implemented line by line in JAX, with the maths explained along the way.
Efficiently Modeling Long Sequences with Structured State Spaces (S4)
The structured state space model that made linear recurrences competitive on very long sequences.
Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2)
Shows a close mathematical link between selective SSMs and a form of linear attention, and uses it to build the faster Mamba-2.
Jamba: A Hybrid Transformer-Mamba Language Model
Interleaves Transformer attention layers, Mamba layers and mixture-of-experts layers in one large hybrid model.
Lil'Log
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