Simple Algorithm
Deep Learning · Emergence · 28 min

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 Δ\Delta, BB and CC.
  • 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.

DerivationProof
  1. KT−j v+KT−j′ f=vfor all f∈[−ϵ,ϵ]⟹KT−j′=0,  KT−j=1K_{T-j}\,v+K_{T-j'}\,f=v\quad\text{for all }f\in[-\epsilon,\epsilon]\quad\Longrightarrow\quad K_{T-j'}=0,\ \ K_{T-j}=1

    Take two candidate positions j≠j′j\ne j' in JJ. Put the marked token at jj, filler ff at j′j' and zeros elsewhere (zero is valid filler). The output must equal vv for every f∈[−ϵ,ϵ]f\in[-\epsilon,\epsilon]:

  2. KT−j=1andKT−j=0K_{T-j}=1\quad\text{and}\quad K_{T-j}=0

    Exchange the roles of jj and j′j': the same argument forces KT−j=0K_{T-j}=0. Both cannot hold. ■\blacksquare 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.

ArchitectureSequence layerSelective copying accuracy
plain stackS4 (LTI)18.3%
plain stackS6 (selective)97.0%
H3 (gated)S457.0%
H3 (gated)S699.7%
Mamba blockS456.4%
Mamba blockS699.8%
Gu & Dao (2023), Table 1. Multiplicative gating between layers helps an LTI layer partially, since gates act at each position but not along the sequence; making the recurrence itself depend on the input solves the task. On induction heads, a two-layer Mamba trained on sequences of 256 tokens recalled perfectly on sequences up to 220≈1062^{20}\approx10^6 tokens, 4,000 times longer, while the other models tested failed beyond twice the training length.

The selective SSM and the gating theorem

DerivationProof
  1. Aˉt=e−Δt=11+ezt=σ(−zt)=1−σ(zt)\bar A_t=e^{-\Delta_t}=\frac{1}{1+e^{z_t}}=\sigma(-z_t)=1-\sigma(z_t)

    The continuous system is the leaky integrator h′=−h+xh'=-h+x. With Δt=log⁡(1+ezt)\Delta_t=\log(1+e^{z_t}), zero-order hold gives

  2. Bˉt=(−Δt)−1(e−Δt−1) Δt=1−e−Δt=σ(zt)■\bar B_t=(-\Delta_t)^{-1}\big(e^{-\Delta_t}-1\big)\,\Delta_t=1-e^{-\Delta_t}=\sigma(z_t)\qquad\blacksquare

    and, since A=−1A=-1 and B=1B=1,

  3. Δt→∞: Aˉt→0, Bˉt→1Δt→0: Aˉt→1, Bˉt→0\Delta_t\to\infty:\ \bar A_t\to0,\ \bar B_t\to1\qquad\qquad\Delta_t\to0:\ \bar A_t\to1,\ \bar B_t\to0

    The step size is the gate. A large Δt\Delta_t (gt→1g_t\to1) resets the state and writes the current input; a small one (gt→0g_t\to0) holds the state and ignores the input. In Gu and Dao's words, Δ\Delta "controls the balance between how much to focus or ignore the current input". For larger NN, input-dependent BtB_t and CtC_t add finer control over what enters the state and what is read out.

Check your understanding

In the theorem's setting, the projection gives zt=0z_t=0 for some token. What update does the layer apply?

  1. ht=ht−1h_t=h_{t-1}: the token is ignored
  2. ht=xth_t=x_t: the state is reset
  3. ht=12ht−1+12xth_t=\tfrac12h_{t-1}+\tfrac12x_t
  4. ht=ht−1+xth_t=h_{t-1}+x_t
Show the answer

C. ht=12ht−1+12xth_t=\tfrac12h_{t-1}+\tfrac12x_t

Δt=softplus⁡(0)=log⁡2\Delta_t=\operatorname{softplus}(0)=\log2, so Aˉt=e−log⁡2=12\bar A_t=e^{-\log2}=\tfrac12 and Bˉt=12\bar B_t=\tfrac12: an even blend. Large positive ztz_t approaches a reset, large negative ztz_t approaches ignoring the token; at z=±3z=\pm3 the gate is 0.950.95 or 0.050.05.

Computing it: the hardware-aware selective scan

Without a kernel, the layer must run its recurrence. For a batch of BB sequences of length LL with DD channels and state size NN, the recurrence costs O(BLDN)\order{BLDN} operations, against O(BLDlog⁡L)\order{BLD\log L} for an LTI convolution, and has the smaller constant. Two problems remain: the steps are sequential, and the states form a tensor of shape (B,L,D,N)(B,L,D,N), NN 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.

Predict before you look

For one sequence of L=2,048L=2{,}048 tokens in a layer with D=2,048D=2{,}048 channels and N=16N=16, stored in 2-byte floats, how many megabytes would the full state tensor (L,D,N)(L,D,N) take? (The output (L,D)(L,D) takes about 8 MB.)

