Skip to content
Skip to lesson
Back to Topics
HardInference Optimization13 min read

Mamba & State Space Models

Replace a growing KV cache with a fixed state, then test what selection, prefix scans, and branch rollback can and cannot restore.

On this page

Every token a standard Transformer generates appends another row to its . At 64K tokens, a 32-layer model holds 32 GiB of history for a single request. What if you replaced that growing table with a single fixed-size running summary that never grows past 5 MiB, no matter how long the conversation gets?

That is the bet behind and .[1] Full keeps every past token directly addressable in memory, making exact verbatim lookup natural at O(L)O(L) cache cost. An SSM folds history into a fixed recurrent state hth_t, giving O(1)O(1) per-request decode memory and linear-time training at the price of compressing past tokens into a finite vector.

Side-by-side comparison of Transformer KV cache growing linearly with sequence length L versus Mamba fixed-size recurrent state and 4-slot convolution window updating in constant time per token.
Attention appends a KV entry for every position (O(L)O(L) memory). Mamba-1 instead updates one fixed recurrent state and a four-slot rolling convolution window (O(1)O(1) live memory per request).

A discrete recurrence you can compute by hand

At its heart, a discrete SSM is two linear equations that update a hidden state hth_t and read out an output yty_t:

ht=Aˉ ht−1+Bˉ xt,yt=Cˉ ht+Dˉ xth_t = \bar{A}\, h_{t-1} + \bar{B}\, x_t, \qquad y_t = \bar{C}\, h_t + \bar{D}\, x_t

The first term carries prior memory forward; the second writes the new token into state. Set Aˉ=0.9\bar{A} = 0.9, Bˉ=0.2\bar{B} = 0.2, Cˉ=1.0\bar{C} = 1.0, Dˉ=0\bar{D} = 0, and step through the four inputs x=[3,1,4,2]x = [3, 1, 4, 2] starting from h0=0h_0 = 0:

Step ttInput xtx_tCarry 0.9 ht−10.9\,h_{t-1}Write 0.2 xt0.2\,x_tState hth_t
130.00000.600.6000
210.54000.200.7400
340.66600.801.4660
421.31940.401.7194

Look at how clean that is: memory never grows, yet step 4 still carries echoes of all four inputs (most of h4=1.7194h_4 = 1.7194 comes from carried history rather than the latest write). Lower Aˉ\bar{A} from 0.9 to 0.1, and the final state plunges to 0.4826 because early inputs wash out almost immediately. State retention depends on the decay dynamics, not just the state width.

Where Aˉ\bar{A} and Bˉ\bar{B} come from

SSMs begin in continuous time as a linear differential equation driven by signal x(t)x(t):

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

Because language arrives as discrete tokens rather than smooth waveforms, we discretize over a step width Δ\Delta using a zero-order hold (ZOH) (holding x(t)x(t) constant across each step Δ\Delta):[1]

Aˉ=eΔA,Bˉ=(ΔA)−1(eΔA−I) ΔB=∫0ΔeuAB du\bar{\mathbf{A}} = e^{\Delta \mathbf{A}}, \qquad \bar{\mathbf{B}} = (\Delta \mathbf{A})^{-1}(e^{\Delta \mathbf{A}} - \mathbf{I})\,\Delta \mathbf{B} = \int_0^\Delta e^{u\mathbf{A}}\mathbf{B}\,du

For scalar A=−1,B=1,Δ=1A = -1, B = 1, \Delta = 1, exact ZOH gives Aˉ=e−1≈0.368\bar{A} = e^{-1} \approx 0.368 and Bˉ=1−e−1≈0.632\bar{B} = 1 - e^{-1} \approx 0.632. Near A=0A = 0, evaluating (eΔA−1)/A(e^{\Delta A} - 1)/A directly loses precision, so numerical implementations use np.expm1 and fall back to Bˉ=ΔB\bar{B} = \Delta B at A=0A = 0.

S4: structured state spaces

