Skip to content
AILinkDeepTech
Go back
Deep Learning Advanced

Mamba & State Space Models (SSM): Mathematical Foundations, Hardware-Aware Parallel Scan, and Mamba-2 SSD Duality

Abstract

Master Mamba and State Space Models (SSM): continuous control theory, Zero-Order Hold (ZOH) discretization, HiPPO orthogonal memory, S4 convolution duality, input-dependent selective scan (S6), GPU SRAM kernel fusion, and Mamba-2 State Space Duality (SSD) with full PyTorch implementations.

The Sequence Modeling Trilemma: Breaking the Physical Wall

The dominance of the Transformer architecture across natural language processing, computer vision, and multimodal foundation models rests on the expressive capacity of the Multi-Head Self-Attention (MHA) mechanism. By computing pairwise inner products across all sequence positions, self-attention allows direct, unconstrained routing of information across arbitrary token distances.

However, standard self-attention exhibits two fundamental physical bottlenecks that constrain long-context scaling:

  1. Quadratic Training Computational Complexity : Computing full attention maps requires materializing an affinity matrix per attention head, scaling quadratically with sequence length .
  2. Linear Memory Explosion in Autoregressive Inference : Autoregressive token generation requires retaining all historical key and value activations in high-bandwidth GPU memory (KV Cache). For an 8k context window across 32 layers, KV cache memory footprint outstrips model weights during batch serving.
flowchart LR RNN["<b>1. Classical RNNs</b><br/>• O(1) Constant State<br/>• Sequential O(L) Train"] --> TRANS["<b>2. Transformers</b><br/>• O(L²) Parallel Train<br/>• O(L) KV Cache Explosion"] TRANS --> S4["<b>3. S4 (LTI SSM)</b><br/>• O(L log L) FFT Conv<br/>• Static Content-Blind Memory"] S4 --> MAMBA["<b>4. Mamba (S6)</b><br/>• O(L) Selective Scan<br/>• O(1) State Memory"] MAMBA --> MAMBA2["<b>5. Mamba-2 (SSD)</b><br/>• Linear Attention Duality<br/>• Tensor Core Matmul GEMM"]

Mamba (Gu & Dao, 2023) breaks the long-standing dichotomy between linear models and Transformers. By combining input-dependent selective state spaces (S6) with hardware-aware GPU kernel fusion, Mamba achieves strict linear compute scaling and constant inference state memory , while matching or exceeding dense Transformer perplexity on multi-billion parameter scales.


Architectural & Theoretical Paradigm Comparison

Architecture MetricStandard Transformer (MHA)Linear Attention (Katharopoulos et al.)Structured SSM (S4)Mamba (S6 Selective SSM)Mamba-2 (SSD Duality)
Training Time Complexity (Quadratic) (Linear in ) (FFT Conv) (Strict Linear) (Chunked GEMM)
Decode Step Complexity (Per-step attention) (State update) (Constant) (Constant) (Constant)
Autoregressive State Memory (Linear KV Cache) (Feature matrix) (Fixed hidden vector) (Fixed hidden vector) (Fixed hidden vector)
Time DynamicsDynamic Dynamic Linear Time-Invariant (LTI)Linear Time-Varying (LTV)Linear Time-Varying (LTV)
Selective Context FilteringComplete (Pairwise routing)Weak (Unnormalized kernel drift)None (Static global kernel)High (Input-dependent )High (Semiseparable Masked Attention)
GPU Hardware PrimitiveFlashAttention (Fused GEMM)Matrix MultiplicationFFT / Circular ConvSRAM Fused Associative ScanTensor Core Block GEMM + Scan

Continuous-Time State Space Foundations & Discretization

1. Continuous-Time Linear State Space Equations

Originating in modern control theory and dynamical systems, a Continuous-Time State Space Model (SSM) maps a continuous one-dimensional input signal through an -dimensional latent state to an output signal via a first-order linear ordinary differential equation (ODE):

where:

  • is the State Transition Matrix, governing system dynamics and latent state decay.
  • is the Input Projection Matrix, modulating the injection of input signal into the latent state.
  • is the Observation Matrix, projecting the latent state into the output space.
  • is the Direct Feedthrough (Skip Connection) Coefficient.
