NN LAB 🧠

Foundational Deep Learning Laboratory

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 O(1)O(1) inference and parallel O(logT)O(\log T) associative scan, observe selective filtering via input-dependent Δt\Delta_t gating, inspect exact state space arithmetic, and benchmark linear memory scaling against quadratic Transformer KV caches.

ht=Aˉtht1+Bˉtxt,yt=Ctht+Dxt,Aˉt=exp(ΔtA)h_t = \bar{A}_t h_{t-1} + \bar{B}_t x_t, \quad y_t = C_t h_t + D x_t, \quad \bar{A}_t = \exp(\Delta_t A)
Domain Presets:
Active Sequence Tokens (Click token to jump):
Step 1 of 10: token "The"

Dynamic Selection Gate (Δt\Delta_t)

When Δt\Delta_t is large, the gate latches new input xtx_t into state while clearing ancient history (Aˉ0\bar{A} \to 0). When small, the gate ignores irrelevant tokens (stopwords/spacers) and retains past latent state indefinitely.

Latent Hidden State Vector (htRNh_t \in \mathbb{R}^N)

State vector evolution across N=dstateN = d_{\text{state}} channels. Green indicates positive memory accumulation, red indicates negative inhibition.

Projected Output Trajectory (yt=Ctht+Dxty_t = C_t h_t + D x_t)

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 Δ\Delta. Because continuous poles An<0A_n < 0, discrete eigenvalues satisfy Aˉn=exp(ΔAn)(0,1)\bar{A}_n = \exp(\Delta A_n) \in (0, 1), guaranteeing spectral contraction and numerical stability.

0.25

Transformer KV Cache vs Mamba Constant Memory Benchmark

During autoregressive inference, Transformers require caching all past Keys and Values, consuming O(N)O(N) memory that explodes with context length. Mamba compresses all past context into a fixed-size latent state vector htRdmodel×dstateh_t \in \mathbb{R}^{d_{\text{model}} \times d_{\text{state}}}, maintaining strict O(1)O(1) memory consumption.

32,768 tokens (32k)

Architecture Dimensions & Computational Complexity

Tune Mamba block hyperparameters to inspect parameter counts, FLOPs per token, and layer memory footprints in real time.

16
8
4
2
Model Parameters (24 Layers)--Linear scaling with dmodeld_{\text{model}}
Computational FLOPs--O(T)O(T) linear sequence FLOPs
Recurrent State Memory--O(1)O(1) constant inference memory

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 u(t)u(t) observed up to current time tt. We seek to maintain a degree-NN polynomial approximation g(t)(τ)g^{(t)}(\tau) of the history u(τ)u(\tau) for τ[0,t]\tau \in [0, t] with respect to a time-varying probability measure μ(t)(τ)=1tI[0,t](τ)\mu^{(t)}(\tau) = \frac{1}{t} \mathbb{I}_{[0, t]}(\tau):

g(t)=argmingPN0t(u(τ)g(τ))21tdτg^{(t)} = \arg\min_{g \in \mathcal{P}_N} \int_0^t \left( u(\tau) - g(\tau) \right)^2 \frac{1}{t} \, d\tau

Expressing g(t)g^{(t)} in the orthogonal basis of shifted Legendre polynomials {Pn}n=0N1\{P_n\}_{n=0}^{N-1}, the projection coefficientsc(t)RNc(t) \in \mathbb{R}^N satisfy a differential equation that guarantees optimal online coefficient updates without storing past values:

ddtc(t)=1tAHiPPOc(t)+1tBHiPPOu(t)\frac{d}{dt} c(t) = -\frac{1}{t} A_{\text{HiPPO}} \, c(t) + \frac{1}{t} B_{\text{HiPPO}} \, u(t)

2. Canonical HiPPO Transition Matrix

Converting this time-varying system into a time-invariant state-space representation yields the canonical continuous HiPPO-LegS matrix:

Ank={2n+12k+1if n>kn+1if n=k0if n<k,Bn=2n+1A_{nk} = -\begin{cases} \sqrt{2n+1}\sqrt{2k+1} & \text{if } n > k \\ n+1 & \text{if } n = k \\ 0 & \text{if } n < k \end{cases}, \qquad B_n = \sqrt{2n+1}

Why this prevents memory fading: Standard RNN transition matrices WhW_h compress history through repeated unconstrained matrix multiplications, causing geometric decay λt\sim \lambda^t. 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 (An=n1A_n = -n - 1) 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):

h˙(t)=Ah(t)+Bx(t),y(t)=Ch(t)+Dx(t)\dot{h}(t) = A h(t) + B x(t), \qquad y(t) = C h(t) + D x(t)

Digital computing architectures operate on discrete sequences {x0,x1,,xT1}\{x_0, x_1, \dots, x_{T-1}\} sampled at intervals parameterized by step size Δ\Delta. The Zero-Order Hold (ZOH) assumption postulates that the input x(t)x(t) remains piecewise-constant over each sampling interval [tΔ,(t+1)Δ)[t\Delta, (t+1)\Delta).

1. Derivation of the Discrete Transition Matrices

Solving the linear continuous ODE over τ[0,Δ]\tau \in [0, \Delta] using the matrix exponential integrating factor:

h(t+Δ)=exp(ΔA)h(t)+0Δexp((Δτ)A)Bx(t)dτh(t+\Delta) = \exp(\Delta A) h(t) + \int_0^\Delta \exp((\Delta - \tau) A) B x(t) \, d\tau

Because x(t)x(t) is constant over the interval, we factor it out of the integral:

0Δexp((Δτ)A)Bdτ=(ΔA)1(exp(ΔA)I)(ΔB)\int_0^\Delta \exp((\Delta - \tau) A) B \, d\tau = (\Delta A)^{-1} (\exp(\Delta A) - I) \cdot (\Delta B)

