AI State of the Art
SOTA/Post-Transformer Architectures/25 min
Section 66

Mamba: Selective State Spaces

Listen as a podcast β†’

The problem S4 can't solve

Imagine this simple test: you're given the sequence a1 b2 c3 COPY 2, and you need to answer b.

A human understands instantly: "COPY 2" means copy the second element of the list. To do this, you need to decide in real time which information to store in memory, the number 2 retroactively changes the importance of each previous element.

S4, however, applies the same fixed filter to every token, without considering the content. It can't "understand" that the word COPY changes the game. S4 excels on music, time series, regular signals, but it fails on this kind of task where the context changes the rules.

That's the problem Mamba solves.

Mamba: Linear-Time Sequence Modeling with Selective State Spaces

Time-invariant SSMs: their fundamental limitation

S4 is an LTI (Linear Time-Invariant) system, meaning the same matrices A, B, C apply at every time step, regardless of the input content. "Time-invariant" means these matrices are fixed once trained. Every token passes through the same filter, regardless of its meaning in context.

The most telling analogy: it's an audio amplifier with a fixed volume. Whether the music is soft or loud, whether the passage is a crucial violin solo or a silence between movements, the filter treats everything the same way. There's no way to "turn up the volume" when something important comes along.

Selectivity as an intelligent compression mechanism

The fundamental idea behind Mamba: selectivity in SSMs is analogous to the forget gate (a "valve" that doses what passes through) of the LSTM (Long Short-Term Memory, the gated recurrent network that dominated the 2010s). It allows the model to dynamically decide, at each token, what to store in its hidden state and what to ignore. An important keyword? Engrave it in memory. A predictable function word? Let it pass without cluttering the state. It's adaptive rather than uniform compression.

The Mamba architecture: making parameters input-dependent

The big idea behind Mamba, published by Albert Gu and Tri Dao in December 2023, is simple to state: make certain SSM parameters dependent on the current token. Instead of a fixed filter, the model adjusts its behavior at each time step based on what it sees.

The three selective parameters

Delta (the discretization step): this is the most intuitive parameter. It controls how fast the state evolves. A large delta = the model gives a lot of importance to the current token and "forgets" the past quickly. A small delta = the model preserves its current state and ignores the input. It's the slider between "absorb" and "ignore."

Ξ”=softplus(Linear(x))\Delta = \text{softplus}(\text{Linear}(x))

The softplus function (log⁑(1+ex)\log(1 + e^x)) guarantees that Ξ”>0\Delta > 0: a negative time step has no physical meaning, it's a "duration," always positive.

B (input matrix, write gate): controls what to write into the hidden state. In the recurrence equation, B multiplies the input xkx_k to determine how the current token modifies the state. Each token can influence the state differently.

B=Linear(x)B = \text{Linear}(x)

C (output matrix, read gate): controls what to read from the hidden state. In the recurrence equation, C multiplies the state hkh_k to determine which information to extract to the output. Each token can "read" the state differently.

C=Linear(x)C = \text{Linear}(x)

Although B and C have the same form (linear projection of xx), they play opposite roles: B is the write gate (input -> state) while C is the read gate (state -> output). They are applied at different places in the recurrence equation and learn distinct weights.

These three projections are computed from the current token x, hence the name "selectivity." The model adapts its filter at each position.

One important clarification to avoid getting lost. In S4, B and C were learned parameters: matrices frozen after training, identical for any text. In Mamba, what is learned are the projection weights hidden behind each "Linear"; the values of Ξ”\Delta, B and C are recomputed for every token from those weights, they are intermediate results, not parameters. As for matrix A, it remains a fixed learned parameter, just as in S4: it is only through Ξ”\Delta, which varies from token to token, that its effect becomes content-dependent.

Diagram of Mamba selective SSM: the input token x_t goes through a projection (the selection mechanism) that produces B_t, C_t and Delta_t; Delta_t discretizes matrix A; state h_(t-1) is updated into h_t and read out to y_t; a pyramid indicates the computation stays in GPU SRAM rather than HBM.
The figure from the Mamba paper. Bottom left, the blue projection is the selection mechanism: the current token x_t itself produces B_t, C_t and Delta_t. Those parameters are therefore no longer frozen, unlike in S4. The small pyramid bottom right is the other half of the idea: all of this computation is kept in the GPU SRAM.Source : Mamba paper (Gu & Dao, figure 1), via Aman's AI Journal
Connection with LSTM

