Skip to content
AI360Xpert
Beta

Mamba & Mamba-2 Architecture

Mamba makes state space models selectively content-aware by generating transition matrices directly from input tokens, while Mamba-2 unifies this recurrence with attention via matrix duality.

Mamba-1 replaces static convolutions with content-dependent selective scans, while Mamba-2 unifies selective recurrence with structured matrix multiplication
Mamba-1 replaces static convolutions with content-dependent selective scans, while Mamba-2 unifies selective recurrence with structured matrix multiplication

Why Does This Exist?

Prior Structured State Space models such as s4 established that linear time-invariant (LTI) systems can train in parallel via Fast Fourier Transform (FFT) convolutions while serving autoregressively in O(1)O(1) constant time. Despite their computational elegance, LTI models hit a fundamental capability ceiling on language and reasoning tasks. Because their state transition matrices (Aˉ,Bˉ,C)(\bar{A}, \bar{B}, C) are fixed constants across all time steps, an LTI system cannot decide to retain or discard information based on what it reads. It compresses every incoming token into its state vector with identical weight, making it mathematically incapable of solving selective copying or associative retrieval ("needle in a haystack").

Transformers solve this effortlessly via input-dependent attention weights (QKTQK^T), but pay an O(L2)O(L^2) computation cost and require hundreds of gigabytes of Key-Value cache memory at scale.

Mamba (Mamba-1) broke this trade-off by making the state space parameters dynamic functions of the current input token xtx_t. However, making parameters time-varying destroys the convolutional representation: the convolution kernel Kˉ\bar{K} can no longer be precomputed, rendering standard FFT parallelization impossible. Mamba resolved this with a hardware-aware parallel associative scan executed directly in fast GPU on-chip SRAM.

Mamba-2 pushed this paradigm further by proving State Space Duality (SSD): a theoretical equivalence showing that selective SSMs and masked linear attention are dual perspectives of the same 1-semiseparable matrix transformation. By reformulating the recurrence as structured block-matrix multiplications, Mamba-2 utilizes GPU Tensor Cores natively, achieving 2 to 8 times higher training throughput than Mamba-1.

Before analyzing selective mechanics, make sure you understand the foundational continuous formulation in state-space models and quadratic attention in transformers.

Think of It Like This

A legal stenographer with selective highlighter pens

An LTI state space model like S4 is like a mechanical dictaphone that records room audio at an unvarying sampling rate. It records background traffic noise, throat-clearing, and legal arguments with the exact same fidelity. When storage fills up, all historical sounds are compressed equally, drowning the critical testimony in ambient noise.

Mamba-1 gives the stenographer cognitive discretion. When irrelevant banter or procedural noise enters the courtroom, the stenographer sets the step size Δt≈0\Delta_t \approx 0, effectively pressing pause on the tape recorder. When crucial testimony begins, Δt\Delta_t spikes, opening the input gate BtB_t and recording the statement into the memory state hth_t with high fidelity. The state vector only expends capacity on tokens that matter.

Mamba-2 recognizes that the stenographer’s selective transcript can be read in two identical ways:

  1. Sentence by sentence (the recurrent view, ideal for live testimony).
  2. As a block-structured reference ledger, where each witness's testimony is processed in chunks using high-speed optical scanners (Tensor Core matrix multiplications).

Both workflows produce the exact same final legal brief, but the structured ledger operates at industrial printing press speed.

How It Actually Works

Selective State Spaces, SRAM Fusion, and State Space Duality

1. The Mamba-1 Selection Mechanism

In Mamba-1, input sequence x∈RB×L×Dx \in \mathbb{R}^{B \times L \times D} passes through linear projection layers to dynamically generate time-varying discretization step sizes and projection matrices:

Bt=LinearN(xt),Ct=LinearN(xt),Δt=Softplus(ParameterΔ+LinearD(xt))B_t = \text{Linear}_N(x_t), \quad C_t = \text{Linear}_N(x_t), \quad \Delta_t = \text{Softplus}(\text{Parameter}_\Delta + \text{Linear}_D(x_t))

Here, Bt∈RB×L×NB_t \in \mathbb{R}^{B \times L \times N} and Ct∈RB×L×NC_t \in \mathbb{R}^{B \times L \times N} vary for each token, and Δt∈RB×L×D\Delta_t \in \mathbb{R}^{B \times L \times D} acts as a content-based gating mechanism. The continuous diagonal matrix A∈RD×NA \in \mathbb{R}^{D \times N} is discretized via zero-order hold (ZOH):

