Selective State Space Models

Dive into Deep Learning · §12.5

Selective State Space Models (Mamba)
selective copying · input-dependent step sizes · softplus–sigmoid duality · reverse-scan adjoint VJP · state contributions

Why Time-Invariant SSMs Fail at Content Selection

Motivation

  • The flaw of fixed lag kernels: In §12.4, S4D weights any token k steps back by the fixed convolution coefficient K_k, whether that token was a key entity or an uninformative filler.
  • Natural language is content-selective: A reader must write salient nouns strongly into memory and hold them across variable-length clauses while ignoring filler tokens in between.
  • Why no LTI convolution can solve selective copying: When target symbols appear at random positions that change from sequence to sequence, no fixed lag weight K_k can align with the targets.

Combining minGRU Selectivity with S4D Multi-Timescales

Unifying Two Paradigms

  • What MinGRU (§12.3) Has: Input-dependent gate \mathbf{z}_t(\mathbf{x}_t), but only N = 1 scalar per channel starting at \tau_{1/2} = 1.
  • What S4D (§12.4) Has: N = 16 log-spaced decay modes per channel (\tau_{1/2} \in [0.4, 693]), but fixed LTI step size \Delta_c.
  • What Mamba (§12.5) Unifies: Token-dependent (\boldsymbol{\Delta}_t, \mathbf{B}_t, \mathbf{C}_t) over an H \times N multi-timescale state trained via parallel + adjoint scans.

The Selective Copying Benchmark: Random Symbol Lags

Synthetic Stress Test

copy_batch tests content-based selection over a 1{,}028-token horizon:

  • Sequence layout: 1{,}024 filler tokens (0) into which 4 marked symbols (drawn uniformly from tokens 2..9) are scattered at random positions, followed by 4 query tokens (1) at steps 1{,}025 \ldots 1{,}028.
  • Prediction target: At the j-th query token, output the j-th marked symbol in order (chance accuracy = 1/8 = 0.125).
tensor([[0, 0, 0, 7, 0, 2, 7, 0, 6, 0, 0, 0, 1, 1, 1, 1],
        [0, 0, 7, 7, 0, 0, 9, 5, 0, 0, 0, 0, 1, 1, 1, 1]])
tensor([[7, 2, 7, 6],
        [7, 7, 9, 5]])

Baseline Test: Time-Invariant S4D vs. Selective minGRU

Baseline Results

Training a 2-block SeqLM (d = 48) for 1{,}500 Adam steps (\text{lr} = 3 \times 10^{-3}, batch size 64, two runs each):

S4D                  42,058 parameters, accuracy 0.17, 0.14
minGRU               48,202 parameters, accuracy 0.94, 0.94
  • S4D stays near chance (\le 0.20): Fixed lag weights cannot track symbols whose positions shift randomly between sequences.
  • Why minGRU succeeds (\approx 0.75–0.95) despite 1-step initial gates: Unlike fixed 1{,}000-step delayed recall (§12.4), random placement occasionally puts marked symbols just a few steps before the queries—providing short-range gradients that progressively teach the gates to stay closed on filler tokens 0.

Exact Duality: Softplus Step Sizes Are Sigmoid Gates

Theorem 1 (Gu & Dao, 2023)

e^{-\Delta_t} = e^{-\log(1 + e^{s_t})} = \frac{1}{1 + e^{s_t}} = \sigma(-s_t) = z_t

  • Exact 1D Equivalence (N = 1, \lambda = -1): Discretizing h'(t) = -h(t) + x(t) with step \Delta_t = \textrm{softplus}(s_t) yields h_t = z_t h_{t-1} + (1 - z_t)x_t (MinGRU).
  • Clock Modulation: Filler tokens (s_t = -4.6 \implies \Delta_t \approx 0.01, z_t \approx 0.99) freeze the state; marked symbols (s_t = +2.0 \implies \Delta_t \approx 2.13, z_t \approx 0.12) overwrite it.

Selective SSM Dynamics: Per-Token Δt, Bt, and Ct

The Selective SSM Equations

