Back to paper library

Mamba-2

Attention's Distant Cousin

Original paper

Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality

Paper authors

Tri Dao · Albert Gu

Publication
ICML 2024Conference
First submitted to arXiv
arXiv:2405.21060
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{mambamamba22024,
  title = {{Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality}},
  author = {Tri Dao and Albert Gu},
  year = {2024},
  eprint = {2405.21060},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2405.21060}
}
On this page

The title of this paper, Transformers are SSMs, is a little provocative.

It's actually a tribute. In 2020, Katharopoulos et al. published a paper called “Transformers are RNNs,” showing that linear attention, with the softmax removed, can be rewritten as an RNN. Tri Dao and Albert Gu also admit in a footnote that the title only holds for “certain flavors” of attention.

Six months earlier, they had used Mamba to show that state space models could trade blows with Transformers. This paper heads in a different direction, showing that the two kinds of models are actually relatives and then asking what that relationship can be used for.

Defining the Problem

The authors' frustration comes from the ecosystem.

Transformers have an entire community studying them, building up layer upon layer of work from theoretical analysis and hardware optimizations like FlashAttention to tensor parallelism and sequence parallelism. On the SSM side, people have mostly been figuring things out on their own, and those results are hard to apply directly.

More concretely, Mamba's selective scan has two practical problems:

  1. It can't use the matrix-multiplication units. The fastest units on a GPU are tensor cores, which do nothing but matrix multiplication. Mamba's recurrence can be computed with a parallel (associative) scan, but most of the work in a scan is elementwise and can't use tensor cores.
  2. The state can't grow much. A larger state dimension NN remembers more, but it also slows the scan. Mamba defaults to N=16N=16.

The authors want to find a correspondence between SSMs and attention, so that SSMs can be computed with matrix multiplication and can directly reuse the systems engineering built up around Transformers.

Solving the Problem

Writing an SSM as a Matrix

First, recall the recurrence of a selective SSM. The parameters at each step are determined by the input:

ht=Atht−1+Btxt,yt=Ct⊤hth_t=A_t h_{t-1}+B_t x_t,\qquad y_t=C_t^\top h_t

Set the initial state to zero. Unrolling the recurrence, the output at step jj is a weighted sum of all inputs up to that step:

yj=∑i≤jCj⊤AjAj−1⋯Ai+1Bi xiy_j=\sum_{i\le j} C_j^\top A_j A_{j-1}\cdots A_{i+1} B_i\, x_i

So the input–output map over the whole sequence is a single matrix multiplication y=Mxy=Mx, where

Mji=Cj⊤Aj:iBi,Aj:i=Aj⋯Ai+1M_{ji}=C_j^\top A_{j:i} B_i,\qquad A_{j:i}=A_j\cdots A_{i+1}
On the left, an input sequence of length T passes through a lower-triangular T×T sequence transformation matrix M to produce the output; on the right, each entry of M is written as C transposed times a chain of A's times B, and a submatrix below the main diagonal is outlined with a dashed box
Figure 2 from the paper, excerpted from page 9 of the v1 PDF, CC BY 4.0.

This MM is lower triangular with an unusual structure, in which any submatrix taken below the diagonal (the blue dashed box in the figure) has rank at most the state dimension NN. In mathematics, matrices like this are called semiseparable matrices.

The authors notice that the various ways of computing an SSM are all different algorithms for multiplying by this matrix. Step-by-step recurrence is one way to do the multiplication; computing the full MM and then multiplying is another.

Reducing AA to a Single Number

Mamba's AtA_t is a diagonal matrix. Mamba-2 simplifies it one step further to At=atIA_t=a_t I, using a single scalar at∈[0,1]a_t\in[0,1] at each step to control the decay. This version is called SSD (state space dual).

With that, Aj:iA_{j:i} becomes a product of scalars, which can be pulled out of the matrix:

M=L∘(CB⊤),Lji={aj×⋯×ai+1,j≥i0,j<iM=L\circ(CB^\top),\qquad L_{ji}=\begin{cases}a_j\times\cdots\times a_{i+1}, & j\ge i\\ 0, & j<i\end{cases}

Now compare it with causal attention:

Y=softmax(mask(QK⊤))VY=\text{softmax}\big(\text{mask}(QK^\top)\big)V

Treat CC as QQ, BB as KK, and xx as VV, and the two look almost identical. They differ in two places:

  1. There's no softmax.
  2. The mask isn't just 0s and 1s. An ordinary causal mask only says whether a position “can be seen”; LL also says “how much”: the farther away, the more decay gets multiplied in, and the decay at each step is determined by the input.

The authors interpret the second point as LL taking the place of the Transformer's positional encoding, becoming a data-dependent positional mask.

Working Through Four Tokens

Take four tokens and a state dimension of N=2N=2. The recurrent form carries a 2-dimensional state forward, multiplying it by the decay ata_t at each step, adding BtxtB_t x_t, and reading out with CtC_t. The matrix form first builds a 4×44\times4 lower-triangular mask LL, whose entry in row ii and column jj is the product aj+1a_{j+1} through aia_i, multiplies it elementwise with CB⊤CB^\top, and finally applies it to xx. The two computations give exactly the same answer.

The recurrent route carries only 2 numbers forward at a time, so memory stays fixed, which suits generation. The matrix route has to build the 4×4 table first, and for a sequence of length TT that table is T×TT\times T, but it's all matrix multiplication, which tensor cores compute very quickly, so it suits training.

In the last row of the mask, when the 4th token looks at the 1st, it gets multiplied by 0.5×0.8×0.7=0.280.5\times0.8\times0.7=0.28. If even one step in between has a small ata_t, whatever came before is almost completely forgotten. This is what Mamba's “selectivity” looks like on the matrix.

Half One Way, Half the Other

The actual SSD algorithm splits the sequence into fixed-length chunks:

  • Within each chunk, it uses the matrix form, computing a small quadratic matrix on the tensor cores.
  • Between chunks, it uses the recurrent form, passing only the state at the end of each chunk on to the next.

This amounts to a block decomposition of MM, in which the small blocks on the diagonal are computed directly and the part below the diagonal, being low-rank, can be represented through the state. Listing 1 of the paper gives a complete implementation in just a short stretch of PyTorch.

Figure 10 of the paper benchmarks the core operation on an A100 80GB PCIe. With the state dimension at 64 for both, SSD is 2 to 8 times faster than Mamba's fused scan; against FlashAttention-2, it breaks even at a sequence length of about 2K and is 6 times faster at 16K. And because it computes so fast, the state dimension can grow from Mamba's default of 16 to 64 or 256.

The Mamba-2 Block

Two blocks side by side. On the left, the Sequential Mamba Block first produces X through a convolution and an activation function, then projects A, B, and C from X and feeds them into the SSM; on the right, the Parallel Mamba Block produces A, X, B, and C at the start of the block with a single linear projection, and after the SSM output is multiplied by the gate there is an extra normalization layer N before the output projection
Figure 6 from the paper, excerpted from page 23 of the v1 PDF, CC BY 4.0. Mamba's block is on the left, Mamba-2's on the right.

Once you see SSMs as relatives of attention, block design can also borrow from attention's experience:

  1. Parallel projections. Mamba first computes XX, then uses XX to project BB, CC, and Δ\Delta; Mamba-2 produces AA, XX, BB, and CC with a single projection at the start of the block (in the figure, AA refers to the discretized decay, whose data dependence comes from the step size Δ\Delta projected at the same time), just as attention produces QQ, KK, and VV all at once. This uses slightly fewer parameters and is friendlier to tensor parallelism, halving the number of synchronization points per block.
  2. Multiple heads. Mamba effectively has one head per channel (head dimension 1); Mamba-2 uses a head dimension of P=64P=64 or 128, following Transformer convention. BB and CC are shared across heads, similar to several value heads sharing keys and queries.
  3. An extra normalization layer. In preliminary experiments, larger models were prone to unstable training, so the authors added a normalization layer after the gate and before the output projection.

Discussion

A Bigger State Remembers More

Three line charts showing multi-query associative recall (MQAR) accuracy at sequence lengths 256, 512, and 1024, with model dimension from 32 to 256 on the x-axis. Mamba (N=16) is near 0 almost everywhere; Mamba-2 (N=16) rises as the model grows; Mamba-2 (N=64) and N=256 are close to 1 in most settings; attention is around 0.5 at length 1024 and dimension 128
Figure 8 from the paper, excerpted from page 28 of the v1 PDF, CC BY 4.0.

MQAR (multi-query associative recall) is a synthetic task in which the model first sees a list of key–value pairs and then gets asked about many keys at once. It's a lot like looking up numbers in a phone book, and it has long been a weak spot for state models.

Reading the figure:

  • Mamba (N=16N=16) fails almost across the board.
  • Mamba-2 with the same N=16N=16 does much better. The authors themselves aren't sure which part of the architecture makes the difference.
  • As NN goes from 16 to 64 and 256, accuracy keeps climbing; at length 1024, the N=256N=256 version even beats standard attention.

The larger the state, the more pairs it can hold. SSD makes large states affordable, and that is exactly why it matters.

Keep in mind that the models here have only two layers and a dimension of at most 256: this is a very small synthetic experiment.

Language Modeling

Trained on 300B tokens of the Pile, Mamba-2 2.7B has a zero-shot average of 60.2, above Mamba 2.8B's 59.9 and Pythia 2.8B's 55.7, and even above Pythia 6.9B, more than twice its size, at 58.3 (Mamba-2 numbers from Table 1 of the paper; Pythia 6.9B from Table 10 in the appendix). A separate set of scaling-law experiments covers 125M to 1.3B parameters and 2.5B to 26B training tokens; in that setting, Mamba-2 beats the authors' Transformer++ baseline in perplexity, theoretical FLOPs, and actual training time.

The Original Authors Recommend Hybrids Too

In an often-overlooked part of this paper, the authors themselves tried mixing SSD layers with attention layers.

They trained a 350M-parameter, 48-layer model on 7B tokens of the Pile, varying how many of its layers were attention:

Table: Excerpted from Table 2 of the paper.
Attention layersPerplexity
0 (pure Mamba-2)8.60
18.38
38.29
68.26
118.30
248.50
Pure Transformer++8.68

Adding just one attention layer drops perplexity from 8.60 to 8.38; 6 layers out of 48 (12.5%) is best, which the authors summarize as “around 10%.” Why does mixing work better? The authors conjecture that the two kinds of layers divide up the work of memory. SSD keeps organizing the preceding text in a fixed-size state, while attention keeps open a path for looking back token by token, so the model doesn't have to cram every detail into the state.

Scaled up to 2.7B parameters, 64 layers, and 300B tokens, Mamba-2-Attention, with 58 SSD layers plus 6 attention layers, reaches a Pile perplexity of 5.95 and a zero-shot average of 61.0, better than both pure Mamba-2 and Transformer++ at 60.2.

Not an Across-the-Board Upgrade

The authors candidly flag limitations in several places:

  • The 2 to 8 times speedup is relative to Mamba's scan. At the level of the whole model, for short sequences like 2K, Mamba-2 doesn't necessarily train faster than a Transformer, because at the same parameter count half of a Transformer consists of highly hardware-efficient MLP layers.
  • A little less expressive power. Reducing AA from a diagonal matrix to a scalar trades expressiveness for training efficiency. Tri Dao states more bluntly on his blog that Mamba-2 isn't strictly better than Mamba-1, because inference speed depends only on state size, and at the same state size Mamba-1 may be more expressive. Tri Dao's blog, Mamba-2 Part I

In the Hacker News discussion, one commenter summed the paper up in a single sentence, saying that restricting AA to a scalar times the identity lets the SSM be written as causal linear attention, with the benefit of much faster training on GPUs. Someone else simply replied, “tldr: mamba is not as good as transformer.” Hacker News, 2024-06-03 The first summary accurately captures the mechanism of the duality and its training benefit; the second verdict never says on which tasks, or under what conditions, the comparison was made. The paper actually limits the expressiveness of AA in exchange for hardware efficiency, and that efficiency in turn lets the state grow, with a benefit that shows up on MQAR.

Conclusion

What Mamba-2 leaves behind can roughly be grouped into three levels:

  1. Theory: an SSM whose state transition is a scalar times the identity (SSD) and linear attention with a semiseparable mask are two algorithms for the same matrix. The authors also prove that, within the masked attention defined in the paper, any mask with a finite-order linear recurrence form must be a semiseparable matrix, which is to say some kind of SSM.
  2. Engineering: the block-decomposition algorithm lets SSMs use tensor cores, making the core operation 2 to 8 times faster than Mamba's scan; the state can grow to 64 or 256, and tensor and sequence parallelism apply directly.
  3. Architecture: the authors' own experiments show that SSD layers combined with around 10% attention layers beat both pure Mamba-2 and pure Transformers.

With Mamba, the question was “Who is the Successor.” This paper holds that the successor was family all along, and that the best arrangement is to have it live under the same roof as the original head of the house.

The later Gated DeltaNet builds directly on this framework, joining Mamba-2's scalar decay to a different update rule.