Aˉt=exp⁡(ΔtA),Bˉt=(ΔtA)−1(exp⁡(ΔtA)−I)⋅(ΔtBt)≈ΔtBt\bar{A}_t = \exp(\Delta_t A), \quad \bar{B}_t = (\Delta_t A)^{-1} (\exp(\Delta_t A) - I) \cdot (\Delta_t B_t) \approx \Delta_t B_t

The recurrent update equation becomes:

ht=Aˉtht−1+Bˉtxt,yt=Cthth_t = \bar{A}_t h_{t-1} + \bar{B}_t x_t, \quad y_t = C_t h_t

When Δt→0\Delta_t \to 0, Aˉt→I\bar{A}_t \to I and Bˉt→0\bar{B}_t \to 0: the current input xtx_t is ignored, and previous state ht−1h_{t-1} is preserved indefinitely. When Δt\Delta_t is large, Aˉt→0\bar{A}_t \to 0 and Bˉt\bar{B}_t absorbs xtx_t: the model resets its state and overwrites memory with fresh information.

2. Hardware-Aware Parallel Scan

Because Aˉt\bar{A}_t varies with time tt, global convolution is mathematically invalid. A naive sequential loop over L=100,000L = 100{,}000 steps on a GPU would cause severe memory bandwidth bottlenecks because reading and writing the state tensor h∈RB×L×D×Nh \in \mathbb{R}^{B \times L \times D \times N} across High-Bandwidth Memory (HBM, ~2 TB/s) is catastrophically slow.

Mamba bypasses HBM by fusing the scan into a single GPU kernel:

  1. Load parameters (x,Δ,A,B,C)(x, \Delta, A, B, C) from HBM to fast on-chip SRAM (~20 TB/s).
  2. Discretize Aˉt,Bˉt\bar{A}_t, \bar{B}_t in SRAM.
  3. Execute a parallel associative prefix scan (Blelloch scan) across time steps directly within GPU thread blocks.
  4. Compute yt=Cthty_t = C_t h_t and write only the final output y∈RB×L×Dy \in \mathbb{R}^{B \times L \times D} back to HBM.

Intermediate states hth_t are never saved to global GPU memory during the forward pass; they are recomputed on the fly during backpropagation via kernel recomputation.

3. Mamba-2 and State Space Duality (SSD)

Mamba-2 constrains the transition matrix AA to be a scalar multiplier per channel (A∈RA \in \mathbb{R}, scaled by identity INI_N). This simplifies the transformation into a 1-semiseparable matrix MM:

Mj,i={∏k=i+1jakif j≥i0if j<iM_{j, i} = \begin{cases} \prod_{k=i+1}^j a_k & \text{if } j \ge i \\ 0 & \text{if } j < i \end{cases}

The entire SSM operation over sequence length LL can be expressed as:

Y=(M∘(CBT))XY = \left( M \circ (C B^T) \right) X

Comparing this to causal linear attention Y=(Mask∘(QKT))VY = \left( \text{Mask} \circ (Q K^T) \right) V, the mapping is exact:

  • Query Q=CQ = C
  • Key K=BK = B
  • Value V=XV = X
  • Attention Mask Mj,iM_{j, i} is weighted by cumulative decay factors ∏ak\prod a_k.

Because Y=(M∘(CBT))XY = (M \circ (C B^T)) X is a structured matrix multiplication, Mamba-2 partitions the sequence into blocks (e.g., block size 64) and executes the intra-block computations using GPU Tensor Cores (Matrix Multiply-Accumulate / MMA instructions). This bridges the hardware utilization gap between SSMs and Transformers.

Worked Example

Consider a single state dimension (N=1N = 1) over 2 time steps (t=1,2t=1, 2) showing how Δt\Delta_t selectively retains or forgets memories:

Parameters:

A=−1.0,x1=10.0,x2=20.0A = -1.0, \quad x_1 = 10.0, \quad x_2 = 20.0

Time step 1 (Important token):

Let the model predict a large step size: Δ1=2.0\Delta_1 = 2.0.

Aˉ1=exp⁡(Δ1A)=exp⁡(2.0×−1.0)=exp⁡(−2.0)≈0.1353\bar{A}_1 = \exp(\Delta_1 A) = \exp(2.0 \times -1.0) = \exp(-2.0) \approx 0.1353 Bˉ1=Δ1=2.0\bar{B}_1 = \Delta_1 = 2.0

Assuming initial state h0=0.0h_0 = 0.0:

h1=Aˉ1h0+Bˉ1x1=0.1353(0.0)+2.0(10.0)=20.0h_1 = \bar{A}_1 h_0 + \bar{B}_1 x_1 = 0.1353(0.0) + 2.0(10.0) = 20.0

Token x1x_1 is absorbed into the state vector.

Time step 2 (Irrelevant distractor token):

The model encounters filler content and selects a tiny step size: Δ2=0.01\Delta_2 = 0.01.

Aˉ2=exp⁡(Δ2A)=exp⁡(0.01×−1.0)=exp⁡(−0.01)≈0.9900\bar{A}_2 = \exp(\Delta_2 A) = \exp(0.01 \times -1.0) = \exp(-0.01) \approx 0.9900 Bˉ2=Δ2=0.01\bar{B}_2 = \Delta_2 = 0.01

Updating the state:

h2=Aˉ2h1+Bˉ2x2=0.9900(20.0)+0.01(20.0)=19.80+0.20=20.00h_2 = \bar{A}_2 h_1 + \bar{B}_2 x_2 = 0.9900(20.0) + 0.01(20.0) = 19.80 + 0.20 = 20.00

Notice that even though distractor input x2x_2 had twice the magnitude of x1x_1 (20.020.0 vs 10.010.0), the selective gate Δ2\Delta_2 suppressed x2x_2's contribution to just 0.200.20, while preserving 99% of prior memory h1h_1 (19.8019.80).

Code

Here is a minimal, self-contained Python implementation of the selective associative scan showing how content-dependent Δ\Delta modulates state evolution:

import numpy as np

def selective_ssm_step(    x: np.ndarray, delta: np.ndarray, a_scalar: float, b: np.ndarray, c: np.ndarray) -> np.ndarray:    """Simulate a selective SSM forward pass across sequence length L."""    seq_len = x.shape[0]    state_dim = b.shape[1]    y = np.zeros(seq_len)
    h = np.zeros(state_dim)
    for t in range(seq_len):        # Discretize continuous parameters based on input-dependent delta[t]        a_bar = np.exp(delta[t] * a_scalar)        b_bar = delta[t] * b[t]
        # Selective recurrent state update        h = a_bar * h + b_bar * x[t]        y[t] = np.dot(c[t], h)
    return y

# Sequence of 3 tokens: Token 0 (signal), Token 1 (noise), Token 2 (query)x = np.array([5.0, 100.0, 1.0])# Model chooses high delta for important token, tiny delta for noisedelta = np.array([1.5, 0.001, 1.0])
a_scalar = -1.0b = np.array([[1.0], [1.0], [1.0]])  # State dimension N = 1c = np.array([[1.0], [1.0], [1.0]])
outputs = selective_ssm_step(x, delta, a_scalar, b, c)
print(f"Token inputs:    {x}")print(f"Selective delta: {delta}")print(f"Model outputs:   {np.round(outputs, 4)}")# -> Token inputs:    [  5. 100.   1.]# -> Selective delta: [1.5   0.001 1.   ]# -> Model outputs:   [7.5    7.5925 3.7915]

Watch Out For

Memory state capacity bottleneck during complex in-context retrieval

While Mamba matches Transformers on language modeling perplexity, its fixed state vector h∈RNh \in \mathbb{R}^N creates a fundamental information-theoretic bottleneck. Unlike Transformer attention, which stores every prior token's Key and Value vector uncompressed in memory (O(L)O(L) capacity), an SSM must compress an arbitrary number of tokens into a fixed D×ND \times N state vector. For tasks requiring exact retrieval across dozens of distinct, arbitrary key-value facts scattered across 100k tokens (multi-query associative recall), pure SSMs degrade. For such workloads, hybrid architectures like jamba that interleave SSM layers with sparse attention layers are required.

The Quick Version

  • Mamba replaces static LTI state spaces with content-dependent parameters B(x),C(x),Δ(x)B(x), C(x), \Delta(x).
  • Content-dependent gating allows Mamba to selectively filter noise and retain critical facts across long horizons.
  • Because selection breaks FFT convolution, Mamba uses a hardware-aware parallel scan executed entirely in fast GPU SRAM.
  • Mamba-2 introduces State Space Duality (SSD), proving the mathematical equivalence of selective SSMs and masked linear attention.
  • Mamba-2 executes intra-chunk recurrence using GPU Tensor Cores, achieving dramatic training throughput gains over Mamba-1.