When delta tends toward infinity, the model completely ignores the previous state and only sees the current token, like a fully open forget gate. When delta tends toward 0, it ignores the token and preserves its state intact, fully closed forget gate. This is exactly the behavior of the LSTM forget gate, but operating in a continuous, high-dimensional state space rather than on a discrete vector.

The technical problem: how to parallelize without FFT?

Selectivity has a major technical cost. S4 could speed up via the FFT (the Fast Fourier Transform, explained in the S4 lesson) because its convolution kernel was fixed for the entire sequence, one kernel, one FFT. With Mamba, the kernel changes at every position (it depends on the token). You can no longer unroll the recurrence into a global convolution.

A time-invariant SSM seen two ways: on top, the convolutional mode used at training time, where the whole sequence is processed in parallel by a single kernel; at the bottom, the recurrent mode used at inference, where the state is updated token by token with the same A bar, B bar and C matrices at every step.
The two faces of a classic SSM like S4: convolutional at training time (fast, parallelizable via FFT), recurrent at inference. Notice that A bar, B bar and C are the same at every time step, that invariance is exactly what makes the FFT possible, and exactly what Mamba gives up.Source : Maarten Grootendorst, A Visual Guide to Mamba and State Space Models

The recurrence becomes:

hk=AΛ‰kβ‹…hkβˆ’1+BΛ‰kβ‹…xkh_k = \bar{A}_k \cdot h_{k-1} + \bar{B}_k \cdot x_k

The "bar" notation designates the discretized versions of A and B: the continuous matrices are transformed into discrete matrices suited for token-by-token processing, recomputed at each step using the current Ξ”k\Delta_k. The exact discretization gives:

AΛ‰k=exp⁑(Ξ”kA),BΛ‰k=(Ξ”kA)βˆ’1(exp⁑(Ξ”kA)βˆ’I)β‹…Ξ”kB\bar{A}_k = \exp(\Delta_k A), \quad \bar{B}_k = (\Delta_k A)^{-1}(\exp(\Delta_k A) - I) \cdot \Delta_k B

The symbols, one by one: Ξ”k\Delta_k is the time step computed for token kk; AA and BB are the continuous matrices (A is learned and fixed, B was just computed from the token); exp⁑\exp is the exponential function, applied here to the matrix Ξ”kA\Delta_k A; II is the identity matrix (the one that changes nothing); the βˆ’1-1 exponent denotes inversion. No need to follow every detail: the essential point is that AΛ‰k\bar{A}_k and BΛ‰k\bar{B}_k are built from the current token's Ξ”k\Delta_k, so they are different at every step. It's an input-dependent recurrence, impossible to reformulate as a simple convolution.

The solution: parallel scan

Mamba uses a parallel associative scan, a parallel algorithmic technique known since the 1980s, originally designed to compute prefix sums on parallel machines.

The key observation: even though h_k depends on h_(k-1), this recurrence is associative, as with addition, you can group the operations however you like without changing the result. It can therefore be cut into independent sub-problems that are recombined afterward. The total work stays proportional to the sequence length L, but the number of steps that must wait for each other drops to log L, about twenty steps for a million tokens. In practice, it's like a tree: you combine pairs, then groups of four, then of eight, until covering the entire sequence.

It's not as fast as S4's FFT, but it's incomparably better than pure sequential recurrence.

Hardware optimizations: Tri Dao's touch

Tri Dao (the same researcher who developed Flash Attention) designed a fused CUDA kernel for Mamba's selective scan: a single small program run directly on the GPU, chaining several operations without going back through memory in between. The philosophy is identical to Flash Attention: minimize memory transfers, not FLOPs (floating-point operations, the count of arithmetic operations performed).

Hardware-aware implementation

