Mamba & State Space Model (SSM) Studio
Explore the continuous-to-discrete mathematical foundations and hardware-aware mechanics of Mamba (Gu & Dao, 2023). Switch between recurrent inference and parallel associative scan, observe selective filtering via input-dependent gating, inspect exact state space arithmetic, and benchmark linear memory scaling against quadratic Transformer KV caches.
Dynamic Selection Gate ()
When is large, the gate latches new input into state while clearing ancient history (). When small, the gate ignores irrelevant tokens (stopwords/spacers) and retains past latent state indefinitely.
Latent Hidden State Vector ()
State vector evolution across channels. Green indicates positive memory accumulation, red indicates negative inhibition.
Projected Output Trajectory ()
The scalar output produced at each sequence step. Click any step column below to jump directly to its execution context.
Zero-Order Hold (ZOH) Discretization Explorer
Continuously parameterized state equations are discretized over sample step . Because continuous poles , discrete eigenvalues satisfy , guaranteeing spectral contraction and numerical stability.
Transformer KV Cache vs Mamba Constant Memory Benchmark
During autoregressive inference, Transformers require caching all past Keys and Values, consuming memory that explodes with context length. Mamba compresses all past context into a fixed-size latent state vector , maintaining strict memory consumption.
Architecture Dimensions & Computational Complexity
Tune Mamba block hyperparameters to inspect parameter counts, FLOPs per token, and layer memory footprints in real time.
Production PyTorch Implementation
Drop-in PyTorch module matching your exact active configuration with input-dependent projection heads, 1D causal convolution, and discretized recurrence.
# Generating PyTorch snippet...Mathematical Foundations & Hardware Engineering
Rigorous mathematical proofs, continuous ODE derivations, and hardware acceleration principles behind modern State Space Models.
The HiPPO Matrix & Optimal Polynomial Memory
Recurrent neural networks (RNNs) historically suffered from either vanishing gradients (fading ancient memory) or exploding gradients. The HiPPO (High-order Polynomial Projection Operators; Gu et al., NeurIPS 2020) framework solved this fundamental challenge by casting online memory as optimal continuous function approximation.
1. Continuous History Projection onto Legendre Polynomials
Consider a continuous 1D input signal observed up to current time . We seek to maintain a degree- polynomial approximation of the history for with respect to a time-varying probability measure :
Expressing in the orthogonal basis of shifted Legendre polynomials , the projection coefficients satisfy a differential equation that guarantees optimal online coefficient updates without storing past values:
2. Canonical HiPPO Transition Matrix
Converting this time-varying system into a time-invariant state-space representation yields the canonical continuous HiPPO-LegS matrix:
Why this prevents memory fading: Standard RNN transition matrices compress history through repeated unconstrained matrix multiplications, causing geometric decay . In contrast, HiPPO projects continuous history onto orthogonal Legendre bases, ensuring that ancient signals retain non-zero projection coefficients over unbounded sequence horizons. In Mamba, the continuous transition matrix is initialized via structured diagonal decomposition with negative real poles () derived from the HiPPO spectrum.
Zero-Order Hold (ZOH) Discretization & Spectral Stability
State Space Models describe continuous dynamical systems governed by ordinary differential equations (ODEs):
Digital computing architectures operate on discrete sequences sampled at intervals parameterized by step size . The Zero-Order Hold (ZOH) assumption postulates that the input remains piecewise-constant over each sampling interval .
1. Derivation of the Discrete Transition Matrices
Solving the linear continuous ODE over using the matrix exponential integrating factor:
Because is constant over the interval, we factor it out of the integral:
Defining discrete transition matrices and :
For diagonal , each dimension evaluates independently as:
2. Proof of Spectral Stability & Contraction Mapping
Let denote the continuous eigenvalues of . By HiPPO construction, continuous poles lie strictly in the open left half-plane:.
Under the exponential mapping, the eigenvalues of discrete operator are:
Because all discrete eigenvalues have magnitude strictly less than 1, is a strict contraction mapping on . Consequently, the latent state remains strictly bounded for arbitrarily long sequence lengths ( as ), preventing gradient explosions during training and unbounded state drift during autoregressive inference.
Hardware-Aware Parallel Associative Scan vs Attention
While Transformers revolutionized deep learning by parallelizing training over time, their quadratic attention matrix creates severe memory and computational bottlenecks for long sequences. Conversely, standard RNNs have linear complexity but failed because sequential recurrent steps cannot parallelize across modern GPU architectures.
1. The Modern GPU Memory Hierarchy Dilemma
Modern accelerators (e.g. Nvidia H100 SXM) have two primary memory tiers:
- High-Bandwidth Memory (HBM): Massive capacity (80–96 GB) but comparatively limited bandwidth (~3.35 TB/s).
- On-Chip Static RAM (SRAM): Ultra-fast bandwidth (~33 TB/s, faster) but minimal capacity (~228 KB per SM, ~50 MB total).
Standard RNNs require reading and writing state vectors between HBM and SRAM at every sequential token step . The arithmetic intensity is negligible ( FLOP/byte), stalling tensor execution units while waiting on HBM memory transfers.
2. The Associative Property of Linear Recurrence
Mamba makes the critical realization that linear state space recurrence is an associative operator. Consider adjacent state transitions:
Defining the binary tuple operator on elements :
Because matrix multiplication and addition are associative, . This enables computing the entire sequence recurrence using the Blelloch Parallel Prefix Scan in parallel time steps across GPU threads.
3. Kernel Fusion in On-Chip SRAM
Mamba implements an optimized Triton/CUDA kernel that fuses discretization, causal 1D convolution, and parallel scan directly in on-chip SRAM:
Mamba-2 & State Space Duality (SSD)
In Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao & Gu, 2024), the authors establish an exact theoretical equivalence between linear attention and structured state space models.
1. The 1-Semiseparable Matrix Connection
Unrolling an unforced SSM over sequence length reveals that the transformation from input sequence to output sequence can be expressed as multiplication by a lower-triangular structured matrix :
This matrix is 1-semiseparable: every submatrix below the main diagonal has rank at most 1 (or rank in multi-channel SSMs). Linear attention computes a special case of this transformation where (no decay):
2. Bridging Tensor Cores and Recurrence
In Mamba-1, general diagonal required custom associative scan kernels that underutilized GPU Tensor Cores (specialized matrix multiply units). Mamba-2 restricts to scalar-times-identity structure (). This enables decomposing the semiseparable matrix into block matrix multiplications:
- Intra-chunk computation (e.g. 64 tokens): Evaluated using dense matrix multiplications ( style) on Tensor Cores with peak compute efficiency.
- Inter-chunk computation: Carried across chunk boundaries via recurrent state propagation in linear time.
The Result: Mamba-2 matches the expressive capacity of selective SSMs while training up to faster than Mamba-1 by computing the core recurrence directly on Tensor Cores, unifying Attention and SSM architectures into a single foundational framework.