01/ 03Case study
Efficient Sequence Modeling: From S4 to Mamba-3
Five sequence backbones written from first principles in pure PyTorch, checked against float64 references, trained at matched parameter counts over three to five seeds, and benchmarked for decoding up to 32K tokens.
- Python
- PyTorch
- NumPy
- SciPy
- Hugging Face Datasets
- Matplotlib
- pytest
- uv
Lab/See it run
Tokens inA sequence of tokens enters the model. Every architecture in the study reads this same input through one shared skeleton.
01/Overview
What this is.
ssmbench is a from-scratch study of how efficient sequence models evolved: a causal Transformer (sinusoidal or RoPE positions) alongside S4D, Mamba-1, Mamba-2 and Mamba-3, all in pure PyTorch behind one interface with a parallel form for training and an O(1) recurrent step() for generation (a KV cache for the Transformer).
The models are compared on controlled tasks at parameter counts matched within 10%, over three run seeds per task and five for parity, then benchmarked for training, prefill, decode, memory, reduced-precision error and torch.compile readiness on one 6 GB RTX 4050 Laptop GPU. Every table and figure is generated from committed JSON.
02/Problem
What motivated it.
Attention's cost grows quadratically with sequence length and its KV cache grows linearly. State-space models promise linear-time training and a fixed-size recurrent state, but each generation carries its own trade-off, and the claims are easy to repeat and hard to verify.
The gap this project attacks: what survives when each generation is implemented from first principles, checked against an independent reference, trained at matched budgets over several seeds, and measured on real hardware, failures included.
03/System
How it is built.
- transformer_minimal.py + attention.py
- Pre-norm causal Transformer with sinusoidal or RoPE positions. Attention runs through SDPA with the backend pinned per variant and the kernel that actually ran recorded; a naive reference checks every backend. Decoding uses a preallocated KV cache.
- s4_minimal.py
- S4D: complex diagonal A, LTI, exact zero-order hold computed as expm1(z)/z with a Taylor branch for small |z|, an FFT-convolution training form and an O(1) complex-state decode step.
- mamba_minimal.py
- Mamba-1: input-dependent Δ, B and C as a sequential selective scan, with an O(1) state-plus-conv-history step() for decoding.
- mamba2_minimal.py
- Mamba-2: a scalar decay per head turns the recurrence into chunked SSD matmuls with a carried state, computed in log space with direct segment sums; grouped B and C are expanded to heads explicitly.
- mamba3_minimal.py
- Mamba-3: complex diagonal decay per head and state slot with the exponential-trapezoidal rule, as a recurrence and as a chunked parallel scan with a two-band correction. Static rotation frequencies, real B and C, no MIMO.
- blocks.py + benchmarks/
- One decode interface (init_state, prefill, step) on every backbone, a seeded deterministic trainer with bitwise checkpoint resume, and the efficiency, inference, numerics and compile benchmarks.
04/Approach
The mechanisms that matter.
Independent references
Every model is checked against a naive float64 reference and with gradcheck, and prefill followed by single steps must reproduce the full forward pass. Comparing a model with itself is what let two real math bugs slip through the first version.
Matched parameters, several seeds
Each SSM gets the width whose parameter count is closest to the Transformer's, all within 10%. A run seed varies initialization, dropout and batch order while a separate data seed keeps every run on the same examples; each test set is scored once.
Pinned attention kernels
PyTorch picks an attention kernel at runtime, so the benchmark pins it with sdpa_kernel and records the kernel that actually ran. FlashAttention is not in the Windows torch wheel and is reported as unsupported, not skipped silently.
Decode as prefill, then step
Prefill returns exactly the state the recurrence would hold after the prompt, so time to first token, per-token latency and decode state are measured the same way for all five backbones.
Spills recorded as data
Points that run past free GPU memory are paged to system memory by the Windows display driver. They are flagged as spilled rather than reported as VRAM numbers, and longer lengths are skipped.
05/Evaluation
Setup and workloads.
- Hardware: RTX 4050 Laptop GPU (6 GB), PyTorch 2.14.1 with CUDA 13.0 and deterministic algorithms; the environment and code revision are recorded with the results.
- Tasks: cumulative-XOR parity trained at length 128 and tested up to 2048; selective copying (T=64 with 3 to 5 pairs in distribution, T=128 with 5 to 10 out of distribution); exact copying trained at length 32 or on lengths 1 to 32; IMDb sentiment on 12,500 reviews at 512 tokens, scored on the 25,000-review test split.
- Seeds: 104 GPU training runs, three run seeds per task and five for parity. Results are mean ± sample standard deviation.
- Benchmarks at width 256 and two layers from 1K to 32K tokens: batch-8 training step and peak memory, batch-1 time to first token and per-token decode with 64 new tokens, bf16 and fp16 error against float64, and torch.compile graph breaks.
06/Results
Measured outcomes.
- 89% / 99%
- parity on 2 of 5 Mamba-3 seeds (mean 72.6 ± 20.5%)
- ≤57.3%
- parity mean of every rotation-free model, 5 seeds (chance 50%)
- 0.39 MiB
- largest SSM decode state at 32K (fp32 KV cache: 128.25 MiB)
- 585
- tests, including float64 references and gradcheck