Mamba's implementation keeps the hidden state in the GPU's SRAM (Static Random Access Memory, the ultra-fast on-chip memory of a few MB integrated directly into the processors) instead of writing it to HBM (High Bandwidth Memory, the GPU's main memory, much larger, but roughly ten times slower to access). The projections for B, C, and delta are computed in the same kernel, without materializing intermediate states in main memory. Result: the bottleneck shifts from memory bandwidth to pure computation, exactly what you want.

The complete Mamba block

A Mamba block stacks six operations in order:

  1. Linear expansion projection (factor 2, doubles the dimension for more capacity)
  2. Causal 1D convolution (kernel size 4, captures a few tokens of local context)
  3. SiLU activation (smooth non-linear function, similar to GELU)
  4. Selective SSM (Mamba's core, the adaptive recurrence)
  5. Multiplicative gate (a "valve" that controls information flow, like in Gated MLPs, MLP for multi-layer perceptron, the small stack of layers serving as the feed-forward building block)
  6. Projection back to the original dimension
Diagram of a Mamba block: the input splits into two branches, each going through a linear expansion projection; the main branch passes through a 1D convolution, then a SiLU activation, then the selective SSM; the side branch acts as a multiplicative gate after its own SiLU activation; both are combined by a multiplication, then a projection brings the result back to the original dimension.
The six operations described above, drawn out. The left branch does the work (projection, convolution, SiLU, selective SSM), the right branch acts as a valve: it is multiplied with the SSM output to control how much passes through. The whole block is then stacked n times.Source : Maarten Grootendorst, A Visual Guide to Mamba and State Space Models

This architecture draws direct inspiration from the Gated MLP block of modern Transformers (LLaMA, Mistral). The only structural difference: the selective SSM replaces attention.

Performance: Mamba vs Transformers

Quality on language benchmarks

According to the paper, Mamba 3B (3 billion parameters) outperforms same-size Transformers on standard language benchmarks and matches Transformers twice its size. On certain tasks involving long sequences, it surpasses them, its fixed state doesn't suffer from the "lost in the middle" problems of long Transformer contexts.

The major advantage: inference

MetricTransformerMamba
Inference memoryKV cache that grows with LFixed state, regardless of length
Cost per tokenO(L) (reading KV cache)O(1) (fixed state update)
Throughput on long contextDecreases with lengthStays constant
KV cache versus fixed state

A Transformer with a 100,000-token context stores 100,000 key and value vectors per layer, gigabytes of memory that grow with each generated token. Mamba stores a single fixed-size state vector (a few thousand dimensions), whether the context is 100 or 1,000,000 tokens. In theory, Mamba can process infinitely long sequences without any increase in inference memory.

Mamba's limitations

Mamba is not a universal solution. Studies have identified specific weaknesses:

  • Precise recall: retrieving exact information (a name, a date) mentioned 50,000 tokens earlier is difficult, the state compresses information in a lossy way. It's like trying to find an exact sentence in a novel summary: the idea is there, the exact words are not.
  • In-context learning (few-shot): giving 5 examples in the prompt and asking the model to imitate the pattern, Transformers are significantly better, because they "see" the examples directly in their KV cache.
  • Ecosystem: fewer optimized inference tools, fewer pre-trained models, smaller community than the Transformer ecosystem.

Mamba's legacy

Mamba demonstrated something many believed impossible: a model without an attention mechanism can be competitive on large-scale language tasks. Before December 2023, the consensus was that attention was irreplaceable for state-of-the-art NLP.

This impact triggered a wave of innovation: Mamba-2 (faster thanks to SSM-attention unification), Jamba (SSM+attention hybrid at production scale), RWKV-6 (adopting Mamba's selectivity), and applications in genomics, audio, and video.

Mamba in practice

Pre-trained Mamba models up to 2.8B parameters are available as open source. The architecture has been adopted and adapted by many teams, giving rise to Mamba-2 (faster), Jamba (hybrid with attention, 52B parameters), and specialized variants for genomics, long-duration audio, and protein modeling.

Check your understanding0 / 5

1. In Mamba, what is learned during training, and what is recomputed for every token?

2. Why can Mamba no longer use the convolution mode that made S4 so fast to train?

3. What role does the discretization step Ξ”, recomputed for each token, play?

4. At inference time, what is Mamba's decisive advantage over a Transformer?

5. Why does Mamba struggle to retrieve an exact name mentioned 50,000 tokens earlier?