An arbitrary random transition matrix A\mathbf{A} either explodes or forgets everything after a few dozen steps. S4 (Structured State Spaces)[2] solves long-horizon memory with HiPPO initialization[3], which projects input history onto orthogonal polynomials so different coordinates preserve information across many timescales right from step zero.

Because S4's coefficients (Aˉ,Bˉ,C)(\bar{\mathbf{A}}, \bar{\mathbf{B}}, \mathbf{C}) stay fixed across every token (a Linear Time-Invariant, or LTI, system), the exact same model runs in two mathematically identical modes:

  • Recurrent mode (generation): ht=Aˉht−1+Bˉxth_t = \bar{\mathbf{A}} h_{t-1} + \bar{\mathbf{B}} x_t, updating in O(s)O(s) time and O(s)O(s) memory per channel.
  • Convolutional mode (training): Unrolling from h0=0h_0 = 0 turns the entire sequence into a single causal convolution y=x∗Kˉ+Dxy = x * \bar{K} + \mathbf{D}x with impulse-response kernel Kˉj=CAˉjBˉ\bar{K}_j = \mathbf{C}\bar{\mathbf{A}}^j\bar{\mathbf{B}}, computed in parallel via FFT in O(Llog⁡L)O(L \log L) time! (Starting from nonzero h0h_0 adds the decaying homogeneous term CAˉth0\mathbf{C}\bar{\mathbf{A}}^t h_0.)
zoh-and-convolution-duality.py
import numpy as np

# 1. Exact ZOH discretization (stable near A=0 via expm1)
for a in (-1.0, 0.0, -1e-12):
    delta = 1.0
    a_bar = np.exp(delta * a)
    b_bar = delta if a == 0.0 else np.expm1(delta * a) / a
    print(f"ZOH A={a:g}: A_bar={a_bar:.6f}, B_bar={b_bar:.6f}")

# 2. Causal convolution matches sequential recurrence bit for bit
x = np.array([3.0, 1.0, 4.0, 2.0])
kernel = 0.2 * (0.9 ** np.arange(len(x)))
conv_out = np.convolve(x, kernel)[:len(x)]

h, rec_out = 0.0, []
for val in x:
    h = 0.9 * h + 0.2 * float(val)
    rec_out.append(h)

assert np.allclose(conv_out, rec_out, atol=1e-12)
print("recurrence == convolution:", np.round(conv_out, 4).tolist())
Output
ZOH A=-1: A_bar=0.367879, B_bar=0.632121
ZOH A=0: A_bar=1.000000, B_bar=1.000000
ZOH A=-1e-12: A_bar=1.000000, B_bar=1.000000
recurrence == convolution: [0.6, 0.74, 1.466, 1.7194]
Unrolled lower-triangular causal convolution matrix K for A-bar = 0.9 and B-bar = 0.2 multiplied by x = [3, 1, 4, 2] producing outputs [0.600, 0.740, 1.466, 1.719] identical to the recurrence.
With fixed LTI coefficients, unrolling the recurrence becomes a Toeplitz matrix-vector product (causal convolution) with kernel [0.200,0.180,0.162,0.146][0.200, 0.180, 0.162, 0.146], producing identical outputs in parallel.

Mamba: selective state spaces

Mamba breaks the LTI bottleneck by making Bt\mathbf{B}_t, Ct\mathbf{C}_t, and step size Δt\Delta_t functions of the current token activation xtx_t while keeping diagonal A<0\mathbf{A} < 0 and skip D\mathbf{D} input-independent:[1]

Bt=LinearB(xt),Ct=LinearC(xt),Δt=softplus(LinearΔ(xt))\mathbf{B}_t = \text{Linear}_B(x_t), \qquad \mathbf{C}_t = \text{Linear}_C(x_t), \qquad \Delta_t = \text{softplus}(\text{Linear}_\Delta(x_t))

Because A\mathbf{A} has negative diagonal entries, Δt\Delta_t acts like a continuous content-aware gate:

  • Large Δt\Delta_t: shrinks carryover eΔtAe^{\Delta_t A} (forgetting old clutter) and amplifies the new write ΔtBtxt\Delta_t B_t x_t (writing an important token into state).
  • Small Δt\Delta_t: keeps eΔtA≈1e^{\Delta_t A} \approx 1 (preserving memory) and skips over filler tokens.

