Mamba is a sequence model that builds a "selective SSM"βa state space model (SSM) whose parameters change with the inputβinto a simple block that uses neither attention nor an MLP. Gu and Dao proposed it in 2023 in the paper "Mamba: Linear-Time Sequence Modeling with Selective State Spaces".
SSMs such as S4 can handle long sequences with computation nearly linear in sequence length, and they had outperformed the Transformer on continuous signals such as audio. On discrete, information-dense data such as text, however, they fell short of Transformers.
The Mamba paper attributes this to an inability to choose, based on content, whether to remember or ignore. The parameters (Ξ,A,B,C) of S4 are the same at every time step (linear time-invariant, LTI), so every input is written into the state by the same rule. Mamba solves this problem with the following three ideas.
Selection mechanism: Ξ,B,C are computed from the current input xtβ.
Hardware-aware computation: When parameters change at every time step, the model can no longer be computed as a convolution, so the recurrent form is computed as a parallel scan inside the GPU's fast memory.
Simple block: The SSM and a gated MLP like SwiGLU are merged into a single block, and only that block is stacked.
The paper reports that Mamba-3B outperforms Transformers of the same size and matches Transformers twice its size. Its generation throughput is about 5Γ that of a Transformer of the same size.
Theory: The Selective SSM
Like S4, Mamba's SSM maps a one-dimensional input xtβ to an output ytβ through an N-dimensional state htβ, independently for each feature (channel) (Eqs. (1)(2) of the paper).
htβ=AΛhtβ1β+BΛxtβ,ytβ=Chtβ
The difference is that Ξ,B,C are computed from the input (Algorithm 2 of the paper, also called S6). The steps are as follows.
Compute Btβ and Ctβ from the input: Btβ=LinearNβ(xtβ), Ctβ=LinearNβ(xtβ). Their shape is (batch, length, N), with different values at each time step.
Compute Ξtβ from the input: Ξtβ=softplus(parameter+sΞβ(xtβ)). sΞβ is a linear layer that projects the input to a small dimension and then expands it to D features. Softplus makes the value positive.
Discretize: A is an input-independent diagonal matrix parameter, converted into AΛtβ,BΛtβ by zero-order hold (ZOH) (the equation below, Eq. (4) of the paper).
Update the state: Compute htβ=AΛtβhtβ1β+BΛtβxtβ, ytβ=Ctβhtβ in time order (in practice, with a parallel scan).
The right side of the figure at the top of the article shows this computation for one time step. The yellow AΛtβ,BΛtβ,Ctβ are the quantities that change with the input xtβ. For real-valued A, the initialization Anβ=β(n+1) (S4D-Real) is used.
Ξ acts as a gate. With N=1, A=β1, and B=1, the selective SSM update takes the following form (Theorem 1 of the paper).
This is the same form as the update gate of a GRU. A large Ξtβ replaces the state and focuses on the current input; a small Ξtβ keeps the state as is and ignores the current input. As an analogy, it is like taking notes while listening to a talk: you move your pen only for the important parts and leave your earlier notes untouched during small talk.
The Mamba Block and Fast Computation
Block structure (Section 3.4 and Figure 3 of the paper): Earlier SSM models (such as H3) alternated an SSM block resembling linear attention with an MLP block. Mamba merges the two into one and stacks only that block.
Expand the input (D dimensions) to ED dimensions with two linear projections (E=2).
One branch goes through a short convolution along time β SiLU β the selective SSM.
The other branch goes through SiLU and is multiplied element-wise into the first branch as a gate.
Project back to D dimensions with a linear projection.
The activation is SiLU (Swish). Standard normalization and residual connections are placed between blocks. Most of the parameters are in the linear projections (3ED2); the SSM's share is much smaller. To match one Transformer layer (attention plus MLP, 12D2), two Mamba blocks are treated as equivalent to one Transformer layer.
Fast computation (Section 3.3 of the paper): When Ξ,B,C change at every time step, the model cannot be folded into a single-kernel convolution as in S4. Computing it in recurrent form makes the state of size (batch, length, D, N), and memory reads and writes become heavy. The paper solves this with the following three techniques.
Kernel fusion: Load the parameters from the GPU's slow memory (HBM) into its fast memory (SRAM), perform discretization and the recurrence there, and write back only the output (batch, length, D). The large state is never stored in HBM.
Parallel scan: A recurrence is computed sequentially, but the form htβ=AΛtβhtβ1β+BΛtβxtβ can be computed in parallel by exploiting associativity.
Recomputation: The intermediate states needed for backpropagation are not saved but recomputed during the backward pass.
As a result, memory usage is about the same as a Transformer with FlashAttention, and computation is linear in sequence length.
Why It Can Select Based on Content
The Mamba paper explains the trade-off between performance and efficiency in sequence models in terms of how well the context can be compressed into a small state (Section 3.1 of the paper).
Attention does not compress the context at all. During generation it keeps all past keys and values (the KV cache), so it performs well but is heavy at both inference and training.
RNNs and S4 keep only a fixed-size state, so they are fast, but their performance depends on whether the necessary information can be kept in that state.
LTI models such as S4 write every input into the state by the same rule, so they cannot "ignore irrelevant tokens and remember only the needed ones". The paper demonstrates this with two synthetic tasks.
Selective copying: A random number of noise tokens are inserted between the tokens to remember. Since the positions of the tokens to remember change every time, a convolution kernel of fixed shape cannot solve it.
Induction heads: After seeing the pair "Harry Potter" once, the model must predict "Potter" the next time "Harry" appears. This ability is thought to explain in-context learning in large language models.
The selection mechanism serves the following three functions (Section 3.5.2 of the paper).
Function
Description
Variable spacing
Can ignore noise between inputs of interest (such as "um" in speech)
Filtering context
Can erase irrelevant history from the state, so performance can improve with longer context
Boundary resetting
When separate documents are concatenated for training, the state can be reset at boundaries
The paper states that a gated block (such as H3) alone cannot substitute for the selection mechanism. A gate only multiplies elements at each time step and does not exchange information along the sequence, so it cannot affect the spacing between tokens. Indeed, on selective copying, accuracy depended far more on whether the inner SSM was changed from S4 to S6 than on the block architecture (table in the next section).
Experimental Results
Selective copying (accuracy %; Table 1 of the paper)
Induction heads (Table 11 of the paper): Trained at length 256 and tested at lengths from 64 up to about 1 million. Mamba kept 100% accuracy up to 1 million (about 4,000Γ the training length). Multi-head attention with RoPE or xPos dropped sharply in accuracy beyond twice the training length.
Language modeling: Trained on The Pile and evaluated zero-shot (Table 3 of the paper; Pile is validation perplexity, lower is better, and the average is accuracy % over six tasks).
Pythia and RWKV were trained on the same data, with the same tokenizer and the same amount of training (300 billion tokens) as Mamba. Mamba-2.8B outperformed Pythia-6.9B, which is more than twice its size. In scaling experiments with model sizes from 125M to 1.3B (Figure 4 of the paper), Mamba was the first attention-free model to match a strong Transformer recipe (Transformer++) using RoPE, SwiGLU, and RMSNorm.
Which components matter (language model with about 350M parameters, perplexity; Tables 6 and 7 of the paper)
Change
Perplexity
Mamba block + S4 (complex)
10.54
Mamba block + Hyena
10.75
Mamba block + S6 (selective SSM)
8.69
S6 with none of Ξ,B,C selective
10.93
Only Ξ selective
9.81
All of Ξ,B,C selective
8.71
The differences among LTI SSMs were small, while switching to the selective SSM brought a large improvement. Among the parameters made selective, Ξ has the largest effect. Increasing the state size N from 1 to 16 lowered perplexity from 9.73 to 8.71 only when B,C were selective (Table 10 of the paper).
Speed (Section 4.5 of the paper): The selective scan was faster than FlashAttention-2 beyond length 2,000, and up to 20β40Γ faster than a straightforward scan written in PyTorch. In generation, the absence of a KV cache allows larger batches, giving 4β5Γ the throughput of a Transformer of the same size.
Practical Considerations
Keep the following points in mind when using Mamba.
Speed depends on dedicated GPU kernels: Looping over time steps one by one, as in the implementation example below, is useful for checking the equations but is very slow. For practical use, use the selective scan in the official implementation (mamba_ssm).
It cannot directly replace a pretrained Transformer: Its computation differs from attention, so it must be trained from scratch as Mamba.
Initialization of Ξ matters: The paper initializes the bias of Ξ so that Ξ is spread uniformly over the range 0.001β0.1 (Section 3.6 of the paper).
The selection mechanism comes at the cost of properties that made LTI SSMs strong on continuous signals. The paper states that selection helps on discrete data such as text and DNA, whereas LTI SSMs may be better suited to continuous data such as audio waveforms. In the paper's audio experiments, Mamba alone was switched to a complex-valued SSM instead of a real-valued one.
Mamba's state size is constant regardless of sequence length. Unlike attention, which can refer directly to any past position, information not kept in the state cannot be retrieved later. For tasks that require copying specific information precisely from a long context, check the performance gap with Transformers on your own task.
Comparison with Other Models
The Mamba paper organizes related models as follows (Section 2 of the paper).
Linear attention: An approximation of self-attention that can be written in recurrent form; it can be viewed as a degenerate linear SSM.
H3: Generalizes the recurrence of linear attention to S4, with the SSM sandwiched between two gates.
Hyena: The same structure as H3, but uses long convolutions produced by an MLP instead of S4.
RetNet: Adds one more gate and uses a simpler SSM, enabling an attention-like parallel computation instead of convolution.
RWKV: An RNN for language modeling based on the Attention-Free Transformer (AFT); its core WKV is an LTI recurrence that can be viewed as a ratio of two SSMs.
To generate quickly on long sequences of discrete data such as language or DNA: Mamba fits. With no KV cache, generation memory does not grow even with long contexts.
To train faster by making better use of GPU matrix operations: Consider Mamba-2, which follows the same idea but shifts the computation toward matrix multiplications.
For continuous signals such as audio waveforms: Also consider an LTI SSM such as S4.
For tasks that require precise reference to information in context, or to use pretrained assets: A Transformer fits.
PyTorch example
βΆShow code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm
"""
A small implementation of the Mamba block written as in the paper's equations (no parallel scan or dedicated GPU kernels; loops over time steps one by one)
- Selective SSM (Algorithm 2): B, C, Ξ are produced from the input x by linear layers. A is an input-independent diagonal matrix
- Discretization is ZOH (Eq. 4). Since A is diagonal, Δ = exp(ΞA) and BΜ = (exp(ΞA) - 1) / A Β· B can be computed element-wise
- Block (Figure 3): split into two branches by a linear projection; one goes conv β SiLU β SSM, the other SiLU. Multiply, then project back
For practical use, use the official implementation mamba_ssm (fast scan for GPUs)
Task: select and remember tokens at distant positions (a small example similar to Selective Copying that needs no download)
"""
# Hyperparameters
seq_len = 64
vocab = 8 # 0 is noise, 1β7 are tokens to remember
n_memorize = 4 # number of tokens to remember (random positions)
d_model = 64 # D
expand = 2 # E
d_state = 16 # N
d_conv = 4 # width of the convolution along time (example)
n_layers = 2
batch_size = 64
steps = 2000
learning_rate = 1e-3
# 'cuda' if available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
class SelectiveSSM(nn.Module):
def __init__(self, d_inner, d_state, dt_rank):
super().__init__()
# A uses the S4D-Real initialization A_n = -(n+1). Stored as a log to keep it positive
A = torch.arange(1, d_state + 1, dtype=torch.float32).repeat(d_inner, 1) # [ED, N]
self.A_log = nn.Parameter(torch.log(A))
self.D = nn.Parameter(torch.ones(d_inner)) # term that adds the input directly
self.x_proj = nn.Linear(d_inner, dt_rank + 2 * d_state, bias=False) # s_Ξ, s_B, s_C
self.dt_proj = nn.Linear(dt_rank, d_inner) # expand Ξ to ED features
# The bias of Ξ is initialized via the inverse of softplus so that Ξ spreads over 0.001β0.1 (Section 3.6 of the paper)
dt = torch.exp(torch.empty(d_inner).uniform_(math.log(1e-3), math.log(1e-1)))
with torch.no_grad():
self.dt_proj.bias.copy_(dt + torch.log(-torch.expm1(-dt)))
self.dt_rank, self.d_state = dt_rank, d_state
def forward(self, x): # x: [B, L, ED]
Bsz, L, Dn = x.shape
A = -torch.exp(self.A_log) # [ED, N] (negative values)
dt_in, Bm, Cm = self.x_proj(x).split([self.dt_rank, self.d_state, self.d_state], dim=-1)
delta = F.softplus(self.dt_proj(dt_in)) # Ξ_t: [B, L, ED] (depends on the input)
dA = delta.unsqueeze(-1) * A # ΞA: [B, L, ED, N]
A_bar = torch.exp(dA) # Δ_t = exp(Ξ_t A)
B_bar = (A_bar - 1) / A * Bm.unsqueeze(2) # BΜ_t = (exp(ΞA) - 1)/(ΞA) Β· ΞB (element-wise since diagonal)
h = x.new_zeros(Bsz, Dn, self.d_state) # state h: [B, ED, N]
ys = []
for t in range(L): # h_t = Δ_t h_{t-1} + BΜ_t x_t, y_t = C_t h_t
h = A_bar[:, t] * h + B_bar[:, t] * x[:, t].unsqueeze(-1)
ys.append((h * Cm[:, t].unsqueeze(1)).sum(-1))
y = torch.stack(ys, dim=1) # [B, L, ED]
return y + self.D * x
class MambaBlock(nn.Module):
def __init__(self, d_model):
super().__init__()
d_inner = expand * d_model
self.in_proj = nn.Linear(d_model, 2 * d_inner, bias=False) # linear projection for the two branches (two of D β ED)
# Convolution along time. Per feature (groups), padded only on the left so it does not see the future
self.conv = nn.Conv1d(d_inner, d_inner, d_conv, groups=d_inner, padding=d_conv - 1)
self.ssm = SelectiveSSM(d_inner, d_state, dt_rank=math.ceil(d_model / 16))
self.out_proj = nn.Linear(d_inner, d_model, bias=False) # ED β D
def forward(self, x): # x: [B, L, D]
L = x.shape[1]
u, z = self.in_proj(x).chunk(2, dim=-1)
u = self.conv(u.transpose(1, 2))[..., :L].transpose(1, 2) # use only the first L (causal)
y = self.ssm(F.silu(u))
return self.out_proj(y * F.silu(z)) # multiply by the gate branch
class MambaLM(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(vocab + 1, d_model) # index vocab is the "answer now" cue
self.norms = nn.ModuleList([nn.LayerNorm(d_model) for _ in range(n_layers)])
self.blocks = nn.ModuleList([MambaBlock(d_model) for _ in range(n_layers)])
self.head = nn.Linear(d_model, vocab)
def forward(self, tokens):
x = self.embed(tokens)
for norm, blk in zip(self.norms, self.blocks):
x = x + blk(norm(x)) # norm β block β residual connection
return self.head(x)
def make_batch(n):
"""Place tokens at random positions among noise (0), append n_memorize cues at the end, and ask for them in order"""
body = torch.zeros(n, seq_len, dtype=torch.long)
targets = torch.randint(1, vocab, (n, n_memorize))
for i in range(n):
pos = torch.randperm(seq_len)[:n_memorize].sort().values
body[i, pos] = targets[i]
cue = torch.full((n, n_memorize), vocab)
return torch.cat([body, cue], dim=1).to(device), targets.to(device)
model = MambaLM().to(device)
optimizer = optim.AdamW(model.parameters(), lr=learning_rate)
criterion = nn.CrossEntropyLoss()
model.train()
for step in tqdm(range(steps)):
x, y = make_batch(batch_size)
logits = model(x)[:, -n_memorize:] # answer at the cue positions
loss = criterion(logits.reshape(-1, vocab), y.reshape(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
x, y = make_batch(500)
acc = (model(x)[:, -n_memorize:].argmax(-1) == y).float().mean().item()
print(f'accuracy: {acc:.3f}')
FAQ
Q. What is the difference between Mamba and S4?
A.
In S4, Ξ,A,B,C are the same at every time step (linear time-invariant), and the model is computed as a single-kernel convolution. Mamba computes Ξ,B,C from the input xtβ, so the update rule changes at every time step and the model can choose to remember or ignore depending on the content. In exchange, it cannot be computed as a convolution and is computed with a parallel scan instead.
Q. Is Mamba an RNN?
A.
At inference, it runs as a linear RNN that updates a fixed-size state htβ one step at a time. However, because the state update is linear in the input (htβ=AΛtβhtβ1β+BΛtβxtβ), training can compute the whole sequence in parallel with a parallel scan. As Theorem 1 of the paper shows, Ξ plays the same role as an RNN gate.
Q. What is S6 in the Mamba paper?
A.
It is the SSM with the selection mechanism. It stands for "S4 with a selection mechanism, computed with a scan", and the paper's experiment tables abbreviate the selective SSM as S6.