Skip to content

Mamba: Linear-Time Sequence Modeling with Selective State Spaces

Pretraining stage 2 #7corefundamentalpaperrubric 12/122023 · ~60 min

Albert Gu, Tri Dao

Status

TL;DR. Classic state space models (S4 and its relatives) use fixed dynamics, so they cannot choose what to remember. Mamba makes the step size Δ\Delta and the matrices BB and CC depend on the current token. The resulting S6 layer is an input-gated recurrence. It loses the convolution trick, so the authors write a hardware-aware parallel scan that keeps the large state in GPU SRAM. The result trains in linear time, decodes with a fixed-size state, and was the first attention-free model to match a strong Transformer recipe on language up to about 3B parameters.

Why it matters now. Hybrid models such as Nemotron-H replace most attention layers with Mamba layers to cut long-context cost. Linear recurrent layers like Gated DeltaNet build directly on Mamba. For IR, long documents and long agent traces are where attention’s quadratic cost and KV cache hurt most, so you need to know what a recurrent layer can and cannot remember.

Continuous SSM, discretised. A state space model maps input xtx_t to output yty_t through a hidden state ht∈RNh_t \in \mathbb{R}^N per channel. With zero-order hold,

Aˉ=exp⁡(ΔA),Bˉ=(ΔA)−1(exp⁡(ΔA)−I) ΔB,\bar A = \exp(\Delta A), \qquad \bar B = (\Delta A)^{-1}\big(\exp(\Delta A) - I\big)\,\Delta B, ht=Aˉ ht−1+Bˉ xt,yt=C ht.h_t = \bar A\, h_{t-1} + \bar B\, x_t, \qquad y_t = C\, h_t .

Selection (S6). S4 keeps Δ,A,B,C\Delta, A, B, C fixed over time, so the model is linear time invariant and can be computed as a convolution. Mamba sets

Bt=LinearN(xt),Ct=LinearN(xt),Δt=softplus(θ+BroadcastD(Linear1(xt))).B_t = \mathrm{Linear}_N(x_t),\quad C_t = \mathrm{Linear}_N(x_t),\quad \Delta_t = \mathrm{softplus}\big(\theta + \mathrm{Broadcast}_D(\mathrm{Linear}_1(x_t))\big).

A large Δt\Delta_t resets the state toward the current input. A small Δt\Delta_t ignores the input and keeps the state. With N=1N=1, A=−1A=-1, B=1B=1, this reduces exactly to a gated RNN, ht=(1−gt)ht−1+gtxth_t = (1-g_t)h_{t-1} + g_t x_t with gt=σ(Linear(xt))g_t=\sigma(\mathrm{Linear}(x_t)) (Theorem 1).

Selective scan. Time-varying parameters mean no fixed convolution kernel. The update ht=atht−1+bth_t = a_t h_{t-1} + b_t is still a composition of affine maps, and the operator (a1,b1)∘(a2,b2)=(a1a2,  a2b1+b2)(a_1,b_1)\circ(a_2,b_2)=(a_1a_2,\;a_2b_1+b_2) is associative. A parallel scan therefore runs in O(L)O(L) work and O(log⁡L)O(\log L) depth. The kernel loads Δ,A,B,C\Delta, A, B, C into SRAM, discretises and scans there, and writes only yy of shape (B,L,D)(B,L,D) to HBM. It never writes the NN-times-larger state, and it recomputes states in the backward pass.

Block. One homogeneous block merges the H3-style SSM path with a gated MLP (expansion E=2E=2), and the network stacks these blocks with no attention and no separate MLP.