\mathbf{h}_t^{(c)} = e^{\Delta_{t,c}\boldsymbol{\lambda}} \odot \mathbf{h}_{t-1}^{(c)} + \Delta_{t,c}\, x_{t,c}\, \mathbf{B}_t, \quad y_{t,c} = \mathbf{C}_t^\top \mathbf{h}_t^{(c)} + D_c\, x_{t,c}

  • Input-Dependent Projections: From \mathbf{x}_t \in \mathbb{R}^H, computes rank-R step sizes \boldsymbol{\Delta}_t \in \mathbb{R}_+^H plus shared \mathbf{B}_t, \mathbf{C}_t \in \mathbb{R}^N.
  • Euler Write Factor: Keeps exact ZOH decay e^{\Delta_{t,c}\boldsymbol{\lambda}} with first-order write \Delta_{t,c} x_{t,c}\mathbf{B}_t.

Tensor Shapes and Low-Rank Step-Size Projection

Parameterization Details

Every tensor in SelectiveSSM has a clear structural role across the H = 2d expanded channels and N state dimensions:

Quantity Shape How It Is Parameterized / Computed
Channel input \mathbf{x}_t (H,) Output of width-4 causal convolution + SiLU on expanded branch
Step sizes \boldsymbol{\Delta}_t (H,) \textrm{softplus}(\mathbf{W}_\Delta \mathbf{x}_t + \mathbf{b}_\Delta) with rank-R bottleneck \mathbf{W}_\Delta \in \mathbb{R}^{H \times R} \times \mathbb{R}^{R \times H}, R = \lceil d/16 \rceil
Initial bias \mathbf{b}_\Delta (H,) Chosen so \textrm{softplus}(\mathbf{b}_\Delta) \in [0.001, 0.1] log-uniformly (dt + log(-expm1(-dt)))
Write & read \mathbf{B}_t, \mathbf{C}_t (N,) each Linear projections \mathbf{W}_B \mathbf{x}_t and \mathbf{W}_C \mathbf{x}_t shared across all H channels
Decay rates \boldsymbol{\lambda} (H, N) -\exp(\text{log\_neg\_rate}), initialized to -1, -2, \ldots, -N in every channel
Recurrent state \mathbf{h}_t (H, N) Updated by elementwise decay e^{\Delta_{t,c}\lambda_{c,n}} and rank-1 outer write (\boldsymbol{\Delta}_t \odot \mathbf{x}_t)\mathbf{B}_t^\top

Anatomy of the Full Mamba Block

Block Architecture

  1. Input expansion (\mathbf{W}_\textrm{in}): Projects width d to two branches (\mathbf{U}, \mathbf{Z}) each of expanded width H = 2d.
  2. Short causal convolution: A depthwise causal Conv1d of width 4 followed by \textrm{SiLU} mixes 4 consecutive tokens before computing \boldsymbol{\Delta}_t, \mathbf{B}_t, \mathbf{C}_t so selection can inspect local context.
  3. Selective SSM & SwiGLU-style gate: Multiplies \textrm{SSM}(\mathbf{U}) \odot \textrm{SiLU}(\mathbf{Z}) and projects back to width d via \mathbf{W}_\textrm{out}.

Pitfall: Activation Memory Explosion in 4D Scans

Systems Bottleneck

  • No FFT Shortcut: Time-varying \boldsymbol{\Delta}_t breaks LTI convolution, requiring a 4D parallel scan over (B, T, H, N).
  • 32× State Expansion (H = 2d, N = 16): Naive autograd stores \sim 20 intermediate doubling-round tensors—consuming \sim 2\text{ GB}/layer in toy runs and \sim 190\text{ GB}/layer at LLM scale.

The Adjoint Scan: Differentiating via a Reverse Scan

Memory-Efficient Backpropagation

