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 M with a structure called semiseparable.
State space duality (SSD): An SSM whose Atโ is a scalar has exactly the same linear form (recurrence) and quadratic form (attention) as masked linear attention.
The SSD algorithm: The matrix M 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โ,Ctโ can be written as follows (Eq. (2) of the paper; the paper omits discretization and writes the discretized values as A,B).
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 M (Eq. (3) of the paper).
M is lower triangular, and every submatrix below the diagonal has rank at most the state size N. A matrix with this property is called an N-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.
Make Atโ a scalar: In Mamba, Atโ was a diagonal matrix; in SSD, Atโ=atโI (scalar ร identity matrix). atโ is an input-dependent value between 0 and 1.
Increase the head dimension: Mamba used an independent SSM per feature (head dimension P=1), but SSD groups features into heads with P=64 or 128. This is the same idea as heads in a Transformer.
The quadratic form matches linear attention: Because Atโ is a scalar, it factors as Mjiโ=(ajโโฏai+1โ)โ CjโคโBiโ, and the whole matrix takes the following form (Section 5.1 of the paper).
Reading C,B,X as the query, key, and value of attention (Q,K,V), this is attention with the softmax removed and a decay mask L applied. If all atโ=1, L becomes the ordinary causal mask (all ones in the lower triangle), and it is identical to causal linear attention.
SSM
Attention
C (matrix that contracts the state into the output)
Q (query)
B (matrix that expands the input into the state)
K (key)
X (input sequence)
V (value)
Aj:iโ (state decay)
Ljiโ (mask)
N (state size)
Feature map dimension
The decay mask L 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โ=atโhtโ1โ+Btโxtโคโ step by step. The cost is proportional to the sequence length, but it uses almost no matrix multiplications.
Quadratic form: Compute Y=(LโCBโค)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 M into chunks of length Q and takes the best of both. The bottom right of the figure at the top of the article shows this split.
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.
Final state of each chunk: Compute the last state of each chunk, assuming a zero initial state, with matrix multiplications.
Passing between chunks: Pass the final states forward through a short scalar SSM recurrence of length T/Q to obtain the true initial state of each chunk.
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รP). If the state size, head dimension, and chunk length are all set to N, the cost is O(TN2) and memory is O(TN), and almost all of the computation is NรN matrix multiplication (Theorem 6.1 of the paper).
Aspect
Attention
Selective SSM (Mamba)
SSD (Mamba-2)
State size
T
N
N
Training cost
T2N
TN2
TN2
Cost per inference step
TN
N2
N2
Memory of a naive implementation
T2
TN2
TN
Uses matrix multiplication
Yes
No
Yes
(Table in Section 6.3 of the paper. T 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 were further projected from the X produced by the first projection. Mamba-2 treats the SSD layer as "a map from A,X,B,C to Y" and produces A (ฮ), X, B, C, and the gate Z in parallel with a single projection at the start of the block. This mirrors how attention produces Q,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), B and C are shared across all heads, and only X 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. atโ 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).
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 layers
0 (Mamba-2)
1
3
6
24
Transformer++
Perplexity
8.60
8.38
8.29
8.26
8.50
8.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)
Projection
Extra normalization
Perplexity
Sequential (Mamba)
No
11.76
Sequential
Yes
11.54
Parallel
No
11.66
Parallel (Mamba-2)
Yes
11.49
Speed (Section 9.3 and Figure 10 of the paper): With state size N=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=16 to 64 and 256.
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 N improves associative recall. Because SSD barely slows down with larger N, a larger N (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 Atโ (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 Atโ, 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 atโ is an input-independent constant ฮณ.
Alternatives to the Transformer compare as follows.
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 Atโ 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,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 L applied, Y=(LโQKโค)V, is exactly the same computation as an SSM whose Atโ 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 N, head dimension P, and chunk length Q equal turns all computation into NรN matrix multiplications, which is efficient. The default in the reference implementation (Listing 1) is 64.