Show the answer

134 MB

2,048×2,048×16×22{,}048\times2{,}048\times16\times2 bytes ≈134\approx134 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.

DerivationThree classical techniques (Gu & Dao, 2023)
  1. O(BLDN) bytes moved⟶O(BLD+BLN+DN)\order{BLDN}\ \text{bytes moved}\quad\longrightarrow\quad\order{BLD+BLN+DN}

    Kernel fusion. Load Δ\Delta, AA, BB, CC 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:

  2. (Aˉ2,b2)∘(Aˉ1,b1)=(Aˉ2Aˉ1, Aˉ2b1+b2)(\bar A_2,\mathbf b_2)\circ(\bar A_1,\mathbf b_1)=\big(\bar A_2\bar A_1,\ \bar A_2\mathbf b_1+\mathbf b_2\big)

    Parallel scan. Each step is an affine map h↦Aˉth+Bˉtxt\mathbf h\mapsto\bar A_t\mathbf h+\bar B_tx_t, and composition of affine maps is associative, so a work-efficient parallel scan (Blelloch, 1990) computes all states in O(log⁡L)\order{\log L} parallel steps:

  3. memory O(BLD) per layer, not O(BLDN)\text{memory}\ \order{BLD}\ \text{per layer, not}\ \order{BLDN}

    Recomputation. Backpropagation needs the intermediate states, but storing them would bring the (B,L,D,N)(B,L,D,N) 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 DD-dimensional stream by a factor E=2E=2 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 DD dimensions. The projections hold almost all of the 3ED2=6D23ED^2=6D^2 parameters per block, so two blocks match a transformer layer's 12D212D^2. 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 λn=−(n+1)\lambda_n=-(n+1).

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.

