AI Logic

Architectures

Mamba-2

Updated๏ผš

Architecture of Mamba-2. Left: the overall flow as a language model (stacked normalization, Mamba-2 blocks, and residual connections). Center: inside a Mamba-2 block (a single linear projection produces X, B, C, ฮ”, and Z; convolution, SiLU, and the SSD layer, whose output is multiplied by a SiLU gate, then normalized and linearly projected). Top right: the SSD state update with a scalar a_t. Bottom right: viewing the same computation as the lower-triangular matrix (L โˆ˜ CBแต€) X and splitting it into matrix multiplications within chunks and state passing between chunks

Background and Overview

Mamba-2 is a sequence model that replaces the selective SSM of Mamba with an SSD layer, whose state decay is restricted to the form "scalar ร— identity matrix", so that it can be computed quickly with GPU matrix multiplications. Dao and Gu proposed it in 2024 in the paper "Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality", presented at ICML 2024.

Mamba matched Transformers in language modeling, but its selective scan cannot use the GPU's dedicated matrix-multiplication units (tensor cores), and it slows down as the state grows. The attention in a Transformer, by contrast, can be computed entirely with matrix multiplications and uses the hardware efficiently.

This paper showed that SSMs and variants of attention are deeply related. The title is a homage to the linear attention paper "Transformers are RNNs".

  • SSMs are the same as multiplication by semiseparable matrices: The sequence transformation of an SSM can be written as multiplying the input by a matrix MM with a structure called semiseparable.
  • State space duality (SSD): An SSM whose AtA_t is a scalar has exactly the same linear form (recurrence) and quadratic form (attention) as masked linear attention.
  • The SSD algorithm: The matrix MM is split into chunks; within each chunk it is computed with attention-like matrix multiplications, and between chunks by passing SSM states.

The paper reports that the SSD implementation is 2โ€“8ร— faster than Mamba's selective scan and barely slows down even when the state is made 8ร— or more larger.

Theory: Viewing SSMs as Matrices

