State Space Models: SSMs and Mamba
A recurrence borrowed from control theory
State space models come from a lineage that has nothing to do with language: continuous-time systems in engineering, where a hidden state evolves under a differential equation and produces observations. Discretise that equation over sequence positions and it becomes a recurrence â update the state with the current input, read out a value â which is precisely the shape of a recurrent neural network, and inherits both its efficiency and its long-standing difficulty with parallel training.
What changed is the treatment of the parameters. Classical formulations fix the dynamics so that the same linear operator applies at every step, which lets you compute the whole sequence with a convolution instead of a loop; that gives parallel training and linear-time execution. Mamba's contribution was to relax the constraint that the dynamics be input-independent, making the transition parameters functions of the current token. That reintroduces a sequential dependency â but only through a scan that stays linear in sequence length, so training remains parallelisable through hardware-aware kernels while the model gains the ability to decide, per token, what to remember and what to discard.
From continuous dynamics to a discrete recurrence
The bridge between the two worlds is discretisation: choose a step size and turn the differential equation into a difference equation that a computer can iterate.
import torch
import torch.nn as nn
class SelectiveSSM(nn.Module):
def __init__(self, d_model: int, d_state: int = 16, dt: float = 0.01):
super().__init__()
self.d_model = d_model
self.d_state = d_state
self.dt = dt
self.A_log = nn.Parameter(torch.randn(d_model, d_state))
self.B = nn.Linear(d_model, d_state)
self.C = nn.Linear(d_model, d_state)
self.D = nn.Parameter(torch.ones(d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
batch, seq_len, _ = x.shape
A = -torch.exp(self.A_log) # stable: eigenvalues negative
B = self.B(x) # [B, L, N], input-dependent
C = self.C(x) # [B, L, N], input-dependent
dA = torch.exp(self.dt * A) # [d, N]
dB = self.dt * B # [B, L, N]
h = torch.zeros(batch, self.d_model, self.d_state, device=x.device)
ys = []
for t in range(seq_len):
h = dA.unsqueeze(0) * h + dB[:, t].unsqueeze(1) * x[:, t].unsqueeze(-1)
y = (h * C[:, t].unsqueeze(1)).sum(-1) + self.D * x[:, t]
ys.append(y)
return torch.stack(ys, dim=1)
Three choices in that loop decide the behaviour. The exponential on A guarantees stability â a state that grows without bound turns a language model into a divergent one after a few hundred positions. The step size controls the memory horizon: a small step forgets slowly and can carry context across long stretches, a large step reacts sharply and forgets quickly. And the skip connection through D gives every block a plain linear path, so gradients have somewhere to travel when the recurrent path is deep.
Selection: the switch that made SSMs competitive
The input-independent version of this recurrence behaves like a fixed filter: it treats every token the same way, remembering and forgetting on a schedule it cannot change. Language does not work like that. Articles and punctuation are worth skipping; a negation or a function name is worth writing down.
def selective_gates(x, A_log, B_proj, C_proj, dt=0.01):
"""Illustrates what selection changes: per-token decay and emission."""
A = -torch.exp(A_log) # [d, N]
B = B_proj(x) # [B, L, N]
C = C_proj(x) # [B, L, N]
decay = torch.exp(dt * A).unsqueeze(0) # fixed across the sequence
write = torch.sigmoid(B).unsqueeze(1) * dt # per-token write strength
read = torch.tanh(C) # per-token read strength
return decay, write, read
# decay is constant: the filter cannot change its memory policy.
# write and read vary with the input: the model can choose what enters state.
With selection in place, the model can zero out uninformative tokens before they reach the state and emphasise the ones that matter â the discrete analogue of attention deciding where to look, implemented as a gated recurrence instead of a weighted sum over all positions. That is why selective models close most of the gap that purely convolutional sequence models never could.
The trade-off table
| Aspect | State space model | Transformer |
|---|---|---|
| Sequence complexity | Linear in length | Quadratic in length |
| Training parallelism | Via scan kernels | Fully parallel attention |
| Retrieval of exact tokens | Indirect, via state | Direct, every position visible |
| Long-context memory | Fixed state budget | Grows with the key set |
| Inference cost | Cacheable state, constant per step | Grows with context length |
| Maturity | Rapidly improving | Battle-tested tooling |
The retrieval row is the honest weak point. Attention keeps every previous token addressable, so copying an exact string from far back is trivial; a recurrent state must compress everything it has seen into a fixed-size vector, and exact recall under compression is the classic failure. Benchmarks that hinge on needle-in-a-haystack retrieval therefore favour attention, while tasks dominated by summarisation, classification, and smooth continuation suit state space models well.
Where SSMs win in practice
The case for state space models is strongest where length and latency dominate. Generation over very long contexts: because the per-step cost does not grow with what has already been produced, throughput stays flat instead of degrading late in a long document. Streaming workloads: the state is a cache you can carry across calls, so real-time transcription or monitoring systems pay a constant price per frame. On-device inference: linear memory growth and cheap steps fit the constraints of hardware where every byte of activation matters. And high-frequency signals â audio, sensor traces, telemetry â where sequences are genuinely long and the quadratic wall arrives quickly.
The case against is equally concrete. Tasks requiring precise recall of earlier exact content, heavy multi-document reasoning where attention's direct access pays off, and toolchains: kernels, quantisation support, and profiling infrastructure for attention are years ahead, and that gap costs real engineering time.
There is also a training-cost subtlety worth knowing before you commit. The recurrent formulation is linear in length, but hardware prefers regular, parallel work, so the realised speed depends entirely on whether an efficient scan kernel exists for your shape and device. Where it does, training throughput is excellent and the theoretical advantage shows up as real numbers. Where it does not, a hand-written loop â like the illustrative one above â runs sequentially and squanders the advantage entirely, leaving you with attention's recall problems and none of attention's speed. Always profile on your own shapes rather than trusting published throughput figures from a different sequence length.
Hybrids and where this is heading
Most serious systems now land on a hybrid. Use attention layers where exact retrieval matters and state space layers where length and throughput matter, interleaved so the model gets both capabilities without paying quadratic cost everywhere. The practical benefit is that the weaknesses of each are covered by the other: attention handles the recall that compression loses, while the SSM blocks carry long-range continuity cheaply.
For evaluation, separate the two questions that get conflated. Quality per token â perplexity, task accuracy â tells you whether the model learned the domain. Scaling of cost with length â throughput at increasing context sizes, memory growth â tells you whether the architecture earns its place. A model that is a few points behind at short context but stays flat as sequences grow is often the right production choice, and only a benchmark that reports both will show you that.
A quick way to make the difference tangible in your own measurements is to time generation at two context lengths and compare the gap. Attention-based models show a widening per-step cost as the context fills, while state space models stay close to flat, because the state they carry does not grow. That single experiment predicts the deployment behaviour better than any leaderboard, and it takes an afternoon rather than a research budget.
Common Mistakes
Comparing an SSM to a transformer only on short-context quality
Fix: Report cost and throughput against length too; the linear advantage is the whole argument.
Expecting exact recall of distant tokens from a fixed-size state
Fix: Route retrieval-heavy steps through attention layers or give the system an external index.
Changing the step size without rechecking the memory horizon
Fix: Step size controls how far information survives; retune it as a real hyperparameter, not a constant.
Discounting the model because kernels and quantisation tooling are immature
Fix: Budget the integration cost explicitly and measure it against the latency you would otherwise pay.
Best Practices
- Measure perplexity and length-scaling cost together, since either alone misleads on this architecture.
- Interleave attention blocks in long-context models rather than choosing one family exclusively.
- Cache the recurrent state across streamed calls instead of reprocessing the whole prefix.
- Keep a retrieval-heavy probe in evaluation to catch the recall failures compression introduces.
Key Takeaways
- State space models discretise a continuous state equation into a linear recurrence, giving linear-time sequence processing.
- Selection â making transition parameters input-dependent â lets the model decide per token what to write and forget.
- The step size sets the memory horizon; stability comes from constraining the transition dynamics to decay.
- The real weakness is exact recall under compression, which attention handles trivially and state must approximate.
- Hybrid stacks combining attention for retrieval and SSMs for length are where most practical systems are converging.