DerivationSSMs are semiseparable matrices
  1. yj=∑i≤jCj⊤ AˉjAˉj−1⋯Aˉi+1 Bˉi⏟Mji  xiy_j=\sum_{i\le j}\underbrace{C_j^\top\,\bar A_j\bar A_{j-1}\cdots\bar A_{i+1}\,\bar B_i}_{M_{ji}}\;x_i

    Unroll the time-varying recurrence for one channel from h−1=0\mathbf h_{-1}=\mathbf 0 and read out with CjC_j. The output is y=Mx\mathbf y=M\mathbf x for a lower-triangular T×TT\times T matrix:

  2. Mji=(Cj⊤Aˉj⋯Aˉm+1)⏟1×N (Aˉm⋯Aˉi+1Bˉi)⏟N×1(i≤m≤j)M_{ji}=\underbrace{\big(C_j^\top\bar A_j\cdots\bar A_{m+1}\big)}_{1\times N}\ \underbrace{\big(\bar A_m\cdots\bar A_{i+1}\bar B_i\big)}_{N\times1}\qquad(i\le m\le j)

    Split the sequence at any position mm. Every entry in a row j≥mj\ge m and a column i≤mi\le m factors through the state hm\mathbf h_m, so every submatrix on or below the diagonal has rank at most NN. That is the definition of an NN-semiseparable matrix; conversely, every NN-semiseparable matrix arises from an SSM of state size NN (Dao & Gu, 2024).

  3. M=L∘(CBˉ⊤),Lji={ajaj−1⋯ai+1j≥i0j<iM=L\circ\big(C\bar B^\top\big),\qquad L_{ji}=\begin{cases}a_ja_{j-1}\cdots a_{i+1}&j\ge i\\0&j<i\end{cases}

    Now restrict each Aˉt\bar A_t to a scalar times the identity, Aˉt=atI\bar A_t=a_tI, as Mamba-2 does. The products of matrices become products of scalars, and MM splits into a decay mask times a matrix of dot products:

  4. y=(L∘CB⊤) x  (quadratic, attention-like)⟺ht=atht−1+Btxt, yt=Ct⊤ht  (linear, recurrent)\mathbf y=\big(L\circ CB^\top\big)\,\mathbf x\ \ \text{(quadratic, attention-like)}\qquad\Longleftrightarrow\qquad\mathbf h_t=a_t\mathbf h_{t-1}+B_tx_t,\ y_t=C_t^\top\mathbf h_t\ \ \text{(linear, recurrent)}

    This is masked attention without the softmax: queries CC, keys Bˉ\bar B, values x\mathbf x, and a data-dependent mask LL in place of the causal mask. With at=1a_t=1 for all tt, LL 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 QQ. Inside each chunk it uses the quadratic form, small dense matrix products that tensor cores execute efficiently; between chunks it passes only the NN-dimensional states, through a short recurrence over the T/QT/Q chunk boundaries, because the off-diagonal blocks are low-rank. With state size, head dimension and chunk length all equal to NN, the whole layer costs O(TN2)\order{TN^2} operations and O(TN)\order{TN} memory, mostly in matrix multiplications:

QuantitySoftmax attentionSelective SSM (scan)SSD (Mamba-2)
State carried while generatingTT (the KV cache)NNNN
Training operationsT2NT^2NTN2TN^2TN2TN^2
Operations per generated tokenTNTNN2N^2N2N^2
Memory, naiveT2T^2TN2TN^2TNTN
Mostly matrix multiplicationsyesnoyes
Dao & Gu (2024), with head dimension equal to the state size NN. The SSD layer was 2–8 times faster than Mamba's selective scan, allowed states about 8 times larger, and overtook FlashAttention-2 beyond sequences of about 2,000 tokens. The price is a scalar decay per head instead of a diagonal matrix: slightly less expressive, much more hardware-friendly.

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 Δ\Delta, BB and CC functions of the token; with N=1N=1, A=−1A=-1, B=1B=1 it is exactly the gated RNN ht=(1−gt)ht−1+gtxth_t=(1-g_t)h_{t-1}+g_tx_t with gt=σ(zt)g_t=\sigma(z_t): a large step resets and writes, a small one holds and ignores.
  • The selective scan is exact and linear in LL; kernel fusion keeps the NN-times-larger states in SRAM, a parallel scan removes the sequential bottleneck, and recomputation removes the activation memory.
  • Any SSM is multiplication by an NN-semiseparable matrix; with scalar decay it is masked linear attention, (L∘CB⊤)x(L\circ CB^\top)\mathbf x, and Mamba-2 computes it in chunks with matrix multiplications, O(TN2)\order{TN^2} work and O(TN)\order{TN} memory.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can a linear time-invariant layer not solve selective copying, even with many channels?

  1. Its state is too small to hold several tokens
  2. 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
  3. It cannot represent long kernels
  4. 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 yT=∑kKkxT−ky_T=\sum_kK_kx_{T-k}, and channels combined linearly form one kernel. When marked tokens and filler can occupy the same positions, KK would have to be 11 and 00 at the same lag. Making Δ\Delta, BB and CC depend on xtx_t removes the obstruction.

Question 2

In a selective SSM, a token produces a very large step size Δt\Delta_t. What happens to the state?

  1. It is held unchanged and the token is ignored
  2. It grows without bound
  3. It oscillates
  4. It is reset and the token is written in, since Aˉt→0\bar A_t\to0 and the input map takes over
Show the answer

D. It is reset and the token is written in, since Aˉt→0\bar A_t\to0 and the input map takes over

For a stable AA, eΔtA→0e^{\Delta_tA}\to0 as Δt→∞\Delta_t\to\infty, so the old state is erased, while Bˉt=(ΔtA)−1(eΔtA−I)ΔtBt→−A−1Bt\bar B_t=(\Delta_tA)^{-1}(e^{\Delta_tA}-I)\Delta_tB_t\to-A^{-1}B_t, which writes the token. In the gating theorem this is gt→1g_t\to1.

Question 3

What does Mamba's fused selective-scan kernel avoid, compared with a straightforward implementation?

  1. Writing the (B,L,D,N)(B,L,D,N) tensor of states to HBM and storing it for the backward pass
  2. Any computation that grows with the sequence length
  3. The discretization step, which it skips
  4. Sequential dependence between tokens, by approximating the recurrence with a convolution
Show the answer

A. Writing the (B,L,D,N)(B,L,D,N) tensor of states to HBM and storing it for the backward pass

The kernel keeps the expanded states in SRAM, writes only the (B,L,D)(B,L,D) outputs, and recomputes the states in the backward pass. The computation stays exact and linear in LL; what shrinks is the memory traffic and the activation memory.

Question 4

In a scalar-decay SSM, M=L∘(CBˉ⊤)M=L\circ(C\bar B^\top) with Lji=aj⋯ai+1L_{ji}=a_j\cdots a_{i+1} for j≥ij\ge i. If at=1a_t=1 for every tt, what is the layer?

  1. Softmax attention with a causal mask
  2. An LTI convolution with an exponentially decaying kernel
  3. Causal linear attention, yj=∑i≤j(Cj⊤Bˉi) xiy_j=\sum_{i\le j}(C_j^\top\bar B_i)\,x_i, with queries CC and keys Bˉ\bar B
  4. The identity map
Show the answer

C. Causal linear attention, yj=∑i≤j(Cj⊤Bˉi) xiy_j=\sum_{i\le j}(C_j^\top\bar B_i)\,x_i, with queries CC and keys Bˉ\bar B

With all at=1a_t=1 the mask LL is the lower-triangular matrix of ones, the causal mask, and MM is the unnormalized causal attention matrix CB⊤CB^\top without a softmax. Decays at<1a_t<1 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).