flowchart LR X["Continuous Input: x(t)"] --> B_MAT["Input Matrix: B"] X --> D_MAT["Direct Feedthrough: D"] B_MAT --> SUM1["(+)"] A_MAT["State Feedback: A"] --> SUM1 SUM1 --> INT["Integrator: ∫ dt"] INT --> H["Latent State: h(t)"] H --> A_MAT H --> C_MAT["Observation Matrix: C"] C_MAT --> SUM2["(+)"] D_MAT --> SUM2 SUM2 --> Y["Continuous Output: y(t)"]

2. Zero-Order Hold (ZOH) Discretization Calculus

Deep learning architectures operate on discrete sequences of tokens rather than continuous signals. Given a discrete sequence sampled at time interval , we must transform the continuous ODE system into an exact discrete-time recurrence relation:

The standard method used in modern SSMs is the Zero-Order Hold (ZOH) assumption: the continuous input signal remains constant over the sampling interval , such that .

Mathematical Derivation:

Multiplying the ODE by the integrating factor :

Integrating both sides across the sampling window :

Evaluating the left-hand side:

Multiplying through by :

Under the ZOH assumption, is constant across the entire interval. Applying variable substitution ():

This yields the exact closed-form Zero-Order Hold Discretization Formulas:

When is diagonalized (), the matrix exponential collapses to element-wise scalar exponentials , eliminating matrix inversion overhead.


Continuous Memory via Orthogonal Polynomials: The HiPPO Framework

A catastrophic flaw of classical recurrent architectures (such as vanilla RNNs, LSTMs, and GRUs) is the vanishing gradient and memory compression problem: as sequence length , the recurrent state vector exponentially overwrites past observations.

To solve this systematically, Gu et al. (2020) formulated the HiPPO (High-order Polynomial Projection Operators) framework.

flowchart LR SIG["Continuous Input: x(t)"] --> PROJ["HiPPO Projection<br/>Minimizes L2 Error under Sliding Measure"] PROJ --> BASIS["Legendre Polynomial Basis<br/>Orthogonal Memory Space"] BASIS --> COEFF["Optimal Memory State Vector<br/>h(t) ∈ R^N"]

1. Mathematical Formulation of Memory Projection

Let be an arbitrary continuous input history observed on interval . HiPPO maintains an optimal -dimensional polynomial approximation of the entire historical signal projected onto an orthogonal polynomial basis weighted by a probability measure :

The coefficient vector minimizes the continuous squared approximation error:

2. The HiPPO-Legendre Transition Matrix

Under the scaled uniform sliding window measure (HiPPO-Legendre), the temporal evolution of coefficient vector satisfies an exact continuous linear differential equation , where the transition matrices are derived in closed form:

Spectral Stability Property:

For all eigenvalues of , the real parts are strictly negative:

This strict negative real spectrum guarantees that the continuous dynamical system is asymptotically stable (Bounded-Input Bounded-State, BIBS stability) and eliminates exploding gradients across arbitrary sequence lengths.


S4 Convolutional Duality vs. The Linear Time-Invariant (LTI) Wall

1. Recurrence Unrolling to Global Convolution

In Structured State Space Models (S4) (Gu et al., 2021), the system matrices are Linear Time-Invariant (LTI)—they remain fixed across all time steps and independent of input data .

Expanding the discrete recurrence with zero initial state :

Substituting into the observation equation :

This equation is a discrete causal linear convolution:

where is the SSM Convolutional Kernel:

flowchart LR subgraph S4_Train["1. Training Mode: Parallel Convolution"] direction LR X_T["Full Input Sequence (x)"] --> FFT["Fast Fourier Transform (FFT)<br/>Parallel Circular Convolution"] K_KERNEL["S4 Global Kernel (K)"] --> FFT FFT --> Y_T["Full Output Sequence (y)<br/>Complexity: O(L log L)"] end subgraph S4_Infer["2. Inference Mode: Sequential Recurrence"] direction LR X_I["Current Token (x_k)"] --> STEP["Recurrent State Step<br/>Constant Matrix Update"] H_PREV["Prior Hidden State (h)"] --> STEP STEP --> Y_I["Next Token (y_k)<br/>Complexity: O(1) Memory & Time"] end

2. The Expressivity Wall of LTI Models

While S4 achieved parallel training and inference, LTI systems suffer from a severe architectural limitation: the convolutional kernel is static and content-agnostic.

