Mamba and Mamba-2: Selective State Spaces and Structured State Space Duality
Building Mamba and Mamba-2 from scratch — why fixed-dynamics state space models cannot do content-based reasoning, how the selection mechanism fixes it, and the structured-matrix duality showing every selective SSM is masked attention in disguise.
A state space model (SSM) is a sequence model rooted in control theory: a hidden state evolves through time according to a linear differential equation, driven by the input. Discretize the equation, plug in trainable matrices, and you get a sequence layer that runs as a recurrence at inference, scales linearly in sequence length, and looks nothing like attention. The catch is that classical SSMs apply the same transformation to every token regardless of what the token contains — a property that makes them excellent at signal processing and hopeless at selective recall like “Harry … Harry Potter”.
This post derives Mamba and Mamba-2, the two papers that fixed this. The first paper makes the SSM parameters input-dependent so the model can decide per token whether to read or skip. The second reveals that this selective SSM is, under a natural restriction, the same function as a structured form of masked attention computed by a different algorithm. We will work through both papers using a 4-token running example, and arrive at the structured state space duality that ties SSMs and attention together. Concretely, we draw from:
-
Gu and Dao (2023), “Mamba: Linear-Time Sequence Modeling with Selective State Spaces”: identifies the fundamental limitation of prior SSMs (fixed dynamics cannot reason about content), introduces the selection mechanism that makes SSM parameters input-dependent, and proposes a hardware-aware architecture that matches Transformer quality for the first time.
-
Dao and Gu (2024), “Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality”: reveals that SSMs and attention are not separate ideas but two algorithms for computing the same function on semiseparable matrices, uses this duality to design a faster algorithm (SSD) that leverages matrix multiplication units, and proposes the Mamba-2 architecture that is 2–8× faster than Mamba while improving quality.
The first paper says: give SSMs the ability to select. The second paper says: selection makes SSMs equivalent to a form of attention. Together, they close the loop between the two paradigms.
The Running Example
We use a single-channel input sequence of 4 tokens:
This represents one channel () of a sequence after the input projection. For the SSM, we use a state dimension of (the simplest possible latent state — a single scalar). For the model-scale analysis, we use the same parameters as the series: , layers.
For the selective SSM and the Mamba-2 duality sections, we extend to a multi-channel example with and head dimension .
1. State Space Models
1.1 The continuous system
We will build the state space model one concept at a time. Each piece answers one question.
What is a “state”?
The state is a small running summary of everything the model has seen so far. We denote it , where is time and is how many numbers the summary contains. Imagine a bucket sitting under a tap. The tap drips water in (the input), the bucket has a small hole at the bottom that drips water out (forgetting), and at any moment the only thing that matters about the past is the current water level. That water level is the state. Everything the model “remembers” must fit inside it.
In our running example we will pick the smallest possible state: , a single scalar. So the bucket holds just one number.
How does the state change?
The state evolves continuously over time. We need an equation that says how it changes from one instant to the next. Two things can change the state: the state itself (the bucket leaks proportional to how full it is), and the current input (water arriving through the tap). The simplest equation that captures both is:
Read this slowly. is the rate of change of the state — how fast the bucket level is rising or falling at this exact moment. is the part of that change that depends on the current state itself (the leak). is the part driven by the current input (the tap). Add the two contributions and you get the total rate of change.
There is a separate equation for what we read out of the state at each moment:
This says the output is just a linear measurement of the current state. We do not get to look directly at the input when producing the output — everything must flow through the state.
What do , , and do?
Each matrix has one job. is the state matrix: it controls how the state evolves on its own (how fast the bucket leaks, and in our scalar case, whether the leak is even leaking — if were positive instead of negative, the bucket would refill itself). is the input matrix: it controls how the new input enters the state (how wide the tap is). is the output matrix: it controls how we read out of the state (which dipstick we use to measure the level). Together, , , and fully specify the system’s behavior. This setup is the linear time-invariant (LTI) system from classical control theory (Kalman, 1960), and the entire space of possible state trajectories — what could ever happen to — is called the state space.
What does “time-invariant” mean?
The matrices , , do not depend on . The bucket has the same hole size and the same tap width at every moment. Pour the same water in at or at and the bucket level reacts identically. This is what time-invariant means: the rule that governs the system is the same at every instant.
This sounds innocent. It will turn out to be the entire problem we eventually need to fix in Section 2 — because in language modeling, we want the rule to depend on what token just arrived.
Plugging in the running example
For our running example with , we pick , , . The state equation becomes:
This is the canonical leaky integrator: the state grows by whatever you put in (the term, which is with ) and shrinks in proportion to how much is currently there (the term, which is with ). The decay rate is , meaning that if you stop pouring anything in, the bucket loses about 63% of its level per unit of time. This is the same dynamics as an RC circuit discharging through a resistor, or a hot cup of coffee cooling toward room temperature — equations from physics that share the same first-order structure.
1.2 Discretization
Why we need to discretize
The state equation we just wrote down is a continuous-time equation: it talks about , the rate of change of the state at every real-numbered moment in time. But neural networks do not see continuous signals. They see a discrete sequence of tokens arriving one at a time. We need a way to convert “the continuous bucket equation” into “a recurrence that takes one token in and produces one new state out.” That conversion is called discretization.
A discretization rule is a recipe with one job: turn the continuous parameters into discrete parameters such that the discrete recurrence produces the same trajectory at sample points that the continuous bucket would have produced.
What is ?
is the step size: how much continuous time elapses between two adjacent tokens. It is a knob. Crank it small, and adjacent tokens are very close together in continuous time — the bucket barely changes between them. Crank it large, and adjacent tokens are far apart in continuous time — the bucket has long stretches to leak and fill. So controls how aggressively each new token affects the state. We will see in Section 2.3 that this knob is exactly what Mamba turns into a learnable, input-dependent quantity.
What does “zero-order hold” mean?
To do the conversion, we have to make some assumption about what the input is doing between samples — between, say, and . We only have a sample at and a sample at . What happens in between? The simplest possible answer is: it stays at the value it had at . The input is a flat plateau between samples. That assumption is called the zero-order hold (ZOH): we hold the input constant (“zero-order” means “constant,” as opposed to “first-order” which would be linear interpolation, etc.). Under this pretense, the continuous equation can be integrated exactly between samples, and we get the closed-form discrete update:
Two formulas. The first says: in seconds, the bucket leaks by a factor of on its own (with , this is between 0 and 1). The second says: how much new input gets pumped into the bucket during that same interval, accounting for the fact that it leaks while it fills.
Where these formulas come from
The two boxed expressions for and are not assumed — they are derived. The continuous equation is a first-order linear ODE; solving it with the integrating factor method gives a closed-form expression for in terms of and an integral of the input over . Under ZOH the input is constant on that interval, so it factors out of the integral, and what remains evaluates to via a matrix-exponential integral identity. Reading off the coefficients of and in the resulting expression gives the two formulas above. The full step-by-step derivation — integrating factor, matrix exponential, the integral identity, and the ZOH substitution — is in Mathematical Prerequisites for Mamba, Sections 2 through 5.
Plugging in the running example
For , , (one second between samples):
So one second of leak shrinks the bucket level to 36.8% of what it was — equivalently, 63.2% leaks out. That matches the leaky-integrator interpretation from Section 1.1.
So 63.2% of the new input gets written into the bucket per step. Notice that in this scalar case — the fraction that leaks out and the fraction that gets written in sum to 1. The bucket update is a convex combination of the old level and the new input. We will see in Section 2 that this identity is exactly what makes the discretized SSM equivalent to a classical RNN gate.
1.3 The discrete recurrence
With the discretized parameters, the SSM becomes a linear recurrence:
For our running example with , , , :
Step : .
Step : .
Step : .
Step : .
The output is .
1.4 The convolutional form
Since the parameters are constant across time (the LTI property), the recurrence can be unrolled into a global convolution. Let us derive this.
Expanding the recurrence:
The pattern: .
Multiplying by :
Define the SSM convolution kernel . Then:
For our running example:
Numerical check for :
Numerical check for :
This matches from the recurrence (the difference is rounding in the kernel coefficients).
1.5 The dual computation modes
This is the crucial property. The SSM has two equivalent computation modes:
-
Recurrent mode (equation in Section 1.3): processes one token at a time with memory per step. Total cost: for tokens. Ideal for autoregressive inference.
-
Convolutional mode (equation in Section 1.4): processes the entire sequence at once via an FFT-based convolution. Total cost: for tokens. Ideal for parallel training.
Prior SSMs (S4, DSS, S4D, S5, H3, Hyena) exploit this duality: train with convolutions, infer with recurrence. The convolutional mode gives training parallelism. The recurrent mode gives constant-time inference per step.
1.6 The LTI property — and its limitation
The duality between recurrence and convolution only exists because are constant across time. This is the linear time-invariance (LTI) property. The bucket has the same hole and the same tap width at every step, regardless of which token just walked in the door.
LTI is a double-edged sword. On one hand it enables convolutions, because a single fixed kernel can be applied everywhere. On the other hand it prevents content-based reasoning — the model cannot decide to pay attention to one token and ignore another based on what those tokens actually contain. To see why this matters concretely: imagine a sequence “Harry … (lots of irrelevant words) … Harry Potter,” and you want to predict “Potter” after seeing the second “Harry.” The model has to recognize that the current token matches a token it saw earlier and route information based on that match. But an LTI SSM applies the same at every step — it cannot make any decision conditional on what the input looks like. The dynamics are frozen. Mamba’s whole job is to unfreeze them.
2. Why Selection Matters
2.1 The failure mode
Gu and Dao (2023) identify two tasks that reveal the LTI limitation:
The Selective Copying task modifies the standard Copying task by randomizing the spacing between tokens that need to be memorized. The standard Copying task has constant spacing, so a fixed convolution kernel can solve it by simply counting positions. The Selective Copying task has random spacing, so the model must look at the content of each token to decide whether to memorize it.
The Induction Heads task requires the model to perform associative recall: given a pattern like “Harry … Harry Potter”, the model must predict “Potter” when it sees the second “Harry”. This requires recognizing that the current token matches a previously seen token — a content-dependent operation.
LTI SSMs fail on both tasks. From the recurrent view, the transitions are constant, so the model cannot selectively focus on or ignore tokens based on their content. From the convolutional view, a fixed convolution kernel is inherently position-aware but not content-aware — it cannot vary the spacing dynamically.
2.2 What selection means
The solution is to make the SSM parameters functions of the input. Instead of fixed , the selective SSM uses:
where denotes a learned linear projection to dimension , and ensures .
The softplus function is , a smooth approximation to . It is always positive: for all .
The matrix remains fixed (not input-dependent). Gu and Dao hypothesize that making selective in addition to would have similar performance, since already controls through the discretization .
The critical consequence: once vary with time, the parameters are no longer constant. The LTI property breaks. The convolution kernel is no longer well-defined (it would need to be different at every position). The convolutional computation mode is lost.
This is the fundamental tradeoff. Selection gives the model content-dependent dynamics. But it removes the fast convolutional training path. The model must be computed recurrently — or with a new algorithm.
2.3 Interpretation of
Of the three input-dependent parameters , the most important is — and the easiest way to see why is to think of it as a knob between two extremes. controls the balance between focusing on the current input and persisting the state . Mechanistically:
-
A large means (since has negative entries) and large. The state is reset, and the current input is written strongly. The system is “selecting” .
-
A small means and . The state is preserved, and the current input is ignored. The system is “skipping” .
This is exactly the behavior needed for Selective Copying: the model should produce large for content tokens and small for noise tokens.
2.4 Numerical example: selective vs. non-selective
Let us trace the selective SSM for our running example. We keep , , but now varies.
Suppose the selection mechanism produces:
This says: focus on tokens 1 and 4, ignore tokens 2 and 3.
Step : .
Wait — let us be more careful with the ZOH formula. For the scalar case with :
This uses the simplification: . The in the numerator and denominator cancel (by algebraic cancellation).
So:
Note that . This is a convex combination of the previous state and the current input. This identity holds specifically for the scalar case , with ZOH discretization.
Step : .
Strong focus on : the state captures 86.5% of the input.
Step : .
The state barely changed: 90.5% of the previous state is retained, and only 9.5% of the new input enters. Token 2 is effectively ignored.
Step : .
Again, the state is mostly preserved. Token 3 is ignored.
Step : .
Strong focus on : the state is mostly overwritten.
Compare the outputs:
- Non-selective (Section 1.3):
- Selective:
The selective model retains the signal from token 1 through tokens 2 and 3 (where stays near 0.8), then switches to capture token 4. The non-selective model treats all tokens equally, leading to the state collapsing near zero at token 3 (because partially cancels the accumulated positive state).
3. The Connection to Gating
3.1 Theorem 1: selective SSMs are gated RNNs
Gu and Dao (2023) prove that the selective SSM, under specific parameter choices, reduces exactly to a classical gated RNN. This is Theorem 1 of the Mamba paper.
Theorem 1. When , , , , and , the selective SSM recurrence takes the form:
where is the sigmoid function .
3.2 Proof
The proof is in Appendix C of the Mamba paper. Let us re-derive it step by step.
The continuous system with , , is:
The discretization step size is:
We observe that the Parameter can be absorbed as a bias term in the linear projection. So we write where includes the bias.
Applying ZOH with :
Now we use the identity , so . Exponentiating:
Therefore:
By the sigmoid reflection identity :
Define . Then .
For , we showed in Section 2.4 that .
The recurrence becomes:
This is exactly the gated recurrence.
3.3 Numerical verification
For with (a concrete linear projection):
Cross-check via :
For :
The gate is small (), so the model retains most of the state and largely ignores . This is the selection mechanism in action.
3.4 Interpretation
The connection to gating is not merely formal. It means that discretization of SSMs is the principled foundation of heuristic gating mechanisms. The gate in an LSTM or GRU was introduced as a heuristic to control information flow. The SSM perspective derives the same gate from first principles: start with a continuous dynamical system, discretize with ZOH, and the gate emerges naturally from the interaction between and .
This also explains why making input-dependent is the most important selective parameter. Table 7 of the Mamba paper ablates the three selective parameters (, , ). Making alone selective reduces perplexity from 10.93 (no selection) to 10.15. Making or alone selective gives smaller improvements (10.93 → 10.15 for vs 10.93 → 9.98 for vs 10.93 → 9.81 for all three). is the most important because it directly controls the gate — it determines whether to read or skip each token.
4. The Mamba Architecture
4.1 The architecture
Prior SSM architectures (H3, Hyena) interleave an SSM layer with an MLP block, following the Transformer’s pattern of alternating attention and MLP. Mamba simplifies this by merging the two blocks into one.
The Mamba block consists of:
-
Input projection: , where is the expansion factor (typically ).
-
Short convolution: a 1D depthwise convolution with kernel size (typically ) applied to . This provides local context before the SSM.
-
SSM: the selective state space model applied to the convolved . The parameters are computed from the post-convolution activation.
-
Gating: the SSM output is multiplied element-wise by , where is the SiLU (Sigmoid Linear Unit) activation .
-
Output projection: the gated result is projected back to .
The SiLU gating makes the Mamba block analogous to a SwiGLU MLP (Shazeer, 2020) — a variant of the standard two-layer MLP in which one of the linear branches is multiplied element-wise by a Swish-activated copy of the input, used in PaLM and LLaMA. Compared to the MLP block, Mamba simply adds a convolution and SSM to the main branch.
4.2 Parameter count
For each Mamba block with model dimension and expansion factor :
- Input projections: (for and )
- Output projection:
- Total from projections:
With , this is per block. The SSM parameters (, projections for , , ) are much smaller in comparison. Two Mamba blocks (stacked homogeneously) match the parameters of a Transformer layer (one attention + one MLP):
4.3 Key results
Mamba achieves several firsts:
-
Selective Copying: Mamba solves the task with 99.8% accuracy, compared to 97.0% for S4 (no gate) and 18.3% for S4 without the selection mechanism (Table 1).
-
Induction Heads: Mamba extrapolates perfectly to sequences 4000× longer than training length ( training → test). No other method exceeds 2× extrapolation (Table 2).
-
Language modeling: Mamba is the first linear-time model to match the quality of a strong Transformer++ recipe (PaLM/LLaMA-style) on scaling laws from 125M to 1.3B parameters (Figure 4). Mamba-3B matches Transformers at twice the size on downstream tasks.
-
Inference throughput: Mamba achieves 4–5× higher generation throughput than a Transformer of similar size, because it does not require a KV cache that grows with sequence length.
5. The Hardware-Aware Algorithm
5.1 The problem
The selective SSM loses the convolutional computation mode. The naive recurrence requires materializing the expanded state in GPU HBM (high-bandwidth memory), which is prohibitively large. For batch size , sequence length , , : the state requires GB in fp16.
5.2 The solution: kernel fusion
The key insight is that the SSM can be computed entirely in fast SRAM (on-chip memory), without materializing the full state in HBM.
- Load the SSM parameters from HBM to SRAM. Size: .
- Compute discretization () in SRAM.
- Perform the selective scan (recurrence) in SRAM.
- Multiply by and write the output back to HBM.
The intermediate states of size never leave SRAM. This reduces memory IOs by a factor of (the state dimension), which in practice gives 20–40× speedup over a naive implementation.
5.3 Parallel scan
Despite being sequential in nature, the recurrence can be parallelized with a parallel associative scan (Blelloch, 1990). The key observation: the recurrence can be written as an associative binary operation on pairs . The scan computes all prefix products in parallel steps, using work.
5.4 Recomputation
To reduce memory during training, Mamba does not save intermediate states for backpropagation. Instead, it recomputes them in the backward pass by reloading the inputs from HBM and re-running the scan in SRAM. This is the same technique as gradient checkpointing in Transformers (e.g., FlashAttention). The result: the selective SSM layer uses the same activation memory as a FlashAttention layer.
6. SSMs Are Structured Matrices
We now turn to the second paper (Dao and Gu, 2024), which reveals a deep connection between SSMs and attention. The starting point is a simple observation: every SSM can be written as a matrix multiplication.
6.1 The matrix transformation form
Recall the SSM recurrence:
Unrolling this from — multiply out in turn and collect the contribution of each input — produces a closed-form expression for as a sum over the inputs, each weighted by a cumulative product of the matrices that came after it. The full unrolling is derived in Mathematical Prerequisites for Mamba, Section 6. The result is
where denotes the cumulative product of the matrices from time to , with the convention .
Multiplying by :
This is a matrix-vector product where:
and for (causality). The matrix is lower-triangular.
6.2 Semiseparable matrices
Dao and Gu (2024) identify the matrix as belonging to a well-studied class called semiseparable matrices.
Definition 3.1. A lower-triangular matrix is N-semiseparable if every submatrix contained in the lower-triangular portion has rank at most N.
The SSM matrix satisfies this with equal to the state dimension: the formula factors any lower-triangular submatrix as an outer product of a chain of ‘s and a chain of ‘s, capped at rank . This is Theorem 3.5 of the paper: the SSM transformation is identical to matrix multiplication by an N-semiseparable matrix .
6.3 The scalar case: 1-semiseparable matrices
The most important special case is when is a scalar times the identity: for some scalar . The cumulative product collapses to a scalar, where , and the matrix factors as
where is a 1-semiseparable matrix (also called a 1-SS matrix) and denotes the Hadamard (element-wise) product. The 1-SS structure of — a lower-triangular matrix whose every entry below the diagonal is a cumulative product, equivalently whose every lower-triangular submatrix has rank at most 1 — is derived directly from the unrolling in Mathematical Prerequisites for Mamba, Section 7, where the explicit rank-1 factorization is built up from first principles.
Concretely, has the form:
Each entry is a cumulative product of consecutive values. The diagonal is all 1’s. This is the structured mask — it replaces the causal mask of standard attention.
6.4 Numerical example
Let us trace through a 4-token example with scalar . We use and:
(Here , , are all 1-dimensional per token since .)
The 1-SS mask :
Note: is not used in because involves the product , and the first row only has .
The Gram matrix :
The full matrix (element-wise product, lower-triangular):
Output :
We can verify via the recurrence. With scalar , the recurrence is:
The matrix form and recurrence produce the same output.
6.5 Interpretation
The matrix encodes the full input-output map of the SSM. The recurrent mode computes by exploiting the sequential structure (each row depends on the previous state). The quadratic mode computes by materializing and doing direct matrix multiplication. These are two algorithms for the same computation — one is time, the other is time but more hardware-friendly because it uses matrix multiplications.
This is the core insight of the Mamba-2 paper: different methods of computing SSMs can be reframed as different algorithms for multiplying by semiseparable matrices.
7. Structured State Space Duality
7.1 From SSMs to attention
The matrix form with looks strikingly similar to masked attention:
In standard causal attention, is the lower-triangular matrix of all 1’s (the causal mask), and are queries and keys, and is the value matrix. In the SSM, is the 1-semiseparable mask of cumulative decay products, plays the role of queries, plays the role of keys, and plays the role of values.
The correspondence is exact:
| SSM | Attention |
|---|---|
| (output matrix) | (queries) |
| (input matrix) | (keys) |
| (input sequence) | (values) |
| (cumulative product) | (mask entry) |
| (state dimension) | (feature dimension) |
7.2 The duality
Dao and Gu (2024) make this precise with structured state space duality (SSD).
State space models are usually defined through a recurrence (Definition 2.2 of the paper) and computed with a linear-time algorithm (the scan). Attention is usually defined through pairwise comparisons (equation 9) and computed with a quadratic-time algorithm (materializing ).
But both have dual forms:
-
An SSM can be computed quadratically by materializing and multiplying . This is the quadratic (attention-like) mode.
-
Attention can be computed linearly by using the cumsum trick from the linear attention framework (Katharopoulos et al., 2020). This is the linear (recurrent) mode.
The duality says: for scalar-identity matrices, these are the same function computed by different algorithms. The SSM recurrence is the linear mode. Materializing is the quadratic mode. They produce identical outputs.
7.3 The SSD layer
The state space dual (SSD) layer is the specific SSM that the duality applies to. Compared to Mamba’s selective SSM (S6), SSD makes two simplifications:
-
is restricted from diagonal to scalar times identity: . Each is a single scalar shared across all state dimensions.
-
The head dimension is increased from (in Mamba) to or (matching Transformer conventions).
The first restriction slightly decreases expressivity but enables the quadratic mode. The second compensates by using attention-like multi-head structure.
7.4 Why scalar matters
With diagonal , each state dimension has an independent decay rate. The matrix becomes:
This involves different 1-SS masks, one per state dimension. The quadratic mode requires materializing all masks and their Hadamard products, which is expensive.
With scalar , all state dimensions share the same decay: for all . The matrix simplifies to with a single mask , and the quadratic mode becomes a single masked matrix multiplication — just like attention.
8. The SSD Algorithm
8.1 The idea
The linear (recurrent) mode takes time. The quadratic (attention-like) mode takes time. Neither is optimal in practice:
- The recurrent mode is sequential and cannot exploit matrix multiplication units (tensor cores on GPUs).
- The quadratic mode is parallelizable but scales poorly with sequence length.
The SSD algorithm combines both: split the sequence into chunks, compute within each chunk quadratically (using matmul), and connect chunks recurrently (using a scan). This is a block decomposition of the semiseparable matrix .
8.2 Block decomposition
Partition the -length sequence into chunks of size . The matrix decomposes into blocks:
The diagonal blocks represent intra-chunk interactions. They are small () and can be computed quadratically using matrix multiplication.
The off-diagonal blocks for represent inter-chunk interactions. By the semiseparable property, these blocks are low-rank (rank at most ). They factor as:
The center factors are connected by a scalar recurrence (a 1-SS multiplication of length ), which is times shorter than the original sequence.
8.3 The four steps
The SSD algorithm has four steps:
Step 1: Diagonal blocks (intra-chunk). For each chunk , compute the output from tokens within the chunk using the quadratic form:
This is a batched matrix multiplication. Cost: .
Step 2: Right factors (chunk → state). For each chunk, compute the final state assuming the initial state is zero:
This is a matrix multiplication. Cost: .
Step 3: Center factors (state → state). Connect the chunks by propagating states through a scalar SSM scan of length :
This is a 1-SS multiplication on independent channels. Cost: — negligible.
Step 4: Left factors (state → output). For each chunk, compute the output contribution from prior chunks:
This is a matrix multiplication. Cost: .
Final output: .
8.4 Complexity
Setting (state dimension = head dimension = chunk length):
- Total FLOPs: — same as attention but linear in for the dominant terms.
- Total memory: — linear in both sequence length and state size.
- The work is dominated by matrix multiplications on matrices.
This is the key advantage over Mamba’s selective scan: SSD uses matrix multiplication as its core primitive, which tensor cores are optimized for. Mamba’s scan is a custom CUDA kernel that cannot leverage these hardware units.
8.5 Speed comparison
The SSD algorithm is 2–8× faster than Mamba’s fused selective scan (Figure 10 of the Mamba-2 paper). For large state expansion (), SSD is 6× faster. For the default , SSD is 2× faster. SSD is also faster than FlashAttention-2 at sequence lengths beyond 2K and 6× faster at 16K.
9. The Mamba-2 Architecture
9.1 Block design changes
The Mamba-2 block modifies the Mamba block in two ways motivated by the attention connection:
Parallel parameter projections. In Mamba, the SSM parameters are computed from the post-convolution activation , which depends on the initial linear projection. The projections are sequential.
In Mamba-2, are all produced from the input in parallel — analogous to how are produced in parallel in a Transformer. This slightly reduces parameters and, more importantly, enables tensor parallelism for larger models by reducing the number of synchronization points per block from two to one.
Extra normalization. Mamba-2 adds a normalization layer (GroupNorm or RMSNorm) after the gating multiplication and before the output projection. GroupNorm (Wu and He, 2018) splits a feature vector into groups of channels and normalizes each group independently to zero mean and unit variance, sitting between LayerNorm (one group, the whole vector) and InstanceNorm (one group per channel). This improves training stability at larger scales and is analogous to the NormFormer architecture (Shleifer, Weston, and Ott, 2021) that adds normalization at the end of MLP and attention blocks.
9.2 Multi-head patterns
The state space duality allows transferring multi-head design choices from attention to SSMs.
Multi-head SSM (MHS) / Multi-head attention (MHA). The classic pattern: independent heads, each with its own . The state size per head is , and the head dimension is .
Multi-input SSM (MIS) / Multi-value attention (MVA). The original Mamba architecture uses this pattern: has heads (one per channel), but and are shared across all heads. In attention terms, the keys and queries are shared while the values have independent heads. This is the natural choice from the SSM perspective because is the main input to the SSM, while and are auxiliary parameters.
Grouped-input SSM (GIS) / Grouped-value attention (GVA). Analogous to grouped-query attention (GQA), this creates groups of and projections, each shared across input heads. Mamba-2 uses this pattern with set to be a multiple of the tensor parallelism degree for efficient sharding.
The paper ablates these patterns (Table 5) and finds that the MVA/MIS pattern performs best, matching the choice naturally derived from the SSM perspective.
9.3 Kernel feature maps
The SSD framework allows incorporating kernel feature maps from the linear attention literature. In Mamba-2, the feature map is applied to the and branches (corresponding to and in attention). By default, , following Mamba’s SiLU activation.
The paper ablates various kernel approximations (Table 6): cosFormer, Random Feature Attention, and Positive Random Features (Performer). None significantly improve over simple pointwise nonlinearities. This is expected because SSD differs from vanilla linear attention by the inclusion of the 1-semiseparable mask , which already captures positional structure that kernel approximations were designed to provide.
9.4 Hybrid architectures
A striking finding from the Mamba-2 paper is that mixing SSD layers with attention layers improves over either alone. Table 2 shows that adding approximately 10% attention layers (6 out of 48 layers in a 350M model) reduces perplexity from 8.60 (pure SSD) to 8.26, with the best configuration using 7 attention layers.
At the 2.7B scale (Table 3), a Mamba-2 + MLP + Attention hybrid (28 SSD + 4 attention + 32 MLP layers) achieves an average downstream accuracy of 60.7%, compared to 60.2% for pure Transformer++ and 60.2% for pure Mamba-2.
The hypothesis: SSM layers function as general sequence-to-sequence mappings that compress context into their recurrent state, while attention layers act as a retrieval mechanism that can refer directly to previous tokens without compression. A small number of attention layers provides an “escape hatch” for tasks that require exact token lookup, while SSD handles the bulk of the computation more efficiently.
10. Scaling Results
10.1 Mamba scaling laws
On the Pile dataset (Figure 4 of the Mamba paper), Mamba matches Transformer++ scaling from 125M to 1.3B parameters at context length 2048. At context length 8192, Mamba further improves relative to Transformers (which are limited by the quadratic cost of longer sequences).
On downstream zero-shot evaluations (Table 3), Mamba at each model size matches baselines at twice the size:
- Mamba-130M matches Pythia-160M
- Mamba-370M matches Pythia-410M
- Mamba-1.4B matches Pythia-2.8B
10.2 Mamba-2 scaling laws
Mamba-2 is Pareto-dominant over both Mamba and Transformer++ (Figure 9 of the Mamba-2 paper): it achieves lower perplexity at every FLOP budget from 125M to 1.3B parameters. This is because SSD is both faster (enabling more training tokens per wall-clock hour) and slightly more expressive (due to larger state sizes enabled by the efficient algorithm).
On downstream evaluations at 2.7B scale (Table 1 of the Mamba-2 paper), Mamba-2 matches Mamba’s quality while being 2–8× faster to train.
10.3 State expansion
One of SSD’s most important practical benefits is efficient state expansion. In Mamba, increasing the state dimension from 16 to 64 provides a significant perplexity improvement (from 9.82 to 8.71 for a 350M model — Table 10 of the Mamba paper) but at the cost of proportionally slower selective scan.
In Mamba-2, the SSD algorithm’s speed is nearly independent of up to (Figure 10, right panel). This allows Mamba-2 to use much larger state sizes without slowdown, effectively making the capacity-efficiency tradeoff from the Kernel Zoo blog far less severe.
11. The Full Picture: From Selection to Duality
11.1 The progression
The two papers together tell a coherent story:
-
Prior SSMs (S4, S5, H3, Hyena) are LTI systems. They process sequences through convolutions during training and recurrence during inference. They are fast but cannot do content-based reasoning.
-
Mamba makes the SSM parameters input-dependent (selective). This enables content-based reasoning and matches Transformer quality. But the convolutional mode is lost, and the model relies on a custom scan kernel.
-
Mamba-2 reveals that selective SSMs with scalar are equivalent to a form of structured attention. This equivalence — structured state space duality — exposes both a quadratic (attention-like) and a linear (recurrence-like) algorithm. The SSD algorithm combines both by chunking the sequence: quadratic within chunks, linear between chunks. The result is faster than both pure attention and pure recurrence.
11.2 Connection to the blog series
The linear attention framework from the Why Replace Attention blog replaces the softmax with a kernel: , where is the all-1’s causal mask. RetNet replaces with a decay mask . The Gated DeltaNet blog modifies the recurrent update rule.
SSD generalizes all of these. The mask is a 1-semiseparable matrix with input-dependent entries , not fixed scalars. This means:
- Linear attention is SSD with for all (no decay, causal mask of 1’s).
- RetNet is SSD with for all (constant decay).
- Mamba-2 is SSD with varying per token (input-dependent decay).
The feature map and the mask are orthogonal design choices. The Kernel Zoo blog explored . The SSD framework shows that — the structured mask — is equally important, and that making input-dependent is what gives SSMs their selectivity.
Summary
State space models process sequences through a latent state governed by a linear recurrence, with dual convolutional and recurrent computation modes. Prior SSMs kept their parameters fixed (LTI), which enabled convolutions but prevented content-based reasoning. Mamba introduces selection — making , , functions of the input — which breaks the LTI property but gives the model a learnable gate (, equivalent to the ZOH discretization of a leaky integrator) that decides per token whether to read or skip. Mamba-2 then reveals the deeper structure: every SSM is a multiplication by a semiseparable matrix, and when is scalar, this matrix factors as a 1-semiseparable mask times a Gram matrix — exactly the structure of masked attention with an input-dependent decay mask. The SSD algorithm exploits this duality through block decomposition: quadratic attention within chunks (leveraging matrix multiplication hardware), linear recurrence between chunks (keeping the cost linear in sequence length), producing an architecture that is 2–8× faster than Mamba’s custom scan while matching or exceeding Transformer quality at scales up to 2.7B parameters.
Previous: Mathematical Prerequisites for Mamba
Next: The Efficient Transformer Design Space: Comparing All Variants and the Three Futures of Attention
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.