Inside a Mamba-1 block, the projected input splits into two branches: the upper path runs a short causal 1D convolution (k=4) and SiLU before driving the selective SSM scan, and the lower SiLU(z) branch gates the output elementwise.[1][4][5]

Dataflow diagram of a Mamba selective SSM block: input x[t] of width D passes through a linear projection of width 2E and splits into two branches. The upper branch runs a causal 1D convolution (k=4) and SiLU, generates input-dependent Delta_t, B_t, and C_t parameters for the selective scan with D skip connection, and multiplies elementwise with the lower SiLU(z) gating branch before output projection back to y[t] of width D.
Mamba-1 block: the main stream applies a width-4 causal convolution, SiLU, and input-selective SSM scan, then multiplies elementwise by a parallel SiLU(z) gate.

How do you parallelize a non-LTI recurrence on GPUs?

Once Aˉt\bar{\mathbf{A}}_t and Bˉt\bar{\mathbf{B}}_t vary per token, FFT convolution no longer applies. Mamba recovers O(log⁡L)O(\log L) parallel depth with two ideas:

  1. Associative parallel scan: Every step is an affine transform h↦ath+bth \mapsto a_t h + b_t. Composing two steps (a1,b1)(a_1, b_1) then (a2,b2)(a_2, b_2) yields (a2a1,a2b1+b2)(a_2 a_1, a_2 b_1 + b_2). That composition is associative (though non-commutative, so left-to-right order stays fixed), letting a binary prefix-scan tree compute all LL states in parallel!
  2. SRAM fusion: Like FlashAttention, Mamba's kernel fuses discretization and scan inside fast on-chip SRAM so expanded states never materialize in slow HBM.[1]
Two-pass associative scan over four steps: bottom-up reduction merges (a, b) tuples to root (0.6561, 1.7194), and top-down prefix distribution computes states [0.600, 0.740, 1.466, 1.719] in O(log L) depth.
A two-pass Blelloch-style associative prefix scan composes affine pairs upward and distributes prefixes downward, recovering every intermediate state in O(log⁡L)O(\log L) depth.
associative-prefix-scan.py
def compose(right, left):
    a_r, b_r = right
    a_l, b_l = left
    return a_r * a_l, a_r * b_l + b_r

def prefix_scan(steps, initial=0.0):
    n = len(steps)
    size = 1
    while size < n:
        size *= 2
    tree = [(1.0, 0.0)] * (2 * size)
    tree[size:size + n] = steps
    for node in range(size - 1, 0, -1):
        tree[node] = compose(tree[2 * node + 1], tree[2 * node])

    out = [0.0] * n
    def down(node, before):
        if node >= size:
            idx = node - size
            if idx < n:
                a, b = compose(tree[node], before)
                out[idx] = a * initial + b
            return
        down(2 * node, before)
        down(2 * node + 1, compose(tree[2 * node], before))

    down(1, (1.0, 0.0))
    return out

steps = [(0.9, 0.6), (0.9, 0.2), (0.9, 0.8), (0.9, 0.4)]
print("prefix scan states:", [round(v, 4) for v in prefix_scan(steps)])
print("order matters (non-commutative):", compose(steps[1], steps[0]) != compose(steps[0], steps[1]))
Output
prefix scan states: [0.6, 0.74, 1.466, 1.7194]
order matters (non-commutative): True

Mamba-2 and Mamba-3: Tensor Cores and decode intensity