Because depends only on fixed weights , the network processes every sequence using identical weight trajectories regardless of context. Consequently, LTI models systematically fail two fundamental cognitive primitives:

  1. Selective Copying: Extracting salient tokens embedded inside long sequences of noisy filler tokens (e.g., memorizing a security key after 10,000 irrelevant words). An LTI kernel decays exponentially or sinusoidally; it cannot selectively compress informative tokens while discarding filler.
  2. Induction Heads & Associative Recall: Predicting when encountering pattern . An LTI system cannot condition memory lookup on query token identity.

Mamba (S6): Input-Dependent Selective State Spaces

To overcome the expressivity wall of LTI systems while retaining linear scaling, Gu & Dao (2023) introduced Selective State Spaces (S6). Mamba replaces static weights with input-dependent parameterized functions.

flowchart LR subgraph LTI["Static LTI SSM (S4)"] direction TB X1["Input Token (x_t)"] --> REC1["Fixed Recurrence Step<br/>Constant Matrix Dynamics"] REC1 --> Y1["Static Output (y_t)"] end subgraph LTV["Selective SSM (Mamba / S6)"] direction TB X2["Input Token (x_t)"] --> PROJ["Input-Dependent Projections<br/>Linear_B, Linear_C, Linear_Δ"] PROJ --> DISC["Continuous-to-Discrete<br/>ZOH Discretization"] DISC --> REC2["Selective Recurrent Update<br/>Content-Aware Information Routing"] X2 --> REC2 REC2 --> Y2["Context-Aware Output (y_t)"] end

1. Parameter Parameterization Equations

For input sequence , Mamba computes token-level dynamic projections:

where:

  • is the state expansion rank (typically or ).
  • is the inner hidden dimension.
  • is maintained in continuous log-space for numerical stability: .

2. Operational Mechanics of Selective Modulation

The parameter functions as a continuous, input-dependent gating mechanism:

  • Information Retention (): , and . The system ignores current input token , retaining historical memory state without decay.
  • Information Ingestion & Overwrite (): , clearing past history and aggressively updating state with the current token representation.

Because and change dynamically at every position , the system is Linear Time-Varying (LTV). Global FFT convolution is no longer applicable, requiring a new parallelization paradigm.


Hardware-Aware Parallel Scan & GPU SRAM Kernel Fusion

The primary obstacle to training time-varying SSMs is memory bandwidth. In a naive PyTorch implementation, computing the recurrence loop across batch size , sequence length , model dimension , and state dimension requires writing the full hidden state tensor into GPU High Bandwidth Memory (HBM).

For typical hyperparameters ( in 16-bit precision), this tensor requires:

Writing and reading of intermediate state activations per layer saturates GPU memory bandwidth, leading to severe compute starvation.

flowchart LR subgraph PyTorch_Standard["Standard PyTorch: Memory-Bound"] direction TB SRAM1["GPU SRAM Cache"] <-->|"17.2 GB IO per layer\nSaturates HBM Bandwidth"| HBM1["GPU HBM Global Memory"] end subgraph Mamba_Fused["Mamba Fused Kernel: Compute-Bound"] direction TB LOAD["1. Stream Inputs into SRAM"] --> FUSE["2. Discretization + Parallel Associative Scan in SRAM"] FUSE --> WRITE["3. Write ONLY Final Output (y) to HBM\n(16x IO Reduction: 1.07 GB)"] end

1. Work-Efficient Parallel Associative Scan (Blelloch Scan)

The recurrence satisfies the algebraic definition of an associative binary operator :

This associative property allows computing the all-prefix state sequence using the Blelloch Parallel Scan algorithm in total work and parallel time depth across two phases:

flowchart LR subgraph Blelloch["Blelloch Work-Efficient Parallel Scan (Reduction Tree)"] direction LR L0_0["x₀"] --> L1_0["x₀..₁"] L0_1["x₁"] --> L1_0 L0_2["x₂"] --> L1_1["x₂..₃"] L0_3["x₃"] --> L1_1 L0_4["x₄"] --> L1_2["x₄..₅"] L0_5["x₅"] --> L1_2 L0_6["x₆"] --> L1_3["x₆..₇"] L0_7["x₇"] --> L1_3 L1_0 --> L2_0["x₀..₃"] L1_1 --> L2_0 L1_2 --> L2_1["x₄..₇"] L1_3 --> L2_1 L2_0 --> L3_0["x₀..₇ (Prefix State)"] L2_1 --> L3_0 end

2. Backward Pass Activation Recomputation

