Search

Search papers and lessons

Transformers are SSMs: Generalized Models and Efficient Algorithms (Mamba-2)

Tri Dao, Albert Gu · 2024

Mamba-2 shows that a state space model with scalar decay is a masked attention matrix in disguise, and uses that to run the model as block matrix multiplies, 2-8x faster than Mamba's scan.

On this page

  • Colour = topic mix
  • Linear algebra
  • Architectures
  • Calculus
  • Neural network basics
  • Discrete math
  • Efficiency
  • Sign in to see your progress

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 TT as one matrix acting on the input: Y=MXY = MX, where MM is a T×TT \times T matrix that depends on the model parameters. For the scalar-decay case the paper studies, MM has two factors. One is an attention-like matrix CB⊤CB^\top, built from the input projections. The other is a lower-triangular decay mask LL, whose entries multiply together the decays between two positions. The whole output is

Y=(L∘CB⊤) X,Lij=aiai−1⋯aj+1 for i≥j,Lij=0 for i<j.Y = (L \circ CB^\top)\, X, \qquad L_{ij} = a_i a_{i-1} \cdots a_{j+1} \text{ for } i \ge j, \quad L_{ij} = 0 \text{ for } i \lt j.

Here ∘\circ is elementwise multiplication, and each ata_t 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 ata_t and then updated with BtxtB_t x_t, read out by CtC_t. Two ways of computing one object give two algorithms. The recurrence costs time linear in TT but is a sequence of small operations. The masked matrix product costs time quadratic in TT but is one large matrix multiply.

The SSD algorithm takes both. It splits the sequence into chunks of length QQ 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 TT 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 AtA_t is reduced from diagonal to a scalar times the identity, so each step has one decay number ata_t. The head dimension PP 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 N×PN \times P, where NN is the state expansion factor. Training uses the block form.

The block decomposition

Partition MM into a grid of Q×QQ \times Q 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 LL is semiseparable, every block below the diagonal is low rank. Its rank is at most NN, 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 T/QT/Q chunk states rather than over TT tokens, so this step is short. The resulting complexity, with P=NP = N, is stated as Theorem 6.1: O(TN2)O(TN^2) training FLOPs, O(TN)O(TN) inference FLOPs, and O(N2)O(N^2) 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 N=64N = 64, 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:

ModelPile ppl (lower is better)Zero-shot avg. (higher is better)
Mamba-2-1.3B6.6656.4
Mamba-1.4B6.8056.4
Pythia-1.4B7.5151.7
Mamba-2-2.7B6.0960.2
Mamba-2.8B6.2259.9
Pythia-6.9B6.5158.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 N=16N = 16. 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.

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 (L∘CB⊤)X(L \circ CB^\top)X does the same thing as one dense multiply, which is quadratic but uses matrix hardware. Both compute Y=MXY = MX for the same MM.

QuestionTake three steps with scalar decay at=0.5a_t = 0.5 for all tt, input x=(1,2,3)x = (1, 2, 3), and Bt=Ct=1B_t = C_t = 1, with N=P=1N = P = 1 and zero initial state. Use the recurrence ht=atht−1+Btxth_t = a_t h_{t-1} + B_t x_t and yt=Cthty_t = C_t h_t. What are y1,y2,y3y_1, y_2, y_3?Show answer

The recurrence gives h1=1h_1 = 1, h2=0.5⋅1+2=2.5h_2 = 0.5 \cdot 1 + 2 = 2.5, and h3=0.5⋅2.5+3=4.25h_3 = 0.5 \cdot 2.5 + 3 = 4.25. Since Ct=1C_t = 1, y=(1,2.5,4.25)y = (1, 2.5, 4.25). Check with the matrix form: y3=L33x3+L32x2+L31x1=3+0.5⋅2+0.25⋅1=4.25y_3 = L_{33} x_3 + L_{32} x_2 + L_{31} x_1 = 3 + 0.5 \cdot 2 + 0.25 \cdot 1 = 4.25, because L32=a3=0.5L_{32} = a_3 = 0.5 and L31=a3a2=0.25L_{31} = a_3 a_2 = 0.25. The two forms agree.

QuestionWhy does the block decomposition make the off-diagonal blocks cheap?Show answer

Each off-diagonal block of the mask LL is low rank, because LL is semiseparable. Its rank is at most the state size NN. So a block is a product of thin matrices. The model can carry information across a chunk boundary through a state of size NN instead of mixing every pair of positions. The matrix work scales with NN 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 HPNHPN 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 BB and CC 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

Read the full paper

Tri Dao, Albert Gu, 2024. arXiv:2405.21060