TL;DR
Mamba-2 shows that a state space model whose decay is a single scalar per step is the same thing as a masked attention matrix. The paper calls this state space duality (SSD). Because of that equivalence, the model can be computed as block-sized matrix multiplies, which GPUs run fast. The result is a layer that is 2-8x faster than Mamba's selective scan while keeping language-model quality.
Where you'll see it: the SSD layer inside Mamba-2 models, and the short reference implementation of State Space Duality given in the paper.
The problem
Attention and state space models (SSMs) sit at opposite ends of a trade-off. Attention compares every token with every other token, so training cost grows with the square of the sequence length, and generation keeps a KV Cache that grows with the sequence. An SSM such as Mamba compresses the past into a fixed-size state, so training is linear in length and generation needs constant memory. Mamba had recently matched or beaten Transformers on language modeling, and the two families had been developed largely separately. Mamba's own selective scan also ran on the GPU as a scan that does not use matrix multiplication units, which left it slow beside a well-optimized attention kernel.
The paper asks two questions. Are these families actually related? And can the SSM computation be rearranged so that it uses the hardware that makes attention fast, without giving up linear scaling?
Key idea
Write any SSM over a sequence of length as one matrix acting on the input: , where is a matrix that depends on the model parameters. For the scalar-decay case the paper studies, has two factors. One is an attention-like matrix , built from the input projections. The other is a lower-triangular decay mask , whose entries multiply together the decays between two positions. The whole output is
Here is elementwise multiplication, and each is a scalar between 0 and 1 that depends on the current input. Read as a recurrence, the same output comes from a state that is decayed by and then updated with , read out by . Two ways of computing one object give two algorithms. The recurrence costs time linear in but is a sequence of small operations. The masked matrix product costs time quadratic in but is one large matrix multiply.
The SSD algorithm takes both. It splits the sequence into chunks of length and treats the chunks differently. Inside a chunk it uses the matrix form, which is dense and quick on tensor cores. Between chunks it passes a compact state, which is the recurrent form. Its cost is linear in and almost all of it is matrix multiplication.
The method
The SSD layer
The starting point is the selective SSM from Mamba, with two changes. The state matrix is reduced from diagonal to a scalar times the identity, so each step has one decay number . The head dimension is raised from 1 to a typical value of 64 or 128, similar to conventions for modern Transformers. These changes give up a little expressiveness and buy matrix-multiply efficiency.
Mamba-2 keeps a State Space Model view for generation. Each head carries a state of size , where is the state expansion factor. Training uses the block form.
The block decomposition
Partition into a grid of blocks. The paper shows that the blocks split into two kinds.
- Diagonal blocks. Each one is a small SSM over one chunk, starting from zero state. These are computed with the dense masked-attention form, all chunks in parallel.
- Off-diagonal blocks. Because the mask is semiseparable, every block below the diagonal is low rank. Its rank is at most , so it factors into three pieces: right factors that carry each chunk's inputs into a state, a center factor that is a scalar scan over chunk states, and left factors that read the states out.
The center factor is a scan over chunk states rather than over tokens, so this step is short. The resulting complexity, with , is stated as Theorem 6.1: training FLOPs, inference FLOPs, and inference memory, with the work dominated by matrix multiplications. The paper notes these bounds are tight for this model class.
Reference implementation
Section 6.2 gives a short PyTorch-style routine, with a default block length of 64. Its core is a naive segment-sum helper that builds the log-decay mask, followed by four einsum-style steps: the diagonal block output, the chunk states, a scan of those states across chunks, and the state readout. The paper presents this as a complete implementation in a few lines, which is part of its case that the method is simple to adopt.
The Mamba-2 block
Section 7 changes the block around the SSD layer so that it fits how Transformers are sharded. The A, B, C and X inputs to the SSM are computed in parallel at the start of the block, rather than one after another. This removes a sequential dependency, allows tensor parallelism in the style of Megatron, and cuts synchronization points per block by half, according to the introduction. An extra normalization layer is also added. The authors also map the layer onto multi-head vocabulary: the Mamba block turns out to be a multi-input SSM, analogous to multi-value attention, and the paper compares other head patterns (Section 9.4.2).
Results
All results below are the paper's own numbers. Pile perplexity is validation perplexity, lower is better. Zero-shot accuracy is the average over the seven accuracy benchmarks in Table 8 (LAMBADA, HellaSwag, PIQA, Arc-E, Arc-C, WinoGrande, OpenbookQA).
Speed. Figure 10 compares the SSD kernel with Mamba's fused scan and with FlashAttention-2. At state expansion , SSD is 2-8x faster than the Mamba scan. It allows a state about 8 times larger than Mamba's with little slowdown. SSD is faster than FlashAttention-2 from sequence length 2K, and the introduction states it is 6x faster at 16K. The paper also notes that a whole Mamba-2 model may still be slower to train than a Transformer at 2K, because it has more SSD layers than a Transformer has attention layers.
Scaling. Models from about 125M to 1.3B parameters, trained on the Pile with Chinchilla-style token counts, put Mamba-2 at or ahead of Mamba and a strong Transformer++ recipe on perplexity, FLOPs and wall-clock time (Figure 9).
Downstream. Models were trained on 300B tokens of the Pile with the GPT-NeoX tokenizer, and compared with Pythia models trained on the same data. Selected values from Table 1 and Table 8:
| Model | Pile ppl (lower is better) | Zero-shot avg. (higher is better) |
|---|---|---|
| Mamba-2-1.3B | 6.66 | 56.4 |
| Mamba-1.4B | 6.80 | 56.4 |
| Pythia-1.4B | 7.51 | 51.7 |
| Mamba-2-2.7B | 6.09 | 60.2 |
| Mamba-2.8B | 6.22 | 59.9 |
| Pythia-6.9B | 6.51 | 58.3 |
The introduction says Mamba-2 at 2.7B outperforms Pythia-6.9B on the same data. The table bears that out on perplexity and on average accuracy.
Hybrids. For a 350M model with 48 layers, pure Mamba-2 reaches perplexity 8.60. Adding attention layers helps: 6 attention layers give 8.26, the best of the sweep, and Transformer++ gets 8.68 (Table 2). At 2.7B (Table 3), a model with 6 attention layers at fixed positions reaches 5.95 perplexity and 61.0 average accuracy, against 6.09 and 60.2 for pure Mamba-2 and 6.13 and 60.2 for Transformer++. The paper's own summary is that about 10% of layers being attention works best.
Architecture ablations. Parallel projections with an extra normalization reach 11.49 perplexity at 126.5M parameters, against 11.76 for Mamba-1's block at 129.3M (Table 4). In the head-structure study (Table 5), multi-input heads, the analog of multi-value attention, reach 11.66 at 125M, while multi-query and multi-key patterns reach 12.62 and 12.59 at matched parameters. The paper reports the gap and says the state size does not explain it.
Recall. On the multi-query associative recall task (Figure 8), Mamba-2 does well across settings, and it beats Mamba-1 even at the same state size . Recall improves as the state grows from 16 to 64 to 256.
Why it mattered
The paper's contribution is the connection and what it allows. It shows that several sequence models can be treated as structured matrix multiplications, and that a linear-attention variant and a state space model are two forms of one object. From that it derives an algorithm that is linear in length and uses tensor cores, and an architecture that carries Transformer-style systems techniques, including tensor parallelism, sequence parallelism and variable-length training without padding (Section 8). Empirically, at the scales tested, up to 2.7B parameters and 300B tokens, Mamba-2 matches Transformer++ quality and beats Mamba on speed.
Reading guide
Read the paper in this order. Each prerequisite is linked where it first matters.
- Section 1, Introduction. Transformer and Attention Mechanism for the quadratic training cost and the KV Cache.
- Section 2, Background. State Space Model for the continuous system and its discrete form and recurrence. Structured matrices are introduced at 2.3; Semiseparable Matrix is needed from Section 3.2 on.
- Section 3, SSMs as structured matrices. Matrix Multiplication for the matrix view , and Semiseparable Matrix for the low-rank off-diagonal property.
- Section 4, Structured masked attention. Linear Attention and Attention Mechanism for the masked attention form and the kernel view.
- Section 5, Duality. State Space Duality for the equivalence, and Selective State Space Model for the selective SSM that SSD simplifies.
- Section 6, The SSD algorithm. Matrix Multiplication again, for why block products run fast, and GPU Memory Hierarchy for why chunking helps. FlashAttention: Fast and Memory-Efficient Exact Attention is the comparison point for the speed claims.
- Section 7, Mamba-2 architecture. Multi-Head Attention and Multi-Query Attention for the head-pattern analogies, and Layer Normalization and Residual Connection for the surrounding block.
- Section 8, Systems. No new prerequisites. Tensor and sequence parallelism are used as the paper describes them.
- Section 9, Experiments. Neural Scaling Laws and Training Compute-Optimal Large Language Models (Chinchilla) for the token budgets, FlashAttention-2: Faster Attention with Better Parallelism for the speed baseline, and Mamba: Linear-Time Sequence Modeling with Selective State Spaces for the comparison model.
Check yourself
QuestionIn one sentence, what does it mean that the SSD layer is 'an SSM and a masked attention at the same time'?Show answer
The same output sequence can be produced by two algorithms on one object. The recurrence applies a scalar decay to a state and adds the new input, which is linear in length. The masked matrix product does the same thing as one dense multiply, which is quadratic but uses matrix hardware. Both compute for the same .
QuestionTake three steps with scalar decay for all , input , and , with and zero initial state. Use the recurrence and . What are ?Show answer
The recurrence gives , , and . Since , . Check with the matrix form: , because and . The two forms agree.
QuestionWhy does the block decomposition make the off-diagonal blocks cheap?Show answer
Each off-diagonal block of the mask is low rank, because is semiseparable. Its rank is at most the state size . So a block is a product of thin matrices. The model can carry information across a chunk boundary through a state of size instead of mixing every pair of positions. The matrix work scales with rather than with the chunk pairs.
QuestionYou are choosing a layer for a 16K-token training run on one GPU, with a state size of 64 per head and head dimension 64. The paper reports SSD about 6x faster than FlashAttention-2 at 16K. What would you check before relying on that number?Show answer
The 6x figure is the paper's kernel benchmark (Figure 10), not a whole-model result. The paper itself notes that a full Mamba-2 model can be slower than a Transformer at short lengths, and the speed claims come from its own implementation and hardware. Check the same kernel and the same sequence length on your hardware, and time an end-to-end model too, because the mix of attention and MLP layers changes the total.
QuestionWhy does the paper's Table 5 show a large perplexity gap between multi-value and multi-query head patterns, when the total state size is the same?Show answer
Total state size is for every pattern, so capacity is equal. The paper reports the difference and says total state size does not explain it. In the multi-input pattern and use one head, and the model reaches 11.66 against 12.62 for multi-query at 125M. The paper reports the gap as an empirical finding, not a derived result.
Sources
- Dao, T. and Gu, A. (2024). Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. https://arxiv.org/abs/2405.21060
- Gu, A. and Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. https://arxiv.org/abs/2312.00752
- Dao, T. (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. https://arxiv.org/abs/2307.08691
- Vaswani, A. et al. (2017). Attention Is All You Need. https://arxiv.org/abs/1706.03762