Selective State Spaces: Mamba
Input-dependent dynamics, parallel scans and hardware-aware kernels.
S4 remembers well but cannot choose what to remember: it applies the same filter to every input. Mamba makes the step size and the input and output maps functions of the current token. That one change turns a convolution into a gated recurrence, demands a new GPU kernel to compute it quickly, and, written out as a matrix, turns out to be a form of masked attention.
What you’ll learn
- Prove that no linear time-invariant layer with a linear readout solves selective copying, and relate the failure to recall tasks.
- Define the selective SSM, prove its gating theorem for a one-dimensional state, and interpret , and .
- Explain the hardware-aware selective scan (kernel fusion, on-chip state, recomputation), its costs, and the Mamba block.
- Show that an SSM is multiplication by a semiseparable matrix, that with scalar decay it is masked linear attention (structured state space duality), and how Mamba-2's chunked algorithm uses this.
What a time-invariant layer cannot select
In the copying task a model reads a few tokens, waits through a fixed stretch of blanks, and must reproduce them; an LTI layer solves it with a kernel of exactly the right length, since only timing matters. In selective copying the tokens to remember are scattered at random positions among filler, so the model must decide by content what to keep. In the induction heads task it must recall what followed an earlier occurrence of the current token. Gu and Dao (2023) used both to diagnose the weakness of LTI models, and the first has a short proof.
Take two candidate positions in . Put the marked token at , filler at and zeros elsewhere (zero is valid filler). The output must equal for every :
Exchange the roles of and : the same argument forces . Both cannot hold. The kernel gives a position a weight that depends only on its distance from the output, never on what sits there, so it cannot pass a token at a lag where it must also block filler.
| Architecture | Sequence layer | Selective copying accuracy |
|---|---|---|
| plain stack | S4 (LTI) | 18.3% |
| plain stack | S6 (selective) | 97.0% |
| H3 (gated) | S4 | 57.0% |
| H3 (gated) | S6 | 99.7% |
| Mamba block | S4 | 56.4% |
| Mamba block | S6 | 99.8% |
The selective SSM and the gating theorem
The continuous system is the leaky integrator . With , zero-order hold gives
and, since and ,
The step size is the gate. A large () resets the state and writes the current input; a small one () holds the state and ignores the input. In Gu and Dao's words, "controls the balance between how much to focus or ignore the current input". For larger , input-dependent and add finer control over what enters the state and what is read out.
In the theorem's setting, the projection gives for some token. What update does the layer apply?
- : the token is ignored
- : the state is reset
Show the answer
C.
, so and : an even blend. Large positive approaches a reset, large negative approaches ignoring the token; at the gate is or .
Computing it: the hardware-aware selective scan
Without a kernel, the layer must run its recurrence. For a batch of sequences of length with channels and state size , the recurrence costs operations, against for an LTI convolution, and has the smaller constant. Two problems remain: the steps are sequential, and the states form a tensor of shape , times larger than the input and output. Most operations other than matrix products are limited by memory bandwidth, so writing that tensor to HBM and reading it back would dominate the cost.
For one sequence of tokens in a layer with channels and , stored in 2-byte floats, how many megabytes would the full state tensor take? (The output takes about 8 MB.)
Show the answer
134 MB
bytes MB, sixteen times the output, for one layer and one sequence, and again for the backward pass. Avoiding this traffic is the point of the fused kernel.
Kernel fusion. Load , , , from HBM into on-chip SRAM, discretize and run the recurrence there, and write only the outputs back. The traffic to HBM shrinks from the size of the states to the size of the inputs and outputs:
Parallel scan. Each step is an affine map , and composition of affine maps is associative, so a work-efficient parallel scan (Blelloch, 1990) computes all states in parallel steps:
Recomputation. Backpropagation needs the intermediate states, but storing them would bring the tensor back. The kernel instead recomputes them in the backward pass, when the inputs are loaded into SRAM again, the same trade as gradient checkpointing. The fused layer then needs about as much memory as an optimized transformer layer with FlashAttention.
The Mamba block. An input projection widens the -dimensional stream by a factor into two branches. The main branch applies a short causal convolution, a SiLU, and the selective SSM; the other branch applies a SiLU and multiplies the result elementwise, a gate as in the SwiGLU MLP; an output projection returns to dimensions. The projections hold almost all of the parameters per block, so two blocks match a transformer layer's . The network repeats this one block, with normalization and residual connections, and has no attention and no separate MLP. For text the state is real, initialized with .
Reported results. In the paper's experiments, Mamba matched or beat transformers of similar size on language modeling, a 3-billion-parameter Mamba matched transformers twice its size, generation throughput was about five times that of a comparable transformer, and on DNA and audio, performance kept improving with context length up to a million tokens. How these results extend to much larger scales, and to tasks that need exact recall from long contexts, is the subject of Hybrid Models & the Limits of Fixed-Size Memory.
State space duality: SSMs as masked attention
Write the whole layer as one matrix acting on the sequence. That view, developed by Dao and Gu (2024), connects selective SSMs to attention exactly, and leads to a faster algorithm built on matrix multiplications.
Unroll the time-varying recurrence for one channel from and read out with . The output is for a lower-triangular matrix:
Split the sequence at any position . Every entry in a row and a column factors through the state , so every submatrix on or below the diagonal has rank at most . That is the definition of an -semiseparable matrix; conversely, every -semiseparable matrix arises from an SSM of state size (Dao & Gu, 2024).
Now restrict each to a scalar times the identity, , as Mamba-2 does. The products of matrices become products of scalars, and splits into a decay mask times a matrix of dot products:
This is masked attention without the softmax: queries , keys , values , and a data-dependent mask in place of the causal mask. With for all , is the causal mask of ones and the layer is exactly causal linear attention. The quadratic "attention form" and the linear recurrence are two orders of evaluating one product: this is structured state space duality.
The chunked algorithm. Mamba-2 cuts the sequence into chunks of length . Inside each chunk it uses the quadratic form, small dense matrix products that tensor cores execute efficiently; between chunks it passes only the -dimensional states, through a short recurrence over the chunk boundaries, because the off-diagonal blocks are low-rank. With state size, head dimension and chunk length all equal to , the whole layer costs operations and memory, mostly in matrix multiplications:
| Quantity | Softmax attention | Selective SSM (scan) | SSD (Mamba-2) |
|---|---|---|---|
| State carried while generating | (the KV cache) | ||
| Training operations | |||
| Operations per generated token | |||
| Memory, naive | |||
| Mostly matrix multiplications | yes | no | yes |
Key takeaways
- An LTI layer weighs an input by its lag alone, so no LTI layer with a linear readout can select tokens by content; gating between layers helps only partially (selective copying: 18.3% for a plain S4 stack, about 57% with gating, 99.8% for Mamba).
- The selective SSM makes , and functions of the token; with , , it is exactly the gated RNN with : a large step resets and writes, a small one holds and ignores.
- The selective scan is exact and linear in ; kernel fusion keeps the -times-larger states in SRAM, a parallel scan removes the sequential bottleneck, and recomputation removes the activation memory.
- Any SSM is multiplication by an -semiseparable matrix; with scalar decay it is masked linear attention, , and Mamba-2 computes it in chunks with matrix multiplications, work and memory.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why can a linear time-invariant layer not solve selective copying, even with many channels?
- Its state is too small to hold several tokens
- The weight it gives an input depends only on the input's distance from the output, not on its content, so it cannot pass marked tokens and block filler at the same lags
- It cannot represent long kernels
- Its eigenvalues must be real
Show the answer
B. The weight it gives an input depends only on the input's distance from the output, not on its content, so it cannot pass marked tokens and block filler at the same lags
An LTI layer computes , and channels combined linearly form one kernel. When marked tokens and filler can occupy the same positions, would have to be and at the same lag. Making , and depend on removes the obstruction.
In a selective SSM, a token produces a very large step size . What happens to the state?
- It is held unchanged and the token is ignored
- It grows without bound
- It oscillates
- It is reset and the token is written in, since and the input map takes over
Show the answer
D. It is reset and the token is written in, since and the input map takes over
For a stable , as , so the old state is erased, while , which writes the token. In the gating theorem this is .
What does Mamba's fused selective-scan kernel avoid, compared with a straightforward implementation?
- Writing the tensor of states to HBM and storing it for the backward pass
- Any computation that grows with the sequence length
- The discretization step, which it skips
- Sequential dependence between tokens, by approximating the recurrence with a convolution
Show the answer
A. Writing the tensor of states to HBM and storing it for the backward pass
The kernel keeps the expanded states in SRAM, writes only the outputs, and recomputes the states in the backward pass. The computation stays exact and linear in ; what shrinks is the memory traffic and the activation memory.
In a scalar-decay SSM, with for . If for every , what is the layer?
- Softmax attention with a causal mask
- An LTI convolution with an exponentially decaying kernel
- Causal linear attention, , with queries and keys
- The identity map
Show the answer
C. Causal linear attention, , with queries and keys
With all the mask is the lower-triangular matrix of ones, the causal mask, and is the unnormalized causal attention matrix without a softmax. Decays that depend on the input turn it into Mamba-2's gated linear attention.
Further reading
- A. Gu & T. Dao, "Mamba: Linear-time sequence modeling with selective state spaces," arXiv:2312.00752 (2023); Conference on Language Modeling (COLM) (2024).
- T. Dao & A. Gu, "Transformers are SSMs: Generalized models and efficient algorithms through structured state space duality," ICML (2024).
- G. E. Blelloch, "Prefix sums and their applications," Technical Report CMU-CS-90-190, Carnegie Mellon University (1990).
- A. Katharopoulos, A. Vyas, N. Pappas & F. Fleuret, "Transformers are RNNs: Fast autoregressive transformers with linear attention," ICML (2020).