| Model | Parity, T=128 (n=5) | Selective copy, OOD (n=3) | Exact copy, L=32 (n=3) | IMDb test (n=3) |
|---|---|---|---|---|
| Transformer (sinusoidal) | 52.5 ± 0.9 | 12.1 ± 1.9 | 87.4 ± 3.7 | 81.6 ± 0.2 |
| Transformer (RoPE) | 51.7 ± 0.2 | 7.5 ± 0.9 | 98.6 ± 0.7 | 81.9 ± 0.6 |
| S4D | 50.9 ± 0.5 | 17.6 ± 3.4 | 19.7 ± 1.0 | 83.7 ± 0.2 |
| Mamba-1 | 57.3 ± 2.3 | 52.1 ± 20.4 | 35.6 ± 8.3 | not trained |
| Mamba-2 | 56.8 ± 2.7 | 49.6 ± 17.9 | 29.0 ± 2.4 | 84.5 ± 0.1 |
| Mamba-3 | 72.6 ± 20.5 | 14.4 ± 6.3 | 61.4 ± 5.7 | 82.5 ± 1.2 |
| Mamba-3, no rotation | 55.4 ± 1.2 | not run | not run | not run |
From results/SUMMARY.md, generated from results/train/. Accuracy in percent, mean ± sample standard deviation over n run seeds. Selective copy OOD is T=128 with 5 to 10 pairs (answer-token accuracy); exact copy is trained on lengths 1 to 32 and scored at 32. Chance: parity 50, selective copy 5.9, exact copy 3.8, IMDb 50. Parameters are matched within 10% per task (about 100K for parity, 0.37M to 0.40M for selective copy, 0.55M to 0.60M for exact copy, 3.0M to 3.4M for IMDb). Mamba-1 is not trained on IMDb because its sequential scan over 512 tokens is too slow on this GPU; the rotation ablation runs on parity only.
07/Findings
What the results say.
- 01
Rotation is what helps on parity, but only on some seeds: Mamba-3 reaches 89.2% and 99.0% on 2 of 5 seeds (mean 72.6 ± 20.5%); with its rotation removed it falls to 55.4%, and no seed exceeds 57.2%.
- 02
Every rotation-free model stays near chance on parity at T=128 (Mamba-1 57.3%, Mamba-2 56.8%, RoPE Transformer 51.7%, S4D 50.9%), and every model is back to 50.1 to 51.5% at T=2048.
- 03
Selectivity decides selective copying: Mamba-1/2/3 and the Transformers solve it in distribution (98 to 100%) while LTI S4D reaches 28.4%. Out of distribution only Mamba-1 and Mamba-2 keep about half the answers.
- 04
On IMDb all five trained models land between 81.6% and 84.5%; Mamba-2 is best at 84.5 ± 0.1%.
- 05
Decode state is the clearest systems difference: after a 32K prompt the SSM states take 0.14 to 0.39 MiB, while the Transformer's KV cache takes 128.25 MiB in fp32 (64.12 MiB in bf16).
- 06
Every forward pass compiles to one torch.compile graph with zero breaks; S4D's decode step has 4 breaks, at a Tensor.item() call in its parameter-version check.
08/Decisions
Why it was built this way.
One interface, five backbones
init_state, prefill and step on every model make decoding comparable and testable: prefill plus single steps must reproduce the forward pass.
References before speed
Naive float64 implementations and gradcheck are the source of truth for every fast form, including the chunked Mamba-3 scan (values, final state and gradients for chunk sizes 1 to 64).
Seeds vary training, not data
A run seed sets initialization, dropout and batch order; a separate data seed keeps the datasets fixed, so the spread comes from training alone.
Numbers come from generated tables
make_tables.py writes every table and figure from committed JSON, and its --check mode fails when a document drifts from the results.
Honest scope
Full S4 (NPLR), Mamba-3's MIMO form and input-dependent rotation frequencies are declared not implemented, and the benchmark sweeps are labelled as not parameter-matched.
09/Validation
How the claims are checked.
- 585 tests pass (one CUDA-only test skipped on CPU) with ruff and pyright clean. They check every backbone against a naive float64 reference, prefill plus single steps against the full forward pass, the chunked Mamba-3 scan against its recurrence for chunk sizes 1 to 64 and underflowing decays, gradcheck, RoPE against an independent complex rotation, and the attention backends against each other.
- The audit behind this version found two math bugs the earlier self-comparison tests could not catch: S4D's zero-order hold divided by 1 instead of z = Δ·A (gradients off by up to 7.8x), and Mamba-2/3 scrambled grouped B and C across heads. Every earlier result was re-run on the fixed code.
- Training is bitwise identical for equal seeds and after resuming from a checkpoint, and resume is refused across code versions.
- The environment (GPU, driver, PyTorch, CUDA and cuDNN versions, code revision) is recorded at the start of the GPU runs, and every attention result stores the kernel that actually ran.
10/Limitations
Stated plainly.
- Parity rests on a minority of seeds: two of five Mamba-3 seeds learn it, and the mean of 72.6 ± 20.5% hides that split.
- Nothing extrapolates in length: on exact copying every model is at most 13.1% beyond the longest training length, and every parity mean is 50.1 to 51.5% at length 2048.
- The benchmark sweeps are not parameter-matched: every model has width 256 and two layers (Transformer 1.58M parameters, S4D 183K, the Mamba variants about 876K), so no speed or memory ratio between architectures is like for like.
- Timing is one initialization on one laptop GPU with unlocked clocks. There are no fused kernels, and Inductor was not measured because Triton is not available on Windows.
- Small scale: 0.1M to 3.4M parameters and a few epochs. Full S4 (NPLR), Mamba-3's MIMO form and input-dependent rotation frequencies are not implemented.
11/Summary
- Built
- Five sequence backbones (Transformer, S4D, Mamba-1, Mamba-2, Mamba-3) from first principles in pure PyTorch behind one decode interface, trained over 104 GPU runs and benchmarked from 1K to 32K tokens on a 6 GB RTX 4050.
- Why
- To check each SSM generation's claims the only way that sticks: implement it, verify it against an independent reference, train at matched budgets over several seeds, and measure it.
- How it works
- Naive float64 references and gradcheck for correctness, parameter matching within 10% and three to five seeds for the comparisons, pinned attention kernels and flagged spills for the benchmarks, and generated tables for every number.
- Key decision
- Testing against independent float64 references instead of comparing a model with itself. That exposed two real math bugs in the first version and forced every result to be re-run.
- Strongest result
- Mamba-3 reaches 89% and 99% on parity on 2 of 5 seeds, while every rotation-free model, including Mamba-3 with its rotation removed, stays near chance (means ≤57.3%).
- Main limitation
- Only 2 of 5 Mamba-3 seeds learn parity, nothing extrapolates in length, and the benchmark sweeps are not parameter-matched.
- Next
- Fused scan kernels so the timings mean more, and more parity seeds to estimate how often the rotation is learned.
Common questions
Q01Why does Mamba-3 solve parity and Mamba-2 doesn't?
Parity needs a sign flip for every 1-bit, which is a rotation by π. Real, non-negative decays can only shrink the state; a complex rotation can flip it. The rotation-free ablation (55.4%) isolates that factor.
Q02Only 2 of 5 seeds learn it. Is the result real?
The capability exists, but optimization is seed-sensitive at this scale. That is why the results report mean ± std and the per-seed values, not the best seed.
Q03How did you find the bugs?
Naive float64 reference implementations, equivalence tests between the parallel and recurrent forms, and gradcheck. The old tests compared a model with itself in ways that could not catch either bug.
Q04Why is the SSM decode state constant?
The recurrence carries a fixed heads × N × P state, while a KV cache grows linearly with the prompt. At 32K that is at most 0.39 MiB for the SSMs against 128.25 MiB for the fp32 KV cache here.
Q05How do you keep zero-order hold stable?
Exact ZOH for diagonal A gives B̄ = ΔB(e^z - 1)/z with z = ΔA. expm1 avoids the cancellation in e^z - 1, and below |z| = 1e-2 in float32 (1e-4 in float64) a Taylor series keeps the value and its gradient accurate.
Q06Why pin the SDPA backend?
PyTorch picks the attention kernel at runtime, so unpinned benchmarks can compare different kernels across runs. The kernel that actually ran is detected and stored with each result.