To further optimize memory, Mamba does not store intermediate hidden states for backward backpropagation. Instead, when the backward pass begins:

  1. The kernel re-reads the input sequences from HBM into SRAM.
  2. It recomputes the forward scan inside SRAM registers.
  3. It immediately computes parameter gradients with respect to within SRAM.

Trading redundant on-chip arithmetic operations for massive global memory traffic reduction yields a speedup over optimized Transformer implementations.


Mamba-2 & State Space Duality (SSD)

While Mamba achieved linear scaling, its hardware execution model diverged from dense matrix multiplication (GEMM) hardware engines: Tensor Cores. GPUs are heavily specialized for matrix multiplies; memory-bound scans underutilize Tensor Core FLOPs.

In Mamba-2 (Dao & Gu, 2024), Albert Gu and Tri Dao proved an algebraic identity: State Space Duality (SSD), bridging State Space Models and Linear Masked Attention.

flowchart LR subgraph SSM_Domain["State Space Model (Recurrent View)"] direction TB SSM_EQ["Sequential State Update<br/>O(1) Memory per step"] end subgraph SSD_Bridge["State Space Duality (Dao & Gu, 2024)"] direction TB DUAL["A_t = a_t · I (Scalar Decay)<br/>Exact Algebraic Equivalence"] end subgraph Attn_Domain["Masked Linear Attention (Attention View)"] direction TB ATTN_EQ["1-Semiseparable Matrix Multiply<br/>Massively parallel on Tensor Cores"] end SSM_Domain <===> DUAL <===> Attn_Domain

1. The Semiseparable Matrix Transformation

Consider the case where the state transition matrix is constrained to a scalar times identity: . Expanding the linear recurrence in matrix form across an entire sequence:

The transformation matrix is a 1-semiseparable matrix decomposed into a Hadamard product:

where:

  • is a lower-triangular causal decay matrix:
  • is the unmasked outer product of observation and input projection matrices.

This formulation demonstrates that SSMs are equivalent to causal Linear Attention with an exponential decay mask:

2. Chunk-Decomposed Computation for Tensor Cores

To exploit Tensor Core hardware, Mamba-2 decomposes sequence length into non-overlapping chunks of size (typically or ):

flowchart LR SEQ["Sequence Matrix X (L Tokens)"] --> CHUNKS["Split into Chunks (Size Q = 64)"] subgraph Intra_Chunk["1. Intra-Chunk Computation"] direction TB C_GEMM["Tensor Core GEMM Matmul<br/>Dense local interactions in Q × Q"] end CHUNKS --> Intra_Chunk Intra_Chunk --> INTER["2. Inter-Chunk Recurrence Scan<br/>Lightweight scan across L/Q boundaries"] INTER --> OUT["Final Output Sequence (Y)"]
  1. Intra-Chunk Computation (Tensor Cores): Inside each chunk of size , interactions between tokens are computed using dense matrix multiplication: .
  2. Inter-Chunk State Passing (SSM Scan): Across chunk boundaries, hidden states pass sequentially through a recurrence of length . Because , this scan completes orders of magnitude faster.

This dual formulation enables Mamba-2 to run at the training throughput of Mamba-1, fully saturating modern GPU Tensor Cores.


Production PyTorch Implementation

Below is a complete, modular, and self-contained PyTorch implementation featuring:

  1. Exact HiPPO Matrix Initialization.
  2. Input-Dependent Selective SSM (S6) with Discretization.
  3. The complete Mamba Block Architecture (Conv1D + Gating).
  4. State Space Duality (SSD) Chunked Linear Attention.
from __future__ import annotations

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


def make_hippo_matrix(state_dim: int) -> torch.Tensor:
    """
    Constructs the continuous-time HiPPO-Legendre transition matrix A_HiPPO.
    Guarantees optimal continuous history compression on orthogonal polynomials.
    """
    A = torch.zeros(state_dim, state_dim)
    for n in range(state_dim):
        for k in range(state_dim):
            if n > k:
                A[n, k] = -math.sqrt(2 * n + 1) * math.sqrt(2 * k + 1)
            elif n == k:
                A[n, k] = -(n + 1)
            else:
                A[n, k] = 0.0
    return A