\mathbf{g}_t = \frac{\partial \ell}{\partial \mathbf{h}_t}\Big|_\textrm{direct} + \mathbf{a}_{t+1} \odot \mathbf{g}_{t+1}, \quad \frac{\partial \ell}{\partial \mathbf{b}_t} = \mathbf{g}_t, \quad \frac{\partial \ell}{\partial \mathbf{a}_t} = \mathbf{g}_t \odot \mathbf{h}_{t-1}

  • Reverse-Time Linear Recurrence: Evaluates \mathbf{g}_{T:1} via one reverse call to linear_scan.
  • 10× Memory Reduction (adjoint_scan): Saves only 2 tensors (\mathbf{a}, \mathbf{h}) instead of \sim 20 intermediate scan rounds.

Verifying Custom VJP Adjoint Scan Against Autograd

Gradient Verification

Comparing gradients \partial \ell / \partial \mathbf{a} and \partial \ell / \partial \mathbf{b} from adjoint_scan against standard autograd through linear_scan on a T = 100 batch:

max deviation: 1.4e-06

The reverse-time adjoint scan produces the exact same gradients to float32 precision (\sim 10^{-6}) at a fraction of the activation memory.

Selective Copying: Mamba vs. Non-Selective Ablation

Controlled Ablation

We train 2-block Mamba (N = 4) alongside Mamba, not selective (selective=False, keeping the exact same input/output projections, width-4 causal convolution, and SiLU output gate, but fixing \boldsymbol{\Delta}, \mathbf{B}, \mathbf{C} as learned channel constants):

Mamba                71,242 parameters, accuracy 0.99, 1.00
Mamba, not selective 70,090 parameters, accuracy 0.38, 0.29

Selectivity is the decisive mechanism: Mamba reaches 0.95 accuracy or more, usually close to 1.00, whereas freezing \boldsymbol{\Delta}, \mathbf{B}, \mathbf{C} inside the identical block drops accuracy by >30 percentage points (scattering wildly across seeds).

Decomposing the Final State by Token Position

Mechanistic Interpretability

\mathbf{h}_T = \sum_{s=1}^{T} \exp\!\Big(\sum_{r=s+1}^{T} \log \mathbf{a}_r\Big) \odot \mathbf{b}_s

  • Per-Position Surviving Norm: state_contributions measures the Euclidean norm of position s’s decayed write inside \mathbf{h}_T.
  • Width-4 Conv Windows: Each marked symbol spreads across \{s, \ldots, s+3\} (\le 1.6\% of the 1{,}025 tokens).

Mamba Spikes at Marked Symbols; S4D Tracks Recency

State Contribution Profile

Share of the final state that originates in the symbol windows (1.6\% of the positions), for each layer, and the contribution of all 1{,}025 positions in the more selective layer of each model:

symbol windows: 1.6% of the positions
share of the state from them  layer 1  layer 2
S4D                              0.03     0.01
Mamba, run 1                     0.94     0.90
Mamba, run 2                     0.70     0.68

Quantifying Selection: The Symbol-to-Filler Spike Ratio

Large Steps in a Few Channels

The spike ratio is the peak contribution inside a symbol’s 4-token window, divided by the contribution of the filler token immediately preceding it. Median over the symbols of 64 test sequences, in both layers:

spike ratio, median over 256 symbols   layer 1   layer 2
S4D                                       27.8       1.5
Mamba, run 1                           2,933.1   5,654.5
Mamba, run 2                           1,416.0   4,980.2
  • Orders-of-magnitude amplification: In a layer that selects, Mamba’s symbols stand hundreds to tens of thousands of times above the adjacent fillers. S4D reaches a few tens at most: a fixed filter can respond more strongly to one token than to another, but cannot hold it longer. Both layers may select, or only one, and which one varies from run to run.
  • A few channels do the gating: Each symbol is carried by two or three of the H = 96 channels. On fillers they take \Delta_{t,c} \approx 10^{-5}, which freezes their state and writes almost nothing; on the symbol they take \Delta_{t,c} \approx 0.1 to 1.5, which writes it strongly (\Delta_{t,c} x_{t,c}\mathbf{B}_t). That step decays the earlier state by a small factor only: the spike is a strong write into frozen channels, not a flush.

Mamba on Byte-Level WikiText-103 vs. minGRU & Attention