Mamba-1 was linear time, yet its custom elementwise scan underutilized GPU Tensor Cores.

  • Mamba-2 (State Space Duality, SSD)[6] constrains each head's transition At\mathbf{A}_t to a scalar multiple of the identity matrix. That restriction exposes a direct duality with masked linear attention and splits sequence work into fixed chunks (e.g., width 256): intra-chunk outputs and chunk-end states run as batched Tensor Core matrix multiplications, leaving only a tiny inter-chunk scan across chunk boundaries. Core layers run 2–8x faster than Mamba-1's scan!
  • Mamba-3[7] targets memory-bound decoding along three axes: exponential-trapezoidal discretization (ht=αtht−1+(1−λt)ΔtαtBt−1xt−1+λtΔtBtxth_t = \alpha_t h_{t-1} + (1-\lambda_t)\Delta_t\alpha_t B_{t-1}x_{t-1} + \lambda_t\Delta_t B_t x_t, replacing the separate conv buffer with a previous-write slot), complex-valued rotations for stronger state tracking (like parity and modular arithmetic), and multi-input, multi-output (MIMO) state updates that execute up to 4x more decode FLOPs at matched H100 latency by increasing inside the memory-bound state read.

Complexity comparison and hybrid architectures

Compare per-request live decode memory for a 32-layer model (2 bytes/element) as context scales from 128 to 65,536 tokens:

ArchitectureTrainingDecode / tokenLive decode stateAt 64K context (32L)
Transformer (MHA-32)O(L2d)O(L^2 d)O(Ld)O(Ld)O(Ld)O(Ld) linear32,768 MiB (32 GiB)
Hybrid (4 Attn + 28 SSM)MixedMixedO(Ld)O(Ld) (12.5% slope)4,100 MiB (4.0 GiB)
Pure Mamba-1 SSMO(Lsd)O(L s d)O(sd)O(sd)O(sd)O(sd) constant5.0 MiB
Per-request cache memory across 128 to 64K context tokens on a log-spaced context axis: 32-layer attention KV cache climbs linearly to 32 GiB and a 4-attention plus 28-SSM hybrid reaches 4.004 GiB, while a pure 32-layer SSM stays constant at 5 MiB across all context lengths (shown in the zoomed 0 to 10 MiB inset).
Live decode memory across context lengths: Transformer KV climbs to 32 GiB at 64K, a 4-attention/28-SSM hybrid drops to 4.0 GiB, and a pure SSM stays flat at 5.0 MiB.

Why do hybrid architectures dominate practical long-context SSM deployments? Because pure fixed-state models compress history into a finite vector: two distinct prefixes can collide into the exact same state (summarize([3, 1]) == summarize([1, 2]) == 1.25 under ht=0.5ht−1+0.5xth_t = 0.5 h_{t-1} + 0.5 x_t), making exact verbatim copying harder over long documents. Interleaving a handful of attention layers restores token-addressable lookup while slashing KV growth by 8x–12x:

Interleaved layer compositions for hybrid SSM-Transformer models. Jamba repeats an 8-layer block with 1 attention layer and 7 Mamba layers (12.5% KV layers). Nemotron-H-8B interleaves 4 attention layers across 52 total layers alongside 24 Mamba-2 and 24 FFN layers (7.7% KV layers), shrinking KV cache by 8x to 13x relative to an all-attention stack.
Hybrid backbones run every token sequentially through mostly recurrent layers plus occasional full-attention layers that restore direct token lookup at a fraction of the KV cost.

Serving subtleties: checkpoints, conv buffers, and rollback

Fixed live decode state changes how serving engines handle prefix caching and speculative decoding:

  1. Prefix snapshots still grow with length: To resume a shared 64K prompt at arbitrary boundaries without re-running prefill, engines like vLLM cache periodic SSM checkpoints (e.g., 5 MiB every 1,024 tokens = 320 MiB of snapshots beside the 5 MiB live state).[11]
  2. Save EVERY stateful buffer: Resuming a Mamba-1 block requires saving both the recurrent state hth_t and the rolling causal convolution window. Restoring only hth_t while zeroing the conv buffer silently corrupts the very next token.
  3. Speculative rollback needs snapshots, not truncation: Unlike a KV cache (where rejecting draft tokens simply truncates trailing slots), an SSM mutates one state slot in place. And you cannot algebraically invert the step, because tiny decay factors like e−1000e^{-1000} underflow to 0.0. Engines must restore an accepted checkpoint or replay from the last accepted token.