class SelectiveSSM(nn.Module):
    """
    Selective State Space Model (S6) core operator.
    Implements input-dependent time-varying discretization and recurrent scanning.
    """

    def __init__(
        self,
        d_model: int,
        state_dim: int = 16,
        dt_rank: int | None = None,
        dt_min: float = 0.001,
        dt_max: float = 0.1,
    ) -> None:
        super().__init__()
        self.d_model = d_model
        self.state_dim = state_dim
        self.dt_rank = math.ceil(d_model / 16) if dt_rank is None else dt_rank

        # 1. Parameterize A in log-space to enforce negative real spectrum
        A_init = make_hippo_matrix(state_dim).repeat(d_model, 1, 1)
        A_real = torch.diag_embed(torch.diagonal(A_init, dim1=-2, dim2=-1))
        # Parameterize diagonal: A_log = log(-A) -> A = -exp(A_log)
        self.A_log = nn.Parameter(torch.log(-A_real.diagonal(dim1=-2, dim2=-1) + 1e-4))

        # 2. Input-dependent projection matrices for B, C, and Delta
        self.x_proj = nn.Linear(d_model, self.dt_rank + 2 * state_dim, bias=False)

        # 3. Delta projection to d_model channels
        self.dt_proj = nn.Linear(self.dt_rank, d_model, bias=True)

        # Initialize dt_proj bias to match uniform log interval [dt_min, dt_max]
        dt_init = torch.exp(
            torch.rand(d_model) * (math.log(dt_max) - math.log(dt_min)) + math.log(dt_min)
        )
        inv_dt = dt_init + torch.log(-torch.expm1(-dt_init))
        with torch.no_grad():
            self.dt_proj.bias.copy_(inv_dt)

        # Direct feedthrough skip parameter
        self.D = nn.Parameter(torch.ones(d_model))

    def forward(self, u: torch.Tensor) -> torch.Tensor:
        """
        Forward execution of Selective SSM.
        Args:
            u: Input activations of shape (batch, seq_len, d_model)
        Returns:
            y: Transformed activations of shape (batch, seq_len, d_model)
        """
        batch_size, seq_len, d_model = u.shape

        # Compute dynamic B, C, and Delta projections from input
        x_dbl = self.x_proj(u)  # (batch, seq_len, dt_rank + 2 * state_dim)
        dt_raw, B, C = torch.split(
            x_dbl, [self.dt_rank, self.state_dim, self.state_dim], dim=-1
        )

        # Compute input-dependent step size Delta: (batch, seq_len, d_model)
        delta = F.softplus(self.dt_proj(dt_raw))

        # Continuous A to discrete A_bar: exp(Delta * A)
        # A: (d_model, state_dim), delta: (batch, seq_len, d_model)
        A = -torch.exp(self.A_log)  # (d_model, state_dim)
        # delta_A: (batch, seq_len, d_model, state_dim)
        delta_A = torch.exp(delta.unsqueeze(-1) * A.unsqueeze(0).unsqueeze(0))

        # Discretize B: delta * B
        # delta: (batch, seq_len, d_model, 1), B: (batch, seq_len, 1, state_dim)
        delta_B = delta.unsqueeze(-1) * B.unsqueeze(-2)

        # Sequential Recurrence Scan (Exact reference implementation)
        # Note: Production deployments fuse this loop in GPU SRAM via Triton / CUDA
        h = torch.zeros(batch_size, d_model, self.state_dim, device=u.device, dtype=u.dtype)
        ys = []

        for t in range(seq_len):
            u_t = u[:, t, :].unsqueeze(-1)  # (batch, d_model, 1)
            dA_t = delta_A[:, t, :, :]      # (batch, d_model, state_dim)
            dB_t = delta_B[:, t, :, :]      # (batch, d_model, state_dim)
            C_t = C[:, t, :].unsqueeze(-1)  # (batch, state_dim, 1)

            # Recurrence: h_t = A_bar_t * h_{t-1} + B_bar_t * u_t
            h = dA_t * h + dB_t * u_t

            # Output: y_t = C_t^T * h_t
            y_t = torch.matmul(h, C_t).squeeze(-1)  # (batch, d_model)
            ys.append(y_t)

        y = torch.stack(ys, dim=1)  # (batch, seq_len, d_model)

        # Direct feedthrough skip connection
        return y + u * self.D
from __future__ import annotations

import torch
import torch.nn as nn
import torch.nn.functional as F
from mamba_core import SelectiveSSM


