On this page
Every token a standard Transformer generates appends another row to its KV cache. 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 State Space Models (SSMs) and Mamba.[1] Full self-attention keeps every past token directly addressable in memory, making exact verbatim lookup natural at cache cost. An SSM folds history into a fixed recurrent state , giving per-request decode memory and linear-time training at the price of compressing past tokens into a finite vector.

What is the core serving tradeoff between attention and Mamba-style SSMs?
Answer
Attention keeps token-level access to prior context through a KV cache that grows linearly with sequence length. Mamba-style SSMs keep a fixed-size recurrent state, eliminating context-length memory growth during decode while compressing history.
A discrete recurrence you can compute by hand
At its heart, a discrete SSM is two linear equations that update a hidden state and read out an output :
The first term carries prior memory forward; the second writes the new token into state. Set , , , , and step through the four inputs starting from :
| Step | Input | Carry | Write | State |
|---|---|---|---|---|
| 1 | 3 | 0.0000 | 0.60 | 0.6000 |
| 2 | 1 | 0.5400 | 0.20 | 0.7400 |
| 3 | 4 | 0.6660 | 0.80 | 1.4660 |
| 4 | 2 | 1.3194 | 0.40 | 1.7194 |
Look at how clean that is: memory never grows, yet step 4 still carries echoes of all four inputs (most of comes from carried history rather than the latest write). Lower 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 and come from
SSMs begin in continuous time as a linear differential equation driven by signal :
Because language arrives as discrete tokens rather than smooth waveforms, we discretize over a step width using a zero-order hold (ZOH) (holding constant across each step ):[1]
For scalar , exact ZOH gives and . Near , evaluating directly loses precision, so numerical implementations use np.expm1 and fall back to at .
S4: structured state spaces
An arbitrary random transition matrix 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 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): , updating in time and memory per channel.
- Convolutional mode (training): Unrolling from turns the entire sequence into a single causal convolution with impulse-response kernel , computed in parallel via FFT in time! (Starting from nonzero adds the decaying homogeneous term .)
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())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.](https://assets.leetllm.com/v1/cd7609151bdf/fundamentals/state-space-models-mamba-alternatives/illustrations/_generated/recurrence_convolution_dark.png)
Mamba: selective state spaces
Mamba breaks the LTI bottleneck by making , , and step size functions of the current token activation while keeping diagonal and skip input-independent:[1]
Because has negative diagonal entries, acts like a continuous content-aware gate:
- Large : shrinks carryover (forgetting old clutter) and amplifies the new write (writing an important token into state).
- Small : keeps (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.](https://assets.leetllm.com/v1/a7760c639e1c/fundamentals/state-space-models-mamba-alternatives/illustrations/_generated/mamba_block_dark.png)
How do you parallelize a non-LTI recurrence on GPUs?
Once and vary per token, FFT convolution no longer applies. Mamba recovers parallel depth with two ideas:
- Associative parallel scan: Every step is an affine transform . Composing two steps then yields . That composition is associative (though non-commutative, so left-to-right order stays fixed), letting a binary prefix-scan tree compute all states in parallel!
- SRAM fusion: Like FlashAttention, Mamba's CUDA 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.](https://assets.leetllm.com/v1/b7160b69b416/fundamentals/state-space-models-mamba-alternatives/illustrations/_generated/selective_scan_dark.png)
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]))prefix scan states: [0.6, 0.74, 1.466, 1.7194]
order matters (non-commutative): TrueWhy can an associative scan parallelize selective SSMs, but not a standard RNN whose transition depends on the previous hidden state?
Answer
In a selective SSM, every affine pair (a_t, b_t) depends only on the input sequence x_t, so all pairs exist upfront before the scan. A nonlinear RNN mixes h_{t-1} inside its transition, preventing associative pre-composition.
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 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 (, 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 arithmetic intensity 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:
| Architecture | Training | Decode / token | Live decode state | At 64K context (32L) |
|---|---|---|---|---|
| Transformer (MHA-32) | linear | 32,768 MiB (32 GiB) | ||
| Hybrid (4 Attn + 28 SSM) | Mixed | Mixed | (12.5% slope) | 4,100 MiB (4.0 GiB) |
| Pure Mamba-1 SSM | constant | 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 ), 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:
- Jamba-v0.1[8]: 1 attention + 7 Mamba layers per 8-layer block (with MoE MLPs).
- Nemotron-H 8B[9]: 4 attention + 24 Mamba-2 + 24 FFN sublayers (~8% attention).
- Qwen3.6-35B-A3B[10]: alternates 3 Gated DeltaNet layers with 1 gated-attention layer alongside MoE FFNs.

Serving subtleties: checkpoints, conv buffers, and rollback
Fixed live decode state changes how serving engines handle prefix caching and speculative decoding:
- 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 MiBof snapshots beside the5 MiBlive state).[11] - Save EVERY stateful buffer: Resuming a Mamba-1 block requires saving both the recurrent state and the rolling causal convolution window. Restoring only while zeroing the conv buffer silently corrupts the very next token.
- 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 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:
import numpy as np
# 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")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
When to use SSMs vs. transformers vs. hybrids
| Workload | Best starting point | Why |
|---|---|---|
| Short-to-medium chat / few-shot copy | Transformer | Mature fused attention kernels and exact token lookup |
| 128K+ long-document serving | Hybrid (SSM + sparse attention) | Slashes KV memory 8x–12x while keeping exact recall paths |
| Real-time streaming / tight edge RAM | Pure SSM or SSM-heavy hybrid | Flat 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.