Let's verify both failure modes (missing conv buffer and dirty speculative rollback) plus the prefill-vs-decode latency crossover in one short NumPy script:

ssm-state-checkpoint-and-rollback.py
# 1. Conv buffer + recurrence checkpoint restoration
w = np.array([0.2, 0.3, 0.5])
def run_conv_ssm(vals, h=0.0, buf=None):
    buf = np.zeros(3) if buf is None else buf.copy()
    out = []
    for v in vals:
        buf = np.roll(buf, -1); buf[-1] = v
        h = 0.5 * h + float(np.dot(w, buf))
        out.append(h)
    return out, h, buf

full, _, _ = run_conv_ssm([3., 1., 4., 2.])
_, h2, b2 = run_conv_ssm([3., 1.])
exact, _, _ = run_conv_ssm([4., 2.], h2, b2)
broken, _, _ = run_conv_ssm([4., 2.], h2, None)
print("conv+SSM exact vs missing-conv:", np.round(exact, 4).tolist(), "vs", np.round(broken, 4).tolist())

# 2. Speculative rollback: accept 99, reject 77, sample correction 4
step = lambda h, x: 0.5 * h + 0.5 * x
h_prefix = step(step(0.0, 3.0), 1.0)
h_after_99 = step(h_prefix, 99.0)
h_dirty_77 = step(h_after_99, 77.0)
print(f"speculative rollback exact={step(h_after_99, 4.0):.4f}, dirty={step(h_dirty_77, 4.0):.4f}")

# 3. Prefill vs decode crossover (prefill emits token 1, so N-1 decode steps)
for n in (16, 256):
    t_attn = 120.0 + (n - 1) * 3.2
    t_ssm  = 150.0 + (n - 1) * 1.8
    print(f"N={n:3d} tokens -> attn={t_attn:.1f} ms, ssm={t_ssm:.1f} ms")
Output
conv+SSM exact vs missing-conv: [3.975, 4.3875] vs [3.075, 3.7375]
speculative rollback exact=27.0625, dirty=33.7812
N= 16 tokens -> attn=168.0 ms, ssm=177.0 ms
N=256 tokens -> attn=936.0 ms, ssm=609.0 ms
Total generation latency comparing attention (120 ms prefill plus 3.2 ms per decode token) and SSM (150 ms prefill plus 1.8 ms per decode token). The two curves cross at N = 22.4 tokens (188.6 ms): attention is slightly faster at N = 16 (168 ms vs 177 ms), while SSM pulls far ahead at N = 256 (609 ms vs 936 ms).
Attention wins short 16-token answers thanks to lower prefill latency, while lower per-token decode cost lets the SSM overtake at 23 tokens and lead by 327 ms at 256 tokens.

When to use SSMs vs. transformers vs. hybrids

WorkloadBest starting pointWhy
Short-to-medium chat / few-shot copyTransformerMature fused attention kernels and exact token lookup
128K+ long-document servingHybrid (SSM + sparse attention)Slashes KV memory 8x–12x while keeping exact recall paths
Real-time streaming / tight edge RAMPure SSM or SSM-heavy hybridFlat O(1)O(1) live decode memory regardless of stream length

Before adopting any pure SSM for retrieval-heavy tasks, run the multi-depth NIAH and variable-tracking benchmarks from Long Context Window Management alongside peak memory and throughput measurements.

Where fixed-state models lead