class MambaBlock(nn.Module):
    """
    Standard Mamba layer incorporating 1D causal convolutions, SiLU gating,
    and Selective State Space Model recurrence.
    """

    def __init__(
        self,
        d_model: int,
        d_state: int = 16,
        expand_factor: int = 2,
        d_conv: int = 4,
    ) -> None:
        super().__init__()
        self.d_model = d_model
        self.d_inner = int(expand_factor * d_model)

        # Dual branch expansion projection
        self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)

        # Local causal 1D depthwise convolution
        self.conv1d = nn.Conv1d(
            in_channels=self.d_inner,
            out_channels=self.d_inner,
            kernel_size=d_conv,
            bias=True,
            groups=self.d_inner,
            padding=d_conv - 1,
        )

        # Core Selective SSM
        self.ssm = SelectiveSSM(d_model=self.d_inner, state_dim=d_state)

        # Output projection back to d_model
        self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Executes Mamba Block:
        1. Projects input to expanded dual branches (x_branch, z_gate).
        2. Applies causal Conv1d and SiLU activation to x_branch.
        3. Routes through Selective SSM.
        4. Applies multiplicative gate: y * SiLU(z_gate).
        """
        batch_size, seq_len, _ = x.shape

        # 1. Project input to 2x inner dimension
        projected = self.in_proj(x)
        x_branch, z_gate = torch.chunk(projected, chunks=2, dim=-1)

        # 2. Causal 1D Convolution
        x_conv = self.conv1d(x_branch.transpose(1, 2))[:, :, :seq_len].transpose(1, 2)
        x_activated = F.silu(x_conv)

        # 3. Selective State Space Transformation
        y_ssm = self.ssm(x_activated)

        # 4. Multiplicative Gating
        y_gated = y_ssm * F.silu(z_gate)

        # 5. Project back to model dimension
        return self.out_proj(y_gated)
from __future__ import annotations

import torch
import torch.nn as nn
import torch.nn.functional as F


class StateSpaceDualitySSD(nn.Module):
    """
    Mamba-2 Chunked State Space Duality (SSD) layer.
    Computes selective recurrence through chunked Tensor-Core matrix multiplications.
    """

    def __init__(self, d_model: int, chunk_size: int = 64) -> None:
        super().__init__()
        self.d_model = d_model
        self.chunk_size = chunk_size

        self.q_proj = nn.Linear(d_model, d_model, bias=False)
        self.k_proj = nn.Linear(d_model, d_model, bias=False)
        self.v_proj = nn.Linear(d_model, d_model, bias=False)
        self.decay_proj = nn.Linear(d_model, d_model, bias=True)
        self.out_proj = nn.Linear(d_model, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Executes chunk-decomposed 1-semiseparable SSD computation:
        Y = (L ∘ (C · B^T)) · X decomposed across chunk boundaries.
        """
        b, l, d = x.shape
        q = self.chunk_size
        num_chunks = math.ceil(l / q)

        # Pad sequence to integer multiple of chunk size
        pad_len = num_chunks * q - l
        if pad_len > 0:
            x = F.pad(x, (0, 0, 0, pad_len))

        # Compute Q, K, V and decay rates
        C = self.q_proj(x).view(b, num_chunks, q, d)  # Analogous to C / Query
        B = self.k_proj(x).view(b, num_chunks, q, d)  # Analogous to B / Key
        X = self.v_proj(x).view(b, num_chunks, q, d)  # Analogous to u / Value
        decay = -F.softplus(self.decay_proj(x)).view(b, num_chunks, q, d)

        # Intra-Chunk Causal Mask with Decay: L_chunk
        decay_cumsum = torch.cumsum(decay, dim=2)
        # Pairwise decay relative difference: L_{ij} = exp(decay_i - decay_j) for i >= j
        rel_decay = decay_cumsum.unsqueeze(3) - decay_cumsum.unsqueeze(2)
        causal_mask = torch.tril(torch.ones(q, q, device=x.device)).unsqueeze(0).unsqueeze(0).unsqueeze(-1)
        L_chunk = torch.exp(rel_decay) * causal_mask

        # 1. Intra-Chunk Output via Tensor Core Matmul
        # Affinity: (C · B^T) weighted by L_chunk
        affinity = torch.einsum("bckd,bcjd->bckj", C, B)
        affinity_masked = affinity * L_chunk.squeeze(-1)
        y_intra = torch.einsum("bckj,bcjd->bckd", affinity_masked, X)

        # 2. Inter-Chunk State Recurrence Passing
        # Compute end-of-chunk state vectors and propagate across chunks
        chunk_states = torch.einsum("bcjd,bcjd->bcd", B, X)  # Simplified chunk summary
        y_inter = torch.zeros_like(y_intra)
        running_state = torch.zeros(b, d, device=x.device)

        for c in range(num_chunks):
            y_inter[:, c, :, :] = y_inter[:, c, :, :] + running_state.unsqueeze(1)
            running_state = running_state * torch.exp(decay[:, c, -1, :]) + chunk_states[:, c, :]

        # Combine intra and inter chunk updates
        y_total = (y_intra + y_inter).view(b, num_chunks * q, d)
        if pad_len > 0:
            y_total = y_total[:, :l, :]

        return self.out_proj(y_total)