Language Modeling Benchmark

Comparing 4-block Mamba, minGRU, causal attention (d = 256), and a parameter-matched minGRU, d=309 (3.99\text{M} parameters) on 128-byte WikiText-103 windows:

                           validation        0-15       16-63      64-127   ms/step
Mamba           3,989,248 1.298/1.297 1.488/1.488 1.272/1.272 1.269/1.268 69/69
minGRU          2,764,544 1.349/1.346 1.523/1.521 1.324/1.321 1.325/1.321 27/27
attention       3,286,784 1.378/1.383 1.557/1.559 1.354/1.359 1.351/1.357 21/21
minGRU, d=309   3,991,918 1.325/1.328 1.509/1.509 1.300/1.302 1.298/1.301 27/28

Mamba reaches 1.30 nats/byte—matching the full sequential LSTM and GRU of §12.1 while training via a parallel scan, and beating parameter-matched minGRU, d=309 by 0.03 nats/byte.

Concept Check: Softplus Gates, State Size, and Adjoint

Check Your Understanding

Work out the following three questions:

  1. In a 1-state selective SSM (N = 1, \lambda = -1), what step-size pre-activation s_t produces a discrete retention factor z_t = e^{-\textrm{softplus}(s_t)} = 0.999 (half-life \approx 693 steps)?
  2. For a Mamba layer at model width d = 256 (H = 2d = 512, N = 16, width-4 causal convolution), how many total numbers does the layer carry per sequence during autoregressive generation, and how many tokens of an attention KV cache (2d numbers/token) does that equal?
  3. Why does adjoint_scan reduce scan activation memory from O(B T H N \log_2 T) to O(B T H N)?

Answers:

  1. Since e^{-\textrm{softplus}(s_t)} = \sigma(-s_t) = 0.999, we need -s_t = \log(0.999 / 0.001) = \log 999 \approx 6.91 \implies \mathbf{s_t \approx -6.91} (\Delta_t \approx 0.001).
  2. The SSM state holds H \times N = 512 \times 16 = 8{,}192 = 32d numbers (16 tokens of KV cache), plus the last 3 convolution inputs of width H = 2d (3 \times 2d = 6d numbers, or 3 tokens of KV cache): 38d = 9{,}728 numbers total, equal to just 19 tokens of attention KV cache at any sequence length.
  3. Standard autograd saves the output of every doubling round (\lceil \log_2 T \rceil rounds), whereas adjoint_scan saves only the final forward states \mathbf{h} and decays \mathbf{a} and computes \mathbf{g}_t = \mathbf{g}_t^{\text{direct}} + \mathbf{a}_{t+1}\odot \mathbf{g}_{t+1} via one reverse scan.

Summary: Selective State Space Models (Mamba)

Key Takeaways

Component / Model Mathematical Mechanism Key Capability & Empirical Result
Softplus–Gate Identity e^{-\textrm{softplus}(s_t)} = \sigma(-s_t) Bridges continuous step size \Delta_t and MinGRU update gate z_t
Selective SSM (Mamba) \mathbf{h}_t^{(c)} = e^{\Delta_{t,c}\boldsymbol{\lambda}} \odot \mathbf{h}_{t-1}^{(c)} + \Delta_{t,c} x_{t,c}\mathbf{B}_t Token-dependent \boldsymbol{\Delta}_t, \mathbf{B}_t, \mathbf{C}_t + multi-timescale rates \lambda_n = -n
Adjoint Scan VJP \mathbf{g}_t = \nabla_{\mathbf{h}_t}\ell + \mathbf{a}_{t+1} \odot \mathbf{g}_{t+1} Differentiates scan via reverse-time scan; saves 2 tensors instead of \sim 20
Selective Copying 4 random-position symbols in 1{,}024 fillers Mamba scores 0.95 or more (S4D \le 0.20; non-selective Mamba drops >30 pts)
WikiText-103 Bytes 4-block SeqLM (d = 256, 128 bytes) Mamba reaches 1.30 nats/byte (matches LSTM/GRU; beats minGRU, d=309 by 0.03)