SSMs trade token-indexed KV tables for compact, learned recurrences, and hybrid backbones capture most of the memory win without abandoning exact retrieval. Next, we turn to Reasoning & Test-Time Compute, where models deliberately spend thousands of extra decode tokens thinking through hard problems.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A team will benchmark decode memory and rare identifier lookup on 256K-token API specs. It replaces 18 of 24 identical full-attention layers with fixed-state SSM layers. The remaining attention layers keep their original KV dimensions. For one request, what fraction of the original KV growth per token remains, and which layers keep a separate entry for each earlier position?
2.A scalar SSM starts a step with state 6 and input 4. Its discrete coefficients are A = 0.5, B = 2, C = 1 and D = 0.5. An engineer replays that step with C = 3 and all other values unchanged. What pair (updated state, output) should the replay produce?
3.A scalar SSM obeys h′(t)=−2h(t)+3x(t)h'(t)=-2h(t)+3x(t). Each step lasts 0.75 time units, and the input stays constant during the step. In the discrete update hnext=ahold+bxh_{\mathrm{next}}=a h_{\mathrm{old}}+b x, which pair (a,b)(a,b) reproduces the continuous dynamics? Round each coefficient to three decimal places.
4.From zero, process [2,5,1,3] using h_t=0.5 h_(t-1)+0.5 x_t. What final state follows?
5.An S4 layer has two state coordinates with different fixed decay rates. Both start at zero. After decay, each coordinate adds the current input. The output is their sum. Which probe produces outputs you can use directly as a causal convolution kernel for full training sequences, and what should the decoder save between tokens?
6.An LTI SSM treats a routine token and a max_retries identifier with the same update rule. In Mamba-1, what makes the update selective, and what does a very large Δt\Delta_t do when A<0A<0?
7.A reference Mamba implementation loops over sequence positions in Python on GPU and spills intermediate states to HBM. It is mathematically correct but slow. What production change addresses this bottleneck?
8.A profile shows Mamba-1 underusing Tensor Cores, and a proposal says Mamba-3 is just the Tensor Core rewrite. Which statement correctly separates Mamba-2 from Mamba-3?
9.Starting from zero, an inclusive scan applies h↦0.4h+3h \mapsto 0.4h+3 first and h↦0.25h+2h \mapsto 0.25h+2 second. Which list of states does it return?
10.A latency benchmark measures attention prefill at 90 ms and subsequent decode at 2.8 ms/step, while an SSM takes 120 ms for prefill and 1.4 ms/step for decode. Prefill produces token 1. Which totals follow at 16 and 256 generated tokens?

10 questions remaining.

References

Mamba: Linear-Time Sequence Modeling with Selective State Spaces

Gu & Dao · 2023

https://arxiv.org/abs/2312.00752

Efficiently Modeling Long Sequences with Structured State Spaces

Gu et al. · 2022 · ICLR 2022

https://arxiv.org/abs/2111.00396

HiPPO: Recurrent Memory with Optimal Polynomial Projections.

Gu, A., Dao, T., Ermon, S., Rudra, A., & Ré, C. · 2020 · NeurIPS 2020

https://arxiv.org/abs/2008.07669

Mamba selective scan implementation

State Spaces Contributors · 2026

https://github.com/state-spaces/mamba/blob/e9594ce1c732d97440f0332fdc43170a2294dbfa/mamba_ssm/ops/selective_scan_interface.py

Mamba-1 block implementation

State Spaces Contributors · 2026

https://github.com/state-spaces/mamba/blob/e9594ce1c732d97440f0332fdc43170a2294dbfa/mamba_ssm/modules/mamba_simple.py

Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality

Dao & Gu · 2024

https://arxiv.org/abs/2405.21060

Mamba-3: Improved Sequence Modeling using State Space Principles

Lahoti, A., Li, K. Y., Chen, B., Wang, C., Bick, A., Kolter, J. Z., Dao, T., & Gu, A. · 2026

https://arxiv.org/abs/2603.15569

Jamba: A Hybrid Transformer-Mamba Language Model

AI21 Labs · 2024

https://arxiv.org/abs/2403.19887

Nemotron-H: A Family of Accurate and Efficient Hybrid Mamba-Transformer Models

NVIDIA · 2025

https://arxiv.org/abs/2504.03624

Qwen3.6-35B-A3B

Qwen Team · 2026

https://huggingface.co/Qwen/Qwen3.6-35B-A3B

vLLM Mamba cache configuration (pinned source)

vLLM Project · 2026

https://github.com/vllm-project/vllm/blob/4edb55169f69c76bb87ab9f154585917cb01bb17/vllm/config/cache.py

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.