Defining discrete transition matrices Aˉ\bar{A} and Bˉ\bar{B}:

Aˉ=exp(ΔA),Bˉ=(ΔA)1(AˉI)(ΔB)\bar{A} = \exp(\Delta A), \qquad \bar{B} = (\Delta A)^{-1} (\bar{A} - I) \cdot (\Delta B)

For diagonal A=diag(a1,,aN)A = \text{diag}(a_1, \dots, a_N), each dimension evaluates independently as:

Aˉnn=exp(Δan),Bˉnn=exp(Δan)1anBn\bar{A}_{nn} = \exp(\Delta a_n), \qquad \bar{B}_{nn} = \frac{\exp(\Delta a_n) - 1}{a_n} \cdot B_n

2. Proof of Spectral Stability & Contraction Mapping

Let λi(A)\lambda_i(A) denote the continuous eigenvalues of AA. By HiPPO construction, continuous poles lie strictly in the open left half-plane:Re(λi(A))<0\text{Re}(\lambda_i(A)) < 0.

Under the exponential mapping, the eigenvalues of discrete operator Aˉ\bar{A} are:

λi(Aˉ)=exp(Δλi(A))=exp(ΔRe(λi(A)))<exp(0)=1Δ>0|\lambda_i(\bar{A})| = |\exp(\Delta \lambda_i(A))| = \exp(\Delta \cdot \text{Re}(\lambda_i(A))) < \exp(0) = 1 \quad \forall \Delta > 0

Because all discrete eigenvalues have magnitude strictly less than 1, Aˉ\bar{A} is a strict contraction mapping on RN\mathbb{R}^N. Consequently, the latent state remains strictly bounded for arbitrarily long sequence lengths (ht<\|h_t\| < \infty as tt \to \infty), 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 O(T2)O(T^2) creates severe memory and computational bottlenecks for long sequences. Conversely, standard RNNs have linear complexity O(T)O(T) 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, 10×10\times faster) but minimal capacity (~228 KB per SM, ~50 MB total).

Standard RNNs require reading and writing state vectors hth_t between HBM and SRAM at every sequential token step tt. The arithmetic intensity is negligible (<1< 1 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:

ht=Aˉtht1+Bˉtxt=Aˉt(Aˉt1ht2+Bˉt1xt1)+Bˉtxt=(AˉtAˉt1)ht2+(AˉtBˉt1xt1+Bˉtxt)h_t = \bar{A}_t h_{t-1} + \bar{B}_t x_t = \bar{A}_t (\bar{A}_{t-1} h_{t-2} + \bar{B}_{t-1} x_{t-1}) + \bar{B}_t x_t = (\bar{A}_t \bar{A}_{t-1}) h_{t-2} + (\bar{A}_t \bar{B}_{t-1} x_{t-1} + \bar{B}_t x_t)

Defining the binary tuple operator \circ on elements (pi,qi)=(Aˉi,Bˉixi)(p_i, q_i) = (\bar{A}_i, \bar{B}_i x_i):

(aj,bj)(ai,bi)=(ajai,ajbi+bj)(a_j, b_j) \circ (a_i, b_i) = (a_j a_i, \, a_j b_i + b_j)

Because matrix multiplication and addition are associative, ((ab)c)=(a(bc))((a \circ b) \circ c) = (a \circ (b \circ c)). This enables computing the entire sequence recurrence using the Blelloch Parallel Prefix Scan in O(logT)O(\log T) 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:

Memory-Bandwidth Optimization:Input parameters x,Δ,B,Cx, \Delta, B, C are loaded once from HBM into SRAM. Discretization Aˉt=exp(ΔtA)\bar{A}_t = \exp(\Delta_t A) and the parallel scan are executed entirely in SRAM and registers. Intermediate hidden states htRB×L×D×Nh_t \in \mathbb{R}^{B \times L \times D \times N} are never written to HBM; only final outputs yRB×L×Dy \in \mathbb{R}^{B \times L \times D} are written back, reducing HBM memory traffic by over 10×10\times.
🔮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 TT reveals that the transformation from input sequence XRT×1X \in \mathbb{R}^{T \times 1} to output sequence YRT×1Y \in \mathbb{R}^{T \times 1} can be expressed as multiplication by a lower-triangular structured matrix MRT×TM \in \mathbb{R}^{T \times T}:

Mij={CiT(k=j+1iAˉk)Bˉjif i>jCiTBˉiif i=j0if i<jM_{ij} = \begin{cases} C_i^T \left( \prod_{k=j+1}^i \bar{A}_k \right) \bar{B}_j & \text{if } i > j \\ C_i^T \bar{B}_i & \text{if } i = j \\ 0 & \text{if } i < j \end{cases}

This matrix is 1-semiseparable: every submatrix below the main diagonal has rank at most 1 (or rank NN in multi-channel SSMs). Linear attention computes a special case of this transformation where Aˉk=I\bar{A}_k = I (no decay):

Y=tril(QKT)VY = \text{tril}(Q K^T) V

2. Bridging Tensor Cores and Recurrence

In Mamba-1, general diagonal AA required custom associative scan kernels that underutilized GPU Tensor Cores (specialized matrix multiply units). Mamba-2 restricts AA to scalar-times-identity structure (A=αIA = \alpha I). This enables decomposing the semiseparable matrix into block matrix multiplications:

  • Intra-chunk computation (e.g. 64 tokens): Evaluated using dense matrix multiplications (QKTVQ K^T V 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 8×8\times faster than Mamba-1 by computing the core recurrence directly on Tensor Cores, unifying Attention and SSM architectures into a single foundational framework.