Mamba selective scan: input-dependent recurrence computed inside fast GPU memory Top: each input x_t is projected to a step size delta_t and to B_t and C_t. These set the discretised transition A-bar_t and input matrix B-bar_t, so a chain of hidden states h_t equals A-bar_t times h_t-1 plus B-bar_t times x_t, and the output y_t equals C_t times h_t. Large delta resets the state toward the current input; small delta keeps the old state. Bottom: the GPU kernel reads delta, A, B, C from high-bandwidth memory into on-chip SRAM, discretises and runs a parallel scan there, and writes only the outputs y back. The expanded states are never written to HBM and are recomputed in the backward pass. Selective SSM: Δ, B, C depend on the token; the scan stays in SRAM hₜ₋₁ hₜ hₜ₊₁ × Āₜ = exp(Δₜ A) × Āₜ₊₁ xₜ → Δₜ, Bₜ, Cₜ (linear maps of the token) + B̄ₜ xₜ yₜ = Cₜ hₜ large Δ: forget, take xₜ small Δ: keep hₜ₋₁, ignore xₜ HBM (large, slow) read Δ, A, B, C, x write y only: (B, L, D) SRAM (small, fast) discretise → parallel scan states (B, L, D, N) live here recomputed in backward pass inputs in outputs out
Original sketch. The input sets Δ, B and C at each step, so the recurrence chooses what to keep. Training runs a parallel scan in SRAM and writes only the outputs back to HBM.
  • Synthetic tasks (§4.1). It solves selective copying, and on induction heads it extrapolates from training length 256 to 2202^{20} tokens (4000× its training length), while no other method generalises beyond 2×.
  • Scaling (§4.2.1). It is the first attention-free model to match the Transformer++ recipe in perplexity scaling from 125M to 1.3B.
  • Zero-shot (§4.2.2, Table 1, 300B Pile tokens). Mamba-2.8B averages 63.3 against Pythia-6.9B 61.7, GPT-J-6B 63.0 and RWKV-7.4B 62.5, with LAMBADA perplexity 4.23. Mamba-1.4B averages 59.7 against Pythia-1.4B 55.2.
  • Other modalities (§4.3–4.4). It beats prior models on DNA and audio, with quality improving up to million-length sequences.
  • Speed (§4.5). The scan beats FlashAttention-2 beyond 2K tokens and is 20–40× faster than a PyTorch scan. Inference throughput is 4–5× a Transformer’s.
  • Ablations (§4.6). S6 rather than S4 is what helps (perplexity 8.69 against 10.56 in the Mamba block). Selective Δ\Delta is the most important single parameter.
  • Models are only tested up to about 3B parameters. Whether SSMs support fine-tuning, in-context learning and RLHF as well as Transformers is left open (§5).
  • Selection helps discrete data such as text and DNA but can hurt continuous signals. The paper describes this as a continuous–discrete trade-off.
  • A fixed-size state cannot store an arbitrarily long context exactly. Later work shows that pure recurrent models lag attention on recall-heavy tasks, which motivates hybrids and the delta rule.
  • Custom CUDA kernels make the model harder to modify and port than a standard attention layer.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    Take a selective SSM with N = 1, A = −1, B = 1 and step size Δ = softplus(z), where z is a linear function of the input. Using zero-order-hold discretisation, show that the recurrence becomes the gated update h_t = (1 − g_t)·h_(t−1) + g_t·x_t with g_t = sigmoid(z). Then say what the model does with the input when z = 3 and when z = −3.

    What a strong answer covers
    • ZOH gives A-bar = exp(ΔA) = exp(−Δ). B-bar = (ΔA)^(−1)(exp(ΔA) − 1)·ΔB = (−Δ)^(−1)(exp(−Δ) − 1)·Δ = 1 − exp(−Δ).
    • exp(−softplus(z)) = 1/(1 + e^z) = 1 − sigmoid(z). So A-bar = 1 − g_t and B-bar = g_t with g_t = sigmoid(z). This is Theorem 1 of the paper.
    • z = 3: g ≈ 0.953. The state is mostly reset and replaced by the current input, which corresponds to a large Δ.
    • z = −3: g ≈ 0.047. The input is mostly ignored and the state carries on, which corresponds to a small Δ.
    • This is the classic RNN gate. Selection turns the SSM step size into an input-dependent forget/write gate.
  2. Derive / compute

    Show that the recurrence h_t = a_t·h_(t−1) + b_t can be computed with a parallel scan, by defining an operator on pairs (a, b) and proving it is associative. Then compare the decoding-state memory of a hypothetical 48-layer Mamba (D = 2048, E = 2, N = 16) with the KV cache of a 48-layer, d = 2048 multi-head-attention Transformer at 32K tokens, in bf16.

    What a strong answer covers
    • Operator: (a1, b1) ∘ (a2, b2) = (a1·a2, a2·b1 + b2). This composes the step "multiply by a1, add b1" with the step "multiply by a2, add b2".
    • Associativity: both groupings of three elements give (a1·a2·a3, a3·a2·b1 + a3·b2 + b3). A Blelloch-style scan then needs O(L) work and O(log L) depth.
    • Mamba state per layer: E·D·N = 4096 × 16 = 65,536 values. Over 48 layers that is about 3.1M values, about 6.3 MB per sequence, fixed regardless of length (ignoring the small convolution state).
    • Transformer KV cache per token: 2 × 48 × 2048 × 2 bytes ≈ 0.39 MB. At 32K tokens that is about 12.9 GB per sequence, about 2,000 times more than the Mamba state. With GQA at 4× fewer KV heads it is still about 3.2 GB.
    • The Mamba state holds about as many bytes as roughly 16 tokens of KV cache. That is the compression that gives fast decoding, and also the reason exact recall is hard.
  3. Mechanism

    Explain why making B, C and Δ functions of the input removes the convolution view of S4-style SSMs, and how Mamba's selective scan keeps training fast anyway. Cover what is stored in fast SRAM versus slow HBM, and what is recomputed in the backward pass.

    What a strong answer covers
    • LTI SSMs use the same A-bar and B-bar at every step, so the output is a convolution with a fixed kernel. That kernel can be computed once and applied with FFTs.
    • With input-dependent Δ, B and C, each step has different matrices. There is no single kernel, so the model must be computed as a recurrence or a scan.
    • A naive scan would materialise the state of shape (B, L, D, N) in HBM, N times larger than the input.
    • The kernel loads Δ, A, B and C into SRAM, discretises and runs the parallel scan there, and writes only the output y of shape (B, L, D) back to HBM.
    • Intermediate states are not saved. They are recomputed in the backward pass, as in FlashAttention. The scan is faster than FlashAttention-2 beyond about 2K tokens and 20–40× faster than a standard PyTorch scan.
  4. What if…

    Using the ablations in §4.6 (about 350M models), argue which ingredient of Mamba matters most: the block design, the selective SSM, which parameters are selective, or the initialisation of A.

    What a strong answer covers
    • The SSM matters more than the block. H3 with S4 gives perplexity 10.30 and H3 with S6 gives 8.95. The Mamba block with S4 gives 10.56 and with S6 gives 8.69.
    • Selective parameters: none 10.93, B only 10.15, C only 9.98, Δ only 9.81, all three 8.71. Δ alone helps most, consistent with its gating role.
    • Initialisation of A matters little among real-valued choices (S4D-Real 8.71, random 8.71, real −1/2 8.85). Complex-valued A is worse on text (9.16).
    • Conclusion: input-dependent selection, especially of Δ, drives the gains. The simplified block is a convenience rather than the key.
  5. Critique

    Mamba matches Transformer++ on perplexity and common-sense benchmarks up to about 3B parameters. Critique whether this means a pure SSM can replace attention in a retrieval-augmented LLM that must quote exact passages from a long context.

    What a strong answer covers
    • The state has a fixed size, so the model must compress the context. Exact copying of arbitrary spans from far back cannot be guaranteed once the context holds more information than the state.
    • Later evidence: on recall-heavy tasks in the Gated DeltaNet paper (Table 4), Mamba2 averages 29.8 against 37.0 for Transformer++, and hybrids with attention do best.
    • Mamba's synthetic wins (induction heads extrapolating from 256 to about 1M tokens) test a narrow, single-key recall pattern, not multi-passage retrieval.
    • Scale is limited to about 3B in the paper. Fine-tuning and RLHF behaviour were not studied.
    • Practical answer: use hybrids that keep a few attention layers, such as Nemotron-H, which replaces most but not all attention layers with Mamba layers.
  6. Design

    With one academic 8-GPU node, you want a reranker or embedding model for 32K-token scientific documents. Design an experiment comparing a Transformer, a pure Mamba model and a hybrid at the same parameter count. Include the metrics and the failure mode you expect for each.

    What a strong answer covers
    • Backbones: matched parameter counts (for example 1B). The hybrid uses about one attention layer in every few layers. Use the same pretraining data if training from scratch, or the same continued-pretraining budget.
    • Tasks: long-document reranking (nDCG@10 on queries whose evidence sits at different positions) and embedding for long-document retrieval.
    • Efficiency metrics: throughput, peak memory at 8K, 16K and 32K, and decoding or encoding cost.
    • Expected failure modes: the Transformer runs out of memory or slows at 32K. Pure Mamba loses evidence that appears early and is needed late, and handles exact term matching poorly. The hybrid should be close to the Transformer at lower cost.
    • Diagnostics: measure accuracy by evidence position, as in lost-in-the-middle, and test synthetic needle retrieval at the exact sequence length.

Done with this page?

Status