State Space Models & Alt-Architectures
After this lesson, you will be able to:
- Explain why attention's O(N²) cost is the architectural ceiling that motivates linear-time alternatives, and what 'linear time' actually buys you in training and inference
- Walk through the discretization that turns a continuous state space x'(t) = Ax + Bu into the Mamba selective scan you can actually run on a GPU
- Pick the right architecture for a workload — pure transformer for retrieval-heavy tasks, pure SSM for streaming low-memory inference, or hybrid (Jamba/Zamba) for long-context cost-sensitive deployments
- Recognize the strengths and weaknesses of Mamba, RWKV, RetNet, and Hyena well enough to read a 2025 paper without getting lost in the alphabet soup
Before you start
Don't worry if "state space" sounds like control theory. That is exactly where it came from, and the connection back to Kalman filters and signal processing is part of why these models work. The math looks daunting but the core idea is just "an RNN you can train in parallel."
#Why We Even Need Alternatives
#The Mathematical Setup
#Mamba: Selectivity Changes Everything
Mamba's change is to let the step size and the read and write matrices depend on the current input, so the state can keep what matters and skip filler. The full derivation, the selective scan and the Mamba-2 duality are in the same Deep Learning lesson. What follows is the cost comparison with attention.
#The Family Tree of Alt-Architectures
| Model | Core idea | Training | Inference | Strength | Weakness |
|---|---|---|---|---|---|
| S4 (2022) | HIPPO-init linear SSM | O(N log N) conv | O(N) recur | Long-range arena | LM quality below transformers |
| Mamba (2023) | Input-dependent SSM (selective scan) | O(N) parallel scan | O(1) per token | LM-quality competitive at small/mid scale | Recall/copying tasks |
| Mamba-2 (2024) | State-space duality with attention | Same | Same | Better quality, simpler kernel | Newer, less battle-tested |
| RWKV (2023) | RNN with linear-attention parallel training | O(N) parallel | O(1) per token | Open source, multilingual focus | Hyperparameter sensitivity |
| RetNet (2023) | Retention with three modes (parallel/recurrent/chunkwise) | Multi-mode | O(1) recur | Mode flexibility | Quality gap to transformer at scale |
| Hyena (2023) | Long convolutions + element-wise gates | O(N log N) FFT | O(N log N) FFT | Very long context | No exact O(1) recurrent inference |
| Linformer (2020) | Project K, V to fixed length | O(N) | O(N) | Drop-in attention swap | Loses content selectivity |
| Performer (2020) | Random feature kernel approximation of attention | O(N) | O(N) | Theoretically sound | Quality gap for hard tasks |
Hybrid 2024–2025 systems typically use about one attention layer per 7–8 Mamba layers. That is enough to handle in-context learning and copy/recall tasks, while keeping most of the cost on the linear path.
You have to serve 10M-token contexts (e.g. lifetime medical history) on commodity hardware. Pure transformer is impossible — KV cache alone exceeds VRAM. Which architecture earns the slot?
#Building a Tiny Selective SSM
The numpy version below runs on this page. Edit it and run it.
Tests: Check that the output shape is (4096, 64), that nothing is NaN, and that the state stays the same size however long the sequence is.
The same idea with real PyTorch needs a library that does not run on this page. Copy the code below to Google Colab.
# Copy to Colab: needs torch, so it cannot run on this page.
# Minimal selective SSM in PyTorch — Mamba's selective scan, simplified
import torch
import torch.nn as nn
import torch.nn.functional as F
class TinySelectiveSSM(nn.Module):
"""A 50-line selective state space model.
Real Mamba uses a hand-tuned CUDA kernel for the parallel scan.
This naive version is O(N) sequential — fine for understanding,
too slow for production training. Run with batch=1 for the demo.
"""
def __init__(self, d_model=64, d_state=16):
super().__init__()
self.d_state = d_state
# The "structured" A matrix: diagonal with negative real parts (for stability)
# This is the HIPPO-style decay; in real Mamba it is learnable per-channel
log_A = torch.log(torch.linspace(0.1, 1.0, d_state))
self.log_A = nn.Parameter(log_A.expand(d_model, d_state).clone())
# Input-dependent projections that produce B_t, C_t, Delta_t per step
self.proj_BCdt = nn.Linear(d_model, 2 * d_state + 1)
# In-projection and out-projection (real Mamba has more structure)
self.in_proj = nn.Linear(d_model, d_model)
self.out_proj = nn.Linear(d_model, d_model)
def forward(self, u):
# u: (batch, seq_len, d_model)
B, T, D = u.shape
u = self.in_proj(u)
# Compute per-step B_t, C_t, delta_t
bcd = self.proj_BCdt(u) # (B, T, 2*d_state + 1)
B_t, C_t, dt = bcd.split([self.d_state, self.d_state, 1], dim=-1)
dt = F.softplus(dt) # delta must be positive
# The state. (B, D, d_state) — one state per channel (per-channel SSM)
x = torch.zeros(B, D, self.d_state, device=u.device)
ys = []
# A is fixed in this toy version; in real Mamba it is also gated
A = -torch.exp(self.log_A) # (D, d_state), negative for stable decay
for t in range(T):
# Discretize: A_bar = exp(dt * A), B_bar = dt * B
A_bar = torch.exp(dt[:, t] * A.unsqueeze(0)) # (B, D, d_state)
B_bar = dt[:, t].unsqueeze(-1) * B_t[:, t].unsqueeze(1) # (B, 1, d_state) -> (B, D, d_state)
# Update state
x = A_bar * x + B_bar * u[:, t].unsqueeze(-1) # (B, D, d_state)
# Read out via C_t, summed over state dim
y = (x * C_t[:, t].unsqueeze(1)).sum(dim=-1) # (B, D)
ys.append(y)
y = torch.stack(ys, dim=1)
return self.out_proj(y)
# Demo: process a 4096-length sequence, watch memory stay flat
torch.manual_seed(0)
model = TinySelectiveSSM(d_model=64, d_state=16)
u = torch.randn(1, 4096, 64)
print(f"Input shape: {tuple(u.shape)}")
print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
with torch.no_grad():
y = model(u)
print(f"Output shape: {tuple(y.shape)}")
print(f"State size: {16} per channel (constant, regardless of T)")
print()
print("Compare to attention on the same sequence:")
print(" - Attention: O(T^2) = 4096^2 = 16.7M ops + O(T^2) memory")
print(" - This SSM: O(T) = 4096 ops + O(d_state) memory")
print()
print("CHALLENGE: Replace the python for-loop with a parallel scan")
print("(torch.cumsum-based associative scan). Real Mamba uses a custom")
print("CUDA kernel; an associative scan via prefix sums is the textbook approach.")
print("Hint: log-cumsum-exp gives you the running A_bar product.")
# Parallel scan sketch (still slower than custom CUDA but illustrates the idea):
# log_A_bar = (dt * A).cumsum(dim=1) # log of running product of A_bar
# A_bar_running = log_A_bar.exp() # running product
# Then: x_t = sum_{s<=t} (running_A_t / running_A_s) * B_bar_s * u_s
# Which is a single parallel reduction per channel.
# Real Mamba uses Blelloch scan in CUDA shared memory and gets ~3x faster
# than a naive associative scan.#Key Takeaways
- State space models are linear-time alternatives to attention. They compress the past into a fixed-size state and update it each step. Inference is O(1) per token with constant memory; training is O(N) parallelizable via convolution or scan.
- HIPPO initialization is what made S4 work. Random init fails badly. The structured initialization is non-negotiable; modern selective SSMs (Mamba) inherit HIPPO-style structure even after making A partly learnable.
- Selectivity is what made Mamba match transformers. Input-dependent B_t, C_t, Δ_t let the state skip over filler while keeping what it holds, and write in the inputs that are informative. This breaks time-invariance and requires a hardware-aware parallel scan.
- Hybrids beat purity in production. Pure SSMs underperform on copying, recall, and in-context learning. Jamba and Zamba intersperse a few attention layers among many Mamba layers; this hybrid is the practical default for cost-sensitive long-context deployment.
- The architecture race is not over. Transformers are not the final answer; they are the current local optimum that combines content-based retrieval with hardware-friendly matmul. SSMs, RWKV, RetNet, and Hyena are all credible alt-architectures with active research traction.
#Quick Check
What is the asymptotic inference cost per token for a selective SSM (Mamba) vs a vanilla transformer (without KV cache)?