Mamba: Linear-Time Sequence Modeling with Selective State Spaces
- Publication
- COLM 2024Conference
- First submitted to arXiv
- arXiv:2312.00752
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{mambamamba2023,
title = {{Mamba: Linear-Time Sequence Modeling with Selective State Spaces}},
author = {Albert Gu and Tri Dao},
year = {2023},
eprint = {2312.00752},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2312.00752}
}
To read this paper, we put in quite a bit of effort.
First, we had to review the author's past works:
Next, we had to understand the main comparison target of this paper, which is the advantages and disadvantages of the Transformer.
At this point, we assume you’ve already read the previous papers and possess sufficient background knowledge.
Now, let’s dive into this paper.
Defining the Problem
Do you remember what S4 did?
S4 continues the previous research on SSMs, significantly reducing computational complexity and memory requirements through reparameterization of the state matrix and frequency-domain generating function calculations, while maintaining numerical stability.
The SSM core of S4 is linear time-invariant (LTI): it uses the same and step size across time. The full deep S4 network, with nonlinearities and channel mixing, is not a linear system.
For example, consider the following Copying problem: the input is a sequence, and the output requires copying a "part of the information" from that sequence:
In the left diagram, if there is a fixed time gap between the input and output, this problem is very simple for an LTI model, because it only needs to learn a fixed shift or convolution kernel.
But in the right diagram, when there are random time intervals between the input and output and the model needs to be "content-aware," the model must distinguish which tokens need to be copied and which are irrelevant or noisy. At this point, the model needs to have "selective" capabilities.
Self-attention computes content-dependent attention weights, whereas an LTI core uses fixed interactions across positions. The change here concerns input-conditioned coefficients, not retraining model weights for each token during inference.
Therefore, the authors believe that a way must be found to make several key parameters of the SSM (such as , , ) "input-dependent," meaning these parameters will change over time steps rather than remaining fixed.
Solving the Problem
Selective Mechanism
First, let's see how the author improved the core algorithm of the SSM to enable the model with "selectivity."
Start with Algorithm 1 (S4):
Algorithm 1 SSM (S4)
Input: x : (B, L, D)
Output: y : (B, L, D)
1: A : (D, N) ← Parameter ⊲ Represents structured N×N matrix
2: B : (D, N) ← Parameter
3: C : (D, N) ← Parameter
4: Δ : (D) ← τΔ(Parameter)
5: A_bar, B_bar : (D, N) ← discretize(Δ, A, B)
6: y ← SSM(A_bar, B_bar, C) (x) ⊲ Time-invariant: recurrence or convolution
7: return y
-
(Step 1–3) Parameter Initialization
The model has three core parameters: .
can be viewed as a structured matrix, but in practice, it is often diagonalized or uses other special structures to save on parameters, stored in the shape of .
-
(Step 4) Setting
is a positive step size per channel. Softplus maps a real parameter to positive values.
-
(Step 5) Discretization
The function
discretize(Δ, A, B)discretizes the continuous system parameters and through exponential matrix operations and other discretization steps based on , resulting in in discrete time.Since both and are time-invariant, the discretized remain fixed.
-
(Step 6) SSM Computation
Since (A, B, C) do not change across sequence positions, the computation can use a fixed convolution (global convolution) or linear recurrence:
- Using convolution, the entire sequence can be processed at once in parallel, making training highly efficient.
- For autoregressive inference, it can switch back to recursive mode to process step-by-step.
From the above, we can see that S4 retains the "linear time-invariant (LTI)" property, allowing most SSMs to be accelerated using convolution kernels, avoiding explicit expansion of the entire hidden state tensor, thus achieving high efficiency in practice.
Now, let's look at Algorithm 2 (S6).
Here depend on . A single fixed convolution kernel is no longer equivalent, but a recurrence remains valid with position-dependent coefficients. The authors compute that recurrence efficiently with a scan.
Algorithm 2 SSM + Selection (S6)
Input: x : (B, L, D)
Output: y : (B, L, D)
1: A : (D, N) ← Parameter ⊲ Represents structured N×N matrix
2: B : (B, L, N) ← sB(x)
3: C : (B, L, N) ← sC(x)
4: Δ : (B, L, D) ← τΔ(Parameter + sΔ(x))
5: A_bar, B_bar : (B, L, D, N) ← discretize(Δ, A, B)
6: y ← SSM(A_bar, B_bar, C) (x) ⊲ Time-varying: recurrence (scan) only
7: return y
-
(Step 1) Structure of
Like S4, a structured matrix is still needed for , but the other parts () will change over time steps or sequence positions.
-
(Step 2–3) Input-dependent
Here, and are no longer fixed shapes but correspond to , meaning that for each batch and each sequence position, there is a different set of parameter values.
- The paper uses linear projections to dimensions for and , with outputs shared/broadcast across channels. The symbol in tensor shapes means batch size, distinct from the input coefficient matrix .
-
(Step 4) Input-dependent
Compute first, add a learned bias, then apply softplus to obtain positive steps of shape . The bias is not added to before applying . The paper also expands a low-dimensional projection to channels to control parameter count.
-
(Step 5) Discretization
Since each time step of is different, during discretization, must be computed separately for each position.
At this point, will have the shape .
-
(Step 6) Recursive Scan
Because the parameters are "time-varying," a fixed convolution kernel can no longer be used for the entire sequence. Instead, the state must be updated step-by-step or in parallel using a "scan" approach.
S6 Architecture
In deep learning, common efficient fundamental operations include convolution and attention. These operations leverage mature implementation libraries and parallelization strategies on GPUs to fully harness hardware computational potential.
Selective SSMs lose the existing efficient fixed-convolution route. Recurrence itself does not prevent GPU acceleration. The problem is how to parallelize updates without repeatedly moving a huge intermediate state tensor.
Therefore, to generalize SSM, a hardware-oriented algorithm must be developed to ensure that SSM performs well on GPUs.
To achieve this goal, the author proposes the selective scan hardware-oriented algorithm. The core idea is to cleverly expand only the necessary intermediate states in the GPU memory hierarchy and use parallel scan and recomputation techniques to reduce the read/write operations on High Bandwidth Memory (HBM).
With an understanding of the GPU architecture, let’s look at the overall architecture diagram:
In the diagram, the author provides an example of a 5-channel SSM model, where each channel has a 4-dimensional hidden state. If we were to expand it directly, the model’s state space would be , multiplied by batch size and sequence length , which would become massive. Therefore, during the intermediate state exchange step, the selective scan algorithm is used, expanding only when necessary.
As shown in the diagram, the parameters () are first loaded from HBM to faster SRAM. Then, discretization and recursive updates (scan) are performed in SRAM.
Finally, the result is written back to HBM. The computation kernels, which were originally separate, are merged into one or a few kernels to reduce repeated read/write operations on HBM.
Backpropagation needs forward information, but the full state history need not be stored in HBM. The method retains required inputs and smaller intermediates, then recomputes states that are costly to store. Long sequences are processed in chunks rather than fitting everything into SRAM at once.
When backward pass occurs, the original input and parameters are reloaded from HBM, and the forward computation is recomputed to obtain the intermediate states. This recomputation technique increases computational overhead but drastically reduces memory requirements, leading to greater overall efficiency.
Thus, selective SSM retains input-dependence flexibility while utilizing GPU hardware features for higher throughput and lower resource usage, making recursive models more feasible for large-scale applications.
Mamba Architecture
The traditional H3 architecture is a common variant of SSM, where each block contains an interleaved stack of parts resembling "linear attention" along with an MLP (multi-layer perceptron). Here, the authors choose to combine these two components into a single unit, then repeat it multiple times within the network to achieve a more streamlined and scalable design (similar to the simplification of attention in GAU).
Each Mamba block expands width to . Main projections contain approximately parameters: for two input branches and for output projection. SSM parameters and the short convolution are additional, usually smaller contributions.
With , two Mamba blocks have approximately main-projection parameters, comparable to one Transformer MHA-plus-MLP unit. This matches block-level parameter counts; the complete language model is not limited to two layers.
Additionally, to make the "Gated MLP" closer to the popular SwiGLU variant, the authors use SiLU (Swish) as the activation function. Inspired by RetNet (which places normalization layers in similar positions), they also introduce an optional layer normalization (LayerNorm), ultimately forming the complete "Mamba" architecture.
The data flow is: project into two branches; one passes through a short causal depthwise convolution, SiLU and the selective SSM, while the other supplies a SiLU multiplicative gate. Combine them, project the output, and use residual connections and normalization. Removing a separate Transformer MLP block does not remove linear layers or nonlinear operations.
Revisiting the Selective Mechanism
At the end of the methodology, the authors discuss the role and impact of the "selective mechanism" in SSM:
-
Interpretation of the "Selective" Parameters
-
Meaning of : With stable having negative real parts, larger steps make decay the old state more strongly; small steps approach retention. For the ZOH case and , the new-input gate is . This is a conditional gating correspondence, not a reset guarantee for arbitrary matrices.
-
Relationship between and : Although can be set to "change with input," the authors note that the main selectivity is still driven by , since is influenced by during discretization (). As long as can selectively increase or decrease, it significantly impacts the dynamics of the entire model.
-
Meaning of and : controls writing input into state, while controls reading from state. Selective changes the readout, not whether is written into memory.
-
-
Generality of the Selective Mechanism
The "selective mechanism" can be applied in many contexts, including traditional RNNs or CNNs. It can be applied to different parameters (such as in Algorithm 2) and even implemented through various input transformation functions . This suggests that the "selective mechanism" is not limited to a specific model but is a broad concept in the entire sequence modeling domain.
-
Connection to RNN Gating Mechanisms
The authors emphasize that common RNN gating mechanisms (such as the input gate and forget gate in LSTM, and update gate in GRU) can be considered specific instances of a "selective mechanism."
-
Three Key Effects of the Selective Mechanism
The authors summarize the impact of the "selective mechanism" into three important "forces":
-
(a) Variable Spacing: Reduce irrelevant tokens’ effects on memory to handle varying gaps between useful inputs. This does not skip the actual computation at those positions or require physical timestamps for text.
-
(b) Filtering Context: Discarding irrelevant history can make added context more useful.
-
(c) Boundary Resetting: Appropriate dynamics can learn to suppress old state near boundaries. If separate samples require strict isolation, explicitly reset state; a learned gate is not a guaranteed data boundary.
-
Training Methods and Protocols
The authors use the Pile dataset for pretraining, which is a large corpus commonly used for language models, and they employ a training recipe similar to that of GPT-3 (e.g., using corresponding depths and widths).
-
Model Comparison
-
Transformer (GPT3 Architecture): This is the traditional, standard Transformer-based GPT3-style language model with multi-head attention.
-
Transformer++: The authors specifically mention this as "the most powerful Transformer recipe known to date," combining best practices from models like PaLM and LLaMa, including:
- Rotary embedding
- SwiGLU MLP
- RMSNorm (replacing LayerNorm)
- No linear bias
- Higher learning rates
-
Other Subquadratic Architectures: Several recently proposed models that aim to reduce the computational cost or offer more scalability than attention, such as RWKV and RetNet, are also included in the comparison.
-
-
Experimental Methods and Results
- Chinchilla Protocol: The authors follow the "Chinchilla" scaling protocol for models from ≈125M to ≈1.3B parameters. They increase training tokens roughly in proportion to model size, then compare perplexity against training computation across architectures.
Discussion
Scaling Laws
These are compute-scaling comparisons: the horizontal axis is training FLOPs, with separate plots for context lengths 2048 and 8192. It is not a sequence-length axis. For roughly 125M–1.3B models, Mamba approaches Transformer++ under the tested budgets and contexts.
The authors present this as an important advance for attention-free linear-time models. Complete 8k results for RWKV and RetNet are missing because of implementation efficiency, memory or computation limits.
Comparison with Other Language Models
The authors selected multiple well-known zero-shot downstream tasks, including knowledge reasoning, commonsense question answering, and cloze tests, for comparison with models like Pythia and RWKV.
In the table's comparisons at nearby parameter counts, Mamba leads on the listed average accuracy. For example, Mamba-2.8B averages 63.3%, versus 59.1% for Pythia-2.8B and 61.7% even for Pythia-6.9B. This supports better "parameter efficiency" under these evaluation conditions.
Overall, Mamba not only has the potential to match enhanced Transformer models in pretraining perplexity and scaling laws but also outperforms open-source models of the same size on several zero-shot tasks, demonstrating its strong competitiveness in language modeling.
Inference Efficiency Comparison
The authors compare the scan operation's training-time runtime and the complete Mamba model's inference throughput. The two panels measure different things.
Core-operation benchmarks use an A100 80GB PCIe GPU, BF16, batch 1, . Selective scan beats FlashAttention-2 beyond about 2K in that setup. The 20–40-fold gain is against the authors’ unfused PyTorch parallel scan, not FlashAttention-2 or a complete model.
Autoregressive inference avoids a KV cache that grows with history length, but still stores each layer’s SSM state and short-convolution state. For fixed model and batch size, these do not grow with generated length, helping support larger batches.
End-to-end tests use a 2048-token prompt, generate 128 tokens and vary batch size to measure tokens/s. The 6.9B Mamba is about 5.3 times larger than the 1.3B Transformer, yet can have higher throughput. That 6.9B Mamba is an untrained speed-test model, so no quality conclusion follows. The roughly 4–5-fold same-scale throughput advantage is specific to these implementations and settings, not a universal single-request latency reduction.
Training memory and decoding cache are different metrics. In Appendix E.5’s 125M training benchmarks, Mamba is comparable to the optimized FlashAttention-2 Transformer and slightly higher in the listed measurements. It is not universally more memory-efficient at every stage.
Ablation Study - Selective Mechanism
The authors compare architectures and their inner SSM layers in roughly 350M-parameter language models. For the previous non-selective (LTI) SSMs, which are equivalent to global convolutions, the complex and real S4 variants have similar perplexities within each architecture: 10.30 versus 10.34 in H3 and 10.54 versus 10.56 in Mamba. In this setting, using real values does not markedly reduce quality and may help hardware efficiency.
However, when the LTI SSM is replaced with a selective SSM (S6), performance improves significantly. The authors further note that with selective SSM, the performance of Mamba and H3 architectures is very similar.
Ablation Study - Key Parameters
Next, the authors compare which of , , and depend on the input. From the 10.93 perplexity baseline, selecting only reaches 9.81, a larger improvement than selecting only (10.15) or only (9.98). Selecting all three reaches 8.71. This fits the paper's conditional connection between and an RNN gate and shows an additional gain from combining the parameters.
Ablation Study - Other Settings
The authors also explore different initializations for the SSM (especially real or complex numbers) and point out that in language model environments, real-valued diagonal initializations are generally more ideal than complex-valued ones. Even random initializations yield good results, indicating that the model is not heavily reliant on special complex initializations for stability or better convergence.
Finally, the authors stress that with selective , increasing the state size from 1 to 16 improves perplexity from 9.73 to 8.71 while parameters rise from 367.1M to 371.5M, about 1.2%. With fixed , the corresponding improvement is only 9.88 to 9.81. This supports their point that state size matters more when it works with selection:
With the right selection mechanism and hardware-aware algorithm, increasing the state size can strengthen modeling without a comparably large increase in parameter count.
Scan computation and inference state still grow with ; the small parameter increase does not make compute and memory free.
Conclusion
In this paper, the authors completely discard the attention mechanism and propose a solution using a "selective mechanism + state-space model": Mamba.
Across the tested language, audio, and genomics tasks, Mamba can match or exceed strong Transformer baselines while offering faster inference in the measured settings. Selection is not best for every kind of data: Appendix E.4.1 shows long audio-waveform settings benefiting from LTI and complex-valued SSMs. The language-quality evaluation does not cover much larger models.
The authors hope that Mamba will become the backbone of general sequence models and play an even larger role in ultra-long-sequence tasks such as genomics, audio, and vision in the future.