A selective SSM (Mamba's form) with time-varying parameters At,Bt,CtA_t, B_t, C_t can be written as follows (Eq. (2) of the paper; the paper omits discretization and writes the discretized values as A,BA, B).

ht=Atโ€‰htโˆ’1+Btโ€‰xt,yt=CtโŠคhth_t = A_t\, h_{t-1} + B_t\, x_t, \qquad y_t = C_t^\top h_t

Unrolling this recurrence, each output becomes a weighted sum of the inputs, and over the whole sequence it takes the form of multiplication by a matrix MM (Eq. (3) of the paper).

yt=โˆ‘s=0tCtโŠคAtAtโˆ’1โ‹ฏAs+1โ€‰Bsโ€‰xs,y=Mx,Mji=CjโŠคAjโ‹ฏAi+1Biy_t = \sum_{s=0}^{t} C_t^\top A_t A_{t-1} \cdots A_{s+1}\, B_s\, x_s, \qquad y = M x, \quad M_{ji} = C_j^\top A_j \cdots A_{i+1} B_i

MM is lower triangular, and every submatrix below the diagonal has rank at most the state size NN. A matrix with this property is called an NN-semiseparable matrix. The paper shows that SSMs and semiseparable matrices are the same thing, and frames it this way: "different ways of computing an SSM are different algorithms for multiplying by a structured matrix."

The SSD layer of Mamba-2 narrows Mamba's selective SSM in the following steps.

  1. Make AtA_t a scalar: In Mamba, AtA_t was a diagonal matrix; in SSD, At=atIA_t = a_t I (scalar ร— identity matrix). ata_t is an input-dependent value between 0 and 1.
  2. Increase the head dimension: Mamba used an independent SSM per feature (head dimension P=1P = 1), but SSD groups features into heads with P=64P = 64 or 128128. This is the same idea as heads in a Transformer.
  3. The quadratic form matches linear attention: Because AtA_t is a scalar, it factors as Mji=(ajโ‹ฏai+1)โ‹…CjโŠคBiM_{ji} = (a_j \cdots a_{i+1}) \cdot C_j^\top B_i, and the whole matrix takes the following form (Section 5.1 of the paper).
Y=(Lโˆ˜CBโŠค)โ€‰X,Lji={ajร—โ‹ฏร—ai+1(jโ‰ฅi)0(j<i)Y = (L \circ C B^\top)\, X, \qquad L_{ji} = \begin{cases} a_j \times \cdots \times a_{i+1} & (j \ge i) \\ 0 & (j < i) \end{cases}

Reading C,B,XC, B, X as the query, key, and value of attention (Q,K,VQ, K, V), this is attention with the softmax removed and a decay mask LL applied. If all at=1a_t = 1, LL becomes the ordinary causal mask (all ones in the lower triangle), and it is identical to causal linear attention.

SSMAttention
CC (matrix that contracts the state into the output)QQ (query)
BB (matrix that expands the input into the state)KK (key)
XX (input sequence)VV (value)
Aj:iA_{j:i} (state decay)LjiL_{ji} (mask)
NN (state size)Feature map dimension

The decay mask LL can be seen as a mask that, in place of a Transformer's positional encoding, decides based on the input "how much to attenuate information from how far back". The paper notes that removing the softmax is also a change in the direction of avoiding problems such as attention sinks.

The SSD Algorithm: Computing in Chunks

There are two extreme ways to compute the SSD layer.

  • Recurrent form: Compute ht=athtโˆ’1+BtxtโŠคh_t = a_t h_{t-1} + B_t x_t^\top step by step. The cost is proportional to the sequence length, but it uses almost no matrix multiplications.
  • Quadratic form: Compute Y=(Lโˆ˜CBโŠค)XY = (L \circ CB^\top)X directly. It needs only matrix multiplications, but the cost is quadratic in the length.

The SSD algorithm (Section 6 and Listing 1 of the paper) splits the matrix MM into chunks of length QQ and takes the best of both. The bottom right of the figure at the top of the article shows this split.

  1. Within a chunk (diagonal blocks): Treat the initial state as zero and compute the output in quadratic form (attention-like matrix multiplications). Chunks can be computed in parallel.
  2. Final state of each chunk: Compute the last state of each chunk, assuming a zero initial state, with matrix multiplications.
  3. Passing between chunks: Pass the final states forward through a short scalar SSM recurrence of length T/QT/Q to obtain the true initial state of each chunk.
  4. Contribution of the received state: Compute, with matrix multiplications, the contribution of each chunk's initial state to the outputs within the chunk, and add it to the result of step 1.

The off-diagonal blocks are low-rank due to the semiseparable property, so they can be computed cheaply through the state (of size Nร—PN \times P). If the state size, head dimension, and chunk length are all set to NN, the cost is O(TN2)O(TN^2) and memory is O(TN)O(TN), and almost all of the computation is Nร—NN \times N matrix multiplication (Theorem 6.1 of the paper).

AspectAttentionSelective SSM (Mamba)SSD (Mamba-2)
State sizeTTNNNN
Training costT2NT^2 NTN2TN^2TN2TN^2
Cost per inference stepTNTNN2N^2N2N^2
Memory of a naive implementationT2T^2TN2TN^2TNTN
Uses matrix multiplicationYesNoYes

(Table in Section 6.3 of the paper. TT is the sequence length.)

The Mamba-2 Block

The Mamba-2 block (Section 7.1 and Figure 6 of the paper) changes the Mamba block in two ways.

  • Do all projections up front: In Mamba, ฮ”,B,C\Delta, B, C were further projected from the XX produced by the first projection. Mamba-2 treats the SSD layer as "a map from A,X,B,CA, X, B, C to YY" and produces AA (ฮ”\Delta), XX, BB, CC, and the gate ZZ in parallel with a single projection at the start of the block. This mirrors how attention produces Q,K,VQ, K, V in parallel; it slightly reduces parameters and makes the block easier to split for tensor parallelism.
  • Add one normalization: Because training of large models tended to be unstable, a normalization layer (layer normalization, group normalization, RMSNorm, etc.) is added after the gate and before the output projection.

In the head structure (Section 7.2 of the paper), BB and CC are shared across all heads, and only XX is per head. In attention terms, this corresponds to "multi-value attention", where keys and queries are shared and only values are per head. The paper uses this framework to explain that Mamba had the same structure. ata_t is separate for each head.

Experimental Results

Language modeling: Models were trained in the same setting as Mamba (300 billion tokens of The Pile) and evaluated zero-shot (Table 1 of the paper; Pile is validation perplexity, lower is better, and the average is accuracy % over seven tasks).

ModelPile perplexityAverage accuracy on 7 tasks
Pythia-2.8B (Transformer)6.7355.7
RWKV4-3B7.0056.4
Mamba-2.8B6.2259.9
Mamba-2-2.7B6.0960.2

Mamba-2-2.7B outperformed Mamba-2.8B and Pythia-2.8B trained on the same data. In scaling experiments with model sizes from 125M to 1.3B (Figure 9 of the paper), Mamba-2 also matched or exceeded Mamba and a strong Transformer recipe (Transformer++).

Combining with attention (about 350M parameters, 48 layers, perplexity; Table 2 of the paper)

Number of attention layers0 (Mamba-2)13624Transformer++
Perplexity8.608.388.298.268.508.68

A model with only SSD layers performed about the same as Transformer++, but making about 10% of the layers attention gave the best results. The paper suggests that the SSM layers handle general sequence transformation while the attention layers handle directly referring to past tokens. At the 2.7B scale as well, a model with 6 attention layers out of 64 outperformed both Mamba-2 and Transformer++ (Table 3 of the paper).

Effect of the block changes (about 130M parameters, perplexity; Table 4 of the paper)

ProjectionExtra normalizationPerplexity
Sequential (Mamba)No11.76
SequentialYes11.54
ParallelNo11.66
Parallel (Mamba-2)Yes11.49

Speed (Section 9.3 and Figure 10 of the paper): With state size N=64N = 64, SSD was 2โ€“8ร— faster than Mamba's selective scan, and faster than FlashAttention-2 at lengths of 2,000 and above. Increasing the state size does not slow it down the way Mamba's scan does.

Associative recall (MQAR, Section 9.1 of the paper): On a task that requires memorizing several key-value pairs and later retrieving values by key, Mamba struggled, but Mamba-2 solved it well in all settings. Performance improved as the state size increased from N=16N = 16 to 6464 and 256256.

Practical Considerations

Keep the following points in mind when using Mamba-2.

  • On short sequences, it does not necessarily train faster than a Transformer: At the same parameter count, half of a Transformer's layers are MLPs that are pure matrix multiplication, whereas all of Mamba-2's layers are SSD layers. The paper notes that at lengths around 2,000 Transformers can be easier to train, and that mixing SSD layers with MLP layers makes training faster even on short sequences.
  • State size directly affects performance: Increasing NN improves associative recall. Because SSD barely slows down with larger NN, a larger NN (64โ€“256) than in Mamba can be chosen.
  • Pad the sequence length to a multiple of the chunk length: The paper's reference implementation (Listing 1) assumes the length is divisible by the chunk length.

Because SSD restricts Mamba's AtA_t (a diagonal matrix) to a scalar, its expressiveness as a single SSM is somewhat lower. The paper explains that in exchange, the larger head dimension and the ability to enlarge the state with matrix multiplications yield both better performance and speed overall. For tasks that need per-channel differences in AtA_t, verify against Mamba.

Because the state size is fixed, tasks that require retrieving past information exactly (such as looking up a phone book) are hard for an SSM alone. In the paper's experiments as well, models that mixed in a few attention layers gave the best results. When performance matters, consider combining it with attention.

Comparison with Other Models

In the SSD framework, many sequence models can be arranged as "multiplication by a structured matrix" (Figure 4 of the paper). S4 and Mamba's S6 are diagonal SSMs, linear attention and RetNet are on the masked-attention side, and SSD lies in their overlap. For example, RetNet can be positioned as the case where the decay ata_t is an input-independent constant ฮณ\gamma.

Alternatives to the Transformer compare as follows.

ModelHow the sequence is mixedDoes forgetting depend on the inputTraining costOne generation step
TransformerSoftmax attentionNo state (keeps the entire past)Quadratic in lengthProportional to length so far
Linear attentionAccumulates feature-map inner products into a stateNever forgets (only accumulates)Linear in lengthConstant
S4Linear SSM (HiPPO initialization)NoNearly linear in length (FFT)Constant
HyenaLong convolutions and element-wise gatesNo (the kernel is fixed; the gates depend on the input)Nearly linear in length (FFT)Not constant in convolutional form
MambaSSM whose parameters depend on the inputYesLinear in length (parallel scan)Constant
Mamba-2SSM with scalar state decayYesLinear in length (mostly matrix multiplications)Constant
RWKVLinear RNN with exponentially decaying weighted averageNo (fixed per channel)Linear in lengthConstant
RetNetRetention with decayNo (fixed per head)Quadratic in parallel form, linear when chunkedConstant

Rough guidelines for choosing:

  • To train a language model from scratch and train and generate quickly on long sequences: Mamba-2 fits. It trains faster than Mamba and allows a larger state.
  • If you also want the ability to retrieve information in context precisely: Consider a model that mixes about 10% attention layers into Mamba-2 layers.
  • If sequences are mostly short and you want to use pretrained models and tooling: A Transformer fits.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small implementation of the Mamba-2 SSD layer and block
- ssd(): Listing 1 of the paper (chunked computation) rewritten without einops
- ssd_recurrent(): the recurrent form that runs the same SSM one step at a time. At the end we check that both give the same values
- Mamba2Block: Figure 6 of the paper. A single linear projection produces X, B, C, ฮ”, Z; X, B, C go through convolution โ†’ SiLU;
  the SSD output is multiplied by SiLU(Z), normalized, and projected back. B and C are shared across all heads
For practical use, use the official implementation mamba_ssm (Triton kernels)
"""


def segsum(x):
  """exp(segsum(a)) gives the 1-semiseparable matrix L (L[j, i] = a_j ... a_{i+1}, 0 for j < i). x is log a"""
  T = x.size(-1)
  x_cumsum = torch.cumsum(x, dim=-1)
  x_segsum = x_cumsum[..., :, None] - x_cumsum[..., None, :]
  mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool))
  return x_segsum.masked_fill(~mask, -torch.inf)


def ssd(X, A, B, C, block_len=16):
  """
  X: [b, T, h, p] (input), A: [b, T, h] (log a_t, โ‰ค 0), B, C: [b, T, h, n]
  Returns Y: [b, T, h, p]
  """
  b, T, h, p = X.shape
  c = T // block_len
  X, B, C = [t.reshape(b, c, block_len, *t.shape[2:]) for t in (X, B, C)]
  A = A.reshape(b, c, block_len, h).permute(0, 3, 1, 2)                     # [b, h, c, l]
  A_cumsum = torch.cumsum(A, dim=-1)
  # 1. Within a chunk (diagonal blocks): attention-like quadratic form
  L = torch.exp(segsum(A))
  Y_diag = torch.einsum("bclhn,bcshn,bhcls,bcshp->bclhp", C, B, L, X)
  # 2. Final state of each chunk (assuming a zero initial state)
  decay_states = torch.exp(A_cumsum[..., -1:] - A_cumsum)
  states = torch.einsum("bclhn,bhcl,bclhp->bchpn", B, decay_states, X)
  # 3. Recurrence between chunks: pass the state from the previous chunk
  states = torch.cat([torch.zeros_like(states[:, :1]), states], dim=1)
  decay_chunk = torch.exp(segsum(F.pad(A_cumsum[..., -1], (1, 0))))
  states = torch.einsum("bhzc,bchpn->bzhpn", decay_chunk, states)[:, :-1]
  # 4. Contribution of the received state to the outputs within the chunk
  Y_off = torch.einsum("bclhn,bchpn,bhcl->bclhp", C, states, torch.exp(A_cumsum))
  return (Y_diag + Y_off).reshape(b, T, h, p)


def ssd_recurrent(X, A, B, C):
  """Recurrent form: h_t = a_t h_{t-1} + B_t x_tแต€, y_t = C_tแต€ h_t (state is [h, n, p])"""
  b, T, h, p = X.shape
  state = X.new_zeros(b, h, B.shape[-1], p)
  ys = []
  for t in range(T):
    state = torch.exp(A[:, t])[..., None, None] * state + B[:, t, :, :, None] * X[:, t, :, None, :]
    ys.append(torch.einsum("bhn,bhnp->bhp", C[:, t], state))
  return torch.stack(ys, dim=1)


class Mamba2Block(nn.Module):
  def __init__(self, d_model, d_state=64, headdim=64, expand=2, d_conv=4, block_len=16):
    super().__init__()
    self.d_inner = expand * d_model
    self.nheads = self.d_inner // headdim
    self.headdim, self.d_state, self.block_len = headdim, d_state, block_len
    conv_dim = self.d_inner + 2 * d_state                  # X plus B and C shared across all heads
    # A single projection produces Z, (X, B, C), and ฮ” in parallel
    self.in_proj = nn.Linear(d_model, self.d_inner + conv_dim + self.nheads, bias=False)
    self.conv = nn.Conv1d(conv_dim, conv_dim, d_conv, groups=conv_dim, padding=d_conv - 1)
    self.A_log = nn.Parameter(torch.log(torch.empty(self.nheads).uniform_(1, 16)))  # source of a_t (a scalar per head)
    self.dt_bias = nn.Parameter(torch.zeros(self.nheads))
    self.D = nn.Parameter(torch.ones(self.nheads))
    self.norm = nn.LayerNorm(self.d_inner)                 # normalization added before the output projection
    self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)

  def forward(self, u):                                    # u: [b, T, d_model] (T is a multiple of block_len)
    b, T, _ = u.shape
    z, xBC, dt = self.in_proj(u).split([self.d_inner, self.d_inner + 2 * self.d_state, self.nheads], dim=-1)
    xBC = F.silu(self.conv(xBC.transpose(1, 2))[..., :T].transpose(1, 2))
    x, B, C = xBC.split([self.d_inner, self.d_state, self.d_state], dim=-1)
    x = x.reshape(b, T, self.nheads, self.headdim)
    B = B[:, :, None, :].expand(b, T, self.nheads, self.d_state)    # B and C are shared across all heads
    C = C[:, :, None, :].expand(b, T, self.nheads, self.d_state)
    dt = F.softplus(dt + self.dt_bias)                     # ฮ”_t: [b, T, h] (depends on the input)
    A = -torch.exp(self.A_log)                             # a negative scalar per head
    # log a_t = ฮ”_t A (a_t = exp(ฮ”_t A) is in 0โ€“1). The input is also multiplied by ฮ”_t for discretization
    y = ssd(x * dt[..., None], A * dt, B, C, self.block_len)
    y = y + self.D[:, None] * x
    y = y.reshape(b, T, self.d_inner) * F.silu(z)          # gate
    return self.out_proj(self.norm(y))


if __name__ == "__main__":
  torch.manual_seed(0)
  # Check that the chunked computation and the step-by-step recurrence give the same values
  b, T, h, p, n = 2, 64, 4, 8, 16
  X = torch.randn(b, T, h, p)
  A = -F.softplus(torch.randn(b, T, h))                    # log a_t โ‰ค 0
  B, C = torch.randn(b, T, h, n), torch.randn(b, T, h, n)
  print("difference between chunked and recurrent:", (ssd(X, A, B, C, block_len=16) - ssd_recurrent(X, A, B, C)).abs().max().item())

  # Stack blocks with residual connections
  layers = nn.ModuleList([Mamba2Block(d_model=128) for _ in range(2)])
  norms = nn.ModuleList([nn.LayerNorm(128) for _ in range(2)])
  x = torch.randn(2, 64, 128)
  for norm, layer in zip(norms, layers):
    x = x + layer(norm(x))
  print(x.shape)  # torch.Size([2, 64, 128])

FAQ

Q. What is the difference between Mamba-2 and Mamba?
A.

There are two main differences. The inner layer is an SSD layer that restricts AtA_t from a diagonal matrix to a scalar and is computed in chunks with matrix multiplications (2โ€“8ร— faster than Mamba). The block produces A,X,B,C,ZA, X, B, C, Z in parallel with a single initial projection and adds a normalization before the output projection.

Q. What does "Transformers are SSMs" mean?
A.

It means that attention with the softmax removed and a decay mask LL applied, Y=(Lโˆ˜QKโŠค)VY = (L \circ QK^\top)V, is exactly the same computation as an SSM whose AtA_t is a scalar. Not every Transformer is an SSM; the paper itself notes in a footnote that this relationship holds only for particular kinds of attention.

Q. How should the chunk length be chosen?
A.

According to the paper's complexity analysis, setting the state size NN, head dimension PP, and chunk length QQ equal turns all computation into Nร—NN \times N matrix multiplications, which is efficient. The default in the reference implementation (Listing 1) is 64.

References

  1. T. Dao and A. Gu, "Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality," ICML, 2024.
  2. A. Gu and T. Dao, "Mamba: Linear-Time Sequence Modeling with Selective State Spaces," arXiv:2312.00752, 2023.
  3. A. Katharopoulos, A. Vyas, N. Pappas, and F. Fleuret, "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention," ICML, 2020.
  4. Official implementation (mamba)