Empirical Benchmark Evaluation

Quantitative evaluations comparing Mamba against dense Transformer baselines (LLaMA-2, Pythia, RWKV-v5, and RetNet) across multi-dataset pretraining, autoregressive decode latency, and memory scaling.

1. Language Modeling Perplexity on The Pile (Zero-Shot)

Model ArchitectureParameter CountTraining TokensThe Pile Perplexity ()LAMBADA Accuracy ()MMLU (5-shot) ()
Pythia-1.4B
RWKV-4-1.5B
Mamba-1.4B
LLaMA-2-7B
Mamba-2-7B (SSD)

2. Autoregressive Inference Throughput & VRAM Footprint

Benchmarked on a single NVIDIA A100-SXM4-80GB GPU at batch size :

Context Length ()LLaMA-2 7B VRAM (KV Cache)LLaMA-2 7B Speed (tokens/s)Mamba 7B VRAM (State Cache)Mamba 7B Speed (tokens/s)Mamba Speedup
(OOM on batched)
OOM (Exceeds 80GB)Crashed (Feasible)

Troubleshooting Common SSM Numerical & Engineering Faults

1. Matrix Exponential Explosion & Gradient Blowup

  • Symptom: Parameter gradients report NaN or inf during the first 100 optimization steps; loss diverges catastrophically.
  • Root Cause: Unconstrained real parameters in allow positive eigenvalues (). In ZOH discretization , positive exponents cause exponential state blowup across recurrent steps.
  • Remedy: Always parameterize in negative log-space:
    # Correct: Strictly enforces negative real spectrum
    self.A_log = nn.Parameter(torch.log(-A_init))
    A = -torch.exp(self.A_log)

2. Discretization Step Underflow & Dead Neurons

  • Symptom: Hidden states collapse to identity mappings (), and the network fails to learn syntax or induction heads.
  • Root Cause: When initialized with standard normal random weights, linear projections produce negative logits that softplus maps to near-zero step sizes ().
  • Remedy: Initialize dt_proj.bias to a log-uniform distribution between and using the inverse softplus transformation.

3. Precision Loss in Associative Scans under FP16

  • Symptom: Model outputs garbled tokens on sequence lengths exceeding when trained with torch.float16 or bfloat16.
  • Root Cause: Cumulative multiplications suffer catastrophic underflow or rounding errors in 16-bit floating-point registers.
  • Remedy: Execute the parallel scan accumulator strictly in 32-bit floating point (float32), casting activations back to bfloat16 only when writing output tensor to HBM.

References

  1. Gu, A., Goel, K., & Ré, C. (2021). Efficiently Modeling Long Sequences with Structured State Spaces (S4). International Conference on Learning Representations (ICLR 2022).
  2. Gu, A., & Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv:2312.00752.
  3. Dao, T., & Gu, A. (2024). Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2). International Conference on Machine Learning (ICML 2024).
  4. Gu, A., Dao, T., Ermon, S., Rudra, A., & Ré, C. (2020). HiPPO: Recurrent Memory with Optimal Polynomial Projections. Advances in Neural Information Processing Systems (NeurIPS 2020).
  5. Katharopoulos, A., Vyas, A., Pappas, N., & Fleuret, F. (2020). Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. ICML 2020.
  6. Blelloch, G. E. (1990). Prefix Sums and Their Applications. Technical Report CMU-CS-90-190, School of Computer Science, Carnegie Mellon University.


Cite this Explanation

@article{ailinkdeeptech2026mamba,
  title={Mamba & State Space Models (SSM): Mathematical Foundations, Hardware-Aware Parallel Scan, and Mamba-2 SSD Duality},
  author={AILinkDeepTech},
  journal={AILinkDeepTech Algorithm Explanations},
  year={2026},
  url={https://ailinkdeeptech.com/research/mamba/}
}

Related Explanations