Mamba (Selective SSM)

A transformer alternative built on a linear recurrence. No KV cache. Linear in sequence length. Two modes of computation from one model — parallel scan for training, recurrent for inference. As of 2026, mostly shipped inside hybrid SSM–attention LLMs.

Before you start

Prerequisites

  • Module 1 (Transformer): attention cost, the KV cache, prefill vs decode
  • RNN intuition: a hidden state updated once per token
  • exp/log, element-wise products, and PyTorch broadcasting (unsqueeze, einsum)

Time: about 60 minutes to read and try the widgets, 5 minutes to run mamba.py on a CPU, and 1–3 hours for the exercises in §12.

What you'll learn

  • Write the discretized SSM recurrence and say what "selective" (input-dependent Δ, B, C) adds
  • Why one layer can run as a parallel scan (training) or as an RNN step (generation), and check they agree
  • Count a Mamba block's parameters, FLOPs and per-sequence state, and compare with a KV cache
  • What the fused scan kernel, Mamba-2 (SSD) and hybrid SSM–attention models change for inference

🎬 Learn it visually

Watch or read one of these first if a section feels abstract. Ordered: best intuition first, code last.

  1. 🎥 MAMBA from Scratch, Algorithmic Simplicity (32 min). Best first watch: derives Mamba from a linear RNN with almost no SSM theory, including why the scan parallelises.
  2. 📖 A Visual Guide to Mamba and State Space Models, Maarten Grootendorst. Illustrated blog post from "what is a state" to selectivity and the hardware-aware scan.
  3. 🎥 Mamba and S4 Explained, Umar Jamil (1 h 14 min). The maths, slowly: discretization, convolution vs recurrent view, parallel scan, kernel fusion.
  4. 💻 The Annotated S4 and Mamba: The Hard Way, Sasha Rush. Annotated code, from S4 in JAX to a Triton implementation of the Mamba scan.

Notation on this page (Mamba paper symbols)

L
sequence length (Module 1 calls it N)
n_layer
number of layers (Module 1's L)
N
d_state = 16: state entries per channel, not the sequence length
D
in shapes: channels = D_inner = d_inner = 2·d_model; in y = C·h + D·x: the learned skip weight
b
batch size (Module 1's B; here B is an SSM matrix)
Δ, A, B, C
SSM parameters; Δt, Bt, Ct are computed from token t
d, d_model
model width, as in Module 1

The Core Idea: A Linear Recurrence

Intuition first. Mamba reads a sequence the way you keep notes in a meeting: it keeps a small running summary, and every new token decides how much of the old summary to keep and how much of itself to write in. That summary has a fixed size, so the cost per token never grows.

Strip away everything else, and Mamba is built on this recurrence, run independently for every one of the D channels of the input:

# For each time step t and each of the D channels, update an N-dim state h (N = 16 in Mamba-1):
Ā_t = exp(Δ_t · A)                     # [N] decay factors in (0, 1), because A < 0 and Δ_t > 0
B̄_t = Δ_t · B_t                        # [N] how strongly this input is written
h_t = Ā_t ⊙ h_{t-1} + B̄_t · x_t        # [N] new state = decayed old state + new input
y_t = C_t · h_t + D · x_t              # scalar: read the state out, plus a skip
#
# Key point: the recurrence is LINEAR in h. Composing two steps gives another step
# of the same form, which is associative, so it can be computed for all t in
# parallel (log-depth) even though it looks sequential. Attention is parallel too,
# but its compute is O(L²); a selective scan is O(L · D · N) with N ≈ 16.

This is a classic State Space Model (SSM): a continuous-time linear system (dh/dt = A·h + B·x) discretized with a step size Δ. Mamba's contribution is making Δ, B and C functions of the current input. A itself stays a learned constant, but the decay Ā_t = exp(Δ_t·A) still varies token by token through Δ_t. That gives the model an input-dependent way to decide what to store and what to forget, which earlier SSMs lacked.

The maths, one step at a time

1. Discretization: from a leak rate to a per-step keep-fraction

Intuition. A is a continuous "leak rate"; the step size Δ says how much time passes at this token. exp turns that into the fraction of memory kept, Ā, and Δ·B into how strongly the input is written, B̄.

Ā = exp(Δ·A)B̄ = Δ·B
Read it aloud
"A-bar equals e to the delta-times-A; B-bar equals delta times B." For one channel: A and B are [N] vectors (N = 16 in Mamba-1, A negative and learned, B computed from the token), Δ is one positive number per token and channel, so Ā and B̄ are [N] vectors and every entry of Ā lies between 0 and 1.
Why it exists
The SSM is defined in continuous time (dh/dt = A·h + B·x), but a computer needs a per-step update. exp of a negative number is always in (0, 1), so the state can never blow up whatever Δ is. Δ then doubles as the selection knob: small Δ keeps the memory, large Δ overwrites it. (The paper uses the zero-order-hold rule for B̄; the official code uses Δ·B, which agrees to first order in Δ: exercise 3.)
Tiny example

N = 2, A = (−1, −2), B = (1, 0.5):

Δ = 0.1 → Ā = (0.905, 0.819), B̄ = (0.1, 0.05)  keep most, write little

Δ = 1.0 → Ā = (0.368, 0.135), B̄ = (1.0, 0.5)  forget most, write a lot

Code
dA = torch.exp(delta.unsqueeze(-1) * A)                 # [b, L, D, N]
dB_u = delta.unsqueeze(-1) * B.unsqueeze(2) * u.unsqueeze(-1)  # [b, L, D, N]

2. The selective scan: update the summary, then read it

Intuition. New memory = (keep-fraction × old memory) + (write-strength × new input). The output reads the memory through C, plus a direct skip of the input.

ht = Āt ⊙ ht−1 + B̄t xtyt = Ct · ht + D xt
Read it aloud
"h-t equals A-bar-t times h-t-minus-one, element by element, plus B-bar-t times x-t; y-t is C-t dotted with h-t, plus D times x-t." Per channel: ht is the [N] state, xt and yt are scalars, Ct is [N] (computed from the token), D is one learned scalar.
Why it exists
It is the cheapest memory possible: one multiply-add per state entry per token, so a layer costs O(L·D·N) instead of attention's O(L²·d). Because Δ, B and C come from xt, each token chooses what to store. With fixed values (S4) every token would be stored the same way, and the model could not ignore filler or reset on a topic change.
Tiny example

Same A, B as above, C = (1, 1), D = 1, h0 = 0, tokens x = (1, 0, 2) with Δ = (1, 0.1, 1):

t=1: h = (1, 0.5),  y = 1 + 0.5 + 1 = 2.5

t=2: x = 0, small Δ: h = (0.905, 0.409), y = 1.314  (memory just fades slowly)

t=3: h = (0.368·0.905 + 2, 0.135·0.409 + 1) = (2.333, 1.055), y = 5.388

Code
for t in range(L):
    h = dA[:, t] * h + dB_u[:, t]                      # [b, D, N]
    y_t = torch.einsum("bdn,bn->bd", h, C[:, t])       # [b, D], then + D * u
Why this is a big deal. A transformer's attention costs O(L²) compute, and its KV cache grows with every token. A selective SSM costs O(L·D·N) and carries a fixed-size state. Concretely, Mamba-130M's whole recurrent state is 24 layers × 1536 channels × (16 state + 4 conv) values = 1.41 MiB in FP16, at any context length. A transformer of about the same size (12 layers, d = 768) needs 36 KiB of KV cache per token: 1.13 GiB at 32K tokens, per sequence.

1. SSM → Selective SSM — what Mamba adds

Intuition. A plain SSM forgets at a fixed rate, like a bucket with a hole of fixed size. Mamba lets every token resize the hole and decide how much water to pour in.

Plain SSMs (S4) use fixed A, B, C and step size Δ. Because nothing depends on the input, the whole layer is one long convolution that can be computed with an FFT: efficient and parallel, but every token is treated the same way. Mamba makes Δ, B and C input-dependent:

Where do Δ, B and C come from? S4 (fixed) A, B, C, Δ: fixed x_t scan: h ← Āh + B̄x y_t same for every token Mamba (selective) Δ_t, B_t, C_t = f(x_t) x_t selective scan y_t chosen per token

What to notice: the only change is the blue arrow. In S4 the purple box is a constant; in Mamba a small linear layer computes Δt, Bt and Ct from the current token, so every token sets its own write strength and read-out. A stays a learned constant, but the decay Āt = exp(Δt·A) still changes per token through Δt.

Plain SSM (S4)Selective SSM (Mamba)
ParametersA, B, C, Δ fixed: the same across the whole sequenceΔt, Bt, Ct = f(xt), data-dependent; A a learned constant
StrengthsTime-invariant ⇒ the layer is one long convolution (FFT); handles very long sequencesLearns when to "remember" vs "forget"; Mamba-3B matches Transformers twice its size (paper)
WeaknessesSame dynamics for every token, no input-dependent gating; worse than transformers on languageTime-varying ⇒ no convolution trick, needs a scan; more complex to implement (solved by the fused selective_scan_cuda kernel, §5)

Intuitively: when you read a paragraph and hit a word like "however", Δ_t might spike to say "reset state, new thought coming"; when you hit a filler word, Δ_t shrinks to say "keep going, don't let this perturb the state". Plain SSMs can't do this.

Worked example: what Δ does (A = −1, one state). The decay is Ā = exp(−Δ) and the input weight is B̄ = Δ·B:

Δ = 0.01 → Ā = 0.990 (keep 99% of the state, barely write the input)

Δ = 0.1 → Ā = 0.905

Δ = 1 → Ā = 0.368

Δ = 5 → Ā = 0.0067 (forget the past, write the input strongly)

The paper's reading: a large Δ resets the state and focuses on the current input; a small Δ keeps the state and ignores the input. Because Δ_t = softplus(Linear(x_t)) is computed from the token itself, the model decides per token, and per channel, which regime it is in.

Try it: step through a selective scan

One channel, one state, A = −1, B = C = 1. Orange bars are Δt; the green line is the memory ht.

t = 4
0.30
Δ_t
–
Ā_t = exp(−Δ_t)
–
B̄_t·x_t = Δ_t·x_t
–
h_t (= y_t here)
–
h_t again, as one sum
–

Selective mode uses Δt = softplus(4|xt| − 3), so big inputs get big steps. What to notice: in selective mode the spike at t = 4 gets a large Δ (Ā ≈ 0.27), so it overwrites the state; the small inputs that follow get a small Δ (Ā ≈ 0.93–0.95), so the state holds the spike (still ≈ 0.96 five tokens later) until the negative spike at t = 10 overwrites it. Switch to fixed Δ: every token is written and forgotten at the same rate, so the spike only reaches 0.31 and fades. The last stat recomputes ht as one sum over all past inputs, Σk (Π Ā)·B̄kxk, which is exactly what the parallel scan in §2 evaluates.

2. Two Modes of Computation

Intuition. A running total can be computed by walking left to right, or by adding pairs, then pairs of pairs, like a tournament bracket. Mamba's update is a running "total" of this kind, so it can use either.

The same recurrence admits two very different implementations. This is the most important thing to internalize about Mamba:

One recurrence, two ways to run it Training: parallel scan log₂ L levels 1 x₁ … x₈ depth O(log L) Inference: one token at a time x_t step(x_t, h) y_t state h fixed size 2 memory O(1) in L

What to notice: both sides compute exactly the same ht. Training sees the whole sequence, so it combines steps pairwise in a tree; generation sees one token at a time, so it carries a small state forward.

  1. 1Each leaf is one token's step et = (Āt, B̄t·xt). Neighbouring steps combine with (a₂, b₂) ∘ (a₁, b₁) = (a₂a₁, a₂b₁ + b₂). The rule is associative, so a tree of log₂L levels (3 for 8 tokens) plus a second sweep gives every prefix ht: depth O(log L), work O(L·D·N). A naive version stores the [b, L, D, N] states in DRAM; the fused kernel avoids that (§5).
  2. 2Generation carries one state of shape [b, d_inner, N] per layer and updates it in O(D·N) per token. There is no KV cache, so token 30,000 uses the same memory as token 100.
This dual-mode computation is the key property. Transformers train in parallel but must keep every past token (the KV cache) to generate. Classic RNNs generate cheaply but train sequentially. Linear recurrences (S4, linear attention, Mamba) get both: parallel training over the whole sequence, and constant-memory generation one token at a time. mamba.py implements all three paths (sequential loop, parallel scan, step()) and checks they agree.

3. The Mamba Architecture

Intuition. Take a transformer, delete attention and the separate MLP, and put one gated block in their place whose middle is the selective scan. Then repeat it.

A Mamba language model is just a stack of identical Mamba layers wrapped around token embedding and an LM head. No positional encoding (the causal conv and the recurrence inside each layer see tokens in order), no attention at all, and no separate MLP blocks — the novelty lives entirely inside one layer.

A Mamba language model: one block, repeated Token IDs [b, L] Embedding [b,L,d] Mamba layer × n_layer [b,L,d] RMSNorm LM head Logits [b, L, vocab] 1 2 3
  1. 1Nothing is added between the embedding and the first layer: no positional encoding. The causal conv and the recurrence inside each layer see tokens in order, so position is implicit.
  2. 2Every layer is a residual wrapper, x ← x + MambaBlock(RMSNorm(x)), with the same shape [b, L, d_model] in and out. n_layer = 24 for Mamba-B (≈ mamba-130m) and 48 for Mamba-L (≈ mamba-370m). The block is zoomed in below.
  3. 3A final RMSNorm, then the LM head (d_model → vocab), whose weights are tied to the embedding table.

Two things to notice:

Now zooming in on what happens inside one Mamba layer — specifically the MambaBlock, which is the expand → mix → scan → gate → contract pattern:

Inside one Mamba block: expand, scan, gate, contract x_in RMSNorm in_proj 1 x z conv1d, K=4 SiLU selective scan 2 SiLU 3 out_proj x_out residual
  1. 1Expand. in_proj maps d_model → 2·d_inner (d_inner = 2·d_model) and splits the result into two streams: x (to be mixed over time) and z (the gate).
  2. 2Mix over time. A depthwise causal conv1d (kernel 4, one filter per channel, no channel mixing) adds local context, then SiLU, then the selective scan. Inside the scan, x_proj and dt_proj compute Δ, B, C from each token; A (learned, kept negative) and D are plain parameters. This is the part the hardware-aware CUDA kernel runs (§5).
  3. 3Gate and contract. The scan output y_ssm [b, L, d_inner] is multiplied element-wise by SiLU(z); out_proj maps d_inner → d_model and the residual adds x_in back: x_out = x_in + block(x_in), shape [b, L, d_model].

Component roles

Worked example: parameters of one Mamba-B layer (d = 768, d_inner = 1536, N = 16, dt_rank = 48).

in_proj 768·3072 = 2,359,296 · out_proj 1536·768 = 1,179,648 · x_proj 1536·(48+32) = 122,880

dt_proj 48·1536+1536 = 75,264 · A_log+D 1536·17 = 26,112 · conv 1536·5 = 7,680 · RMSNorm 768

Total 3,771,648 = 6.39·d², and 94% of it is the two big projections. A transformer layer (attention 4d² + MLP 8d²) has about 12·d², which is why Mamba-130M stacks 24 layers where GPT-3 Small (125M) has 12.

4. Scaling: Mamba vs Transformer

Intuition. For every new token, attention re-reads the whole past; Mamba only reads its fixed-size summary. Short inputs cost about the same, long ones do not.

The asymptotic difference is the entire point. Both panels below are computed, not sketched: the left uses compute_flops() from mamba.py for Mamba-130M (24 layers, d = 768) and, for the transformer, 12 layers × (24·L·d² + 2·L²·d) FLOPs (projections and MLP, plus causal QKᵀ and A·V). LM heads are left out of both.

Prefill compute vs length (log–log) 0.1 T1 T10 T100 T1000 T1K4K16K64K256K sequence length L 1 Transformer Mamba
Cache per sequence (FP16) 0 GiB2 GiB4 GiB032K64K96K128K tokens processed so far 1.13 GiB at 32K Transformer KV Mamba state (flat)

What to notice: left, on log–log axes a cost ∝ L is a straight line. Up to a few thousand tokens the two models cost about the same (1.02× at 1K) because the d² terms dominate. The transformer costs ∝ L·d² + L²·d: at 1 L = 12·d ≈ 9.2K its L² attention term equals the rest, and it is 2.6× more expensive at 16K and 27× at 256K. Right, the KV cache grows by 36 KiB per token (1.13 GiB at 32K, 4.5 GiB at 128K) while Mamba's 1.41 MiB state never grows.

Measured speed (Mamba paper, A100, N = 16): the fused selective scan is faster than FlashAttention-2 beyond 2K tokens and up to 7× faster at 32K; generation throughput is 4–5× that of a Transformer of similar size, mainly because without a KV cache it can run much larger batches. At short context the scan's advantage is small, which is why hybrids (§8.3) keep a few attention layers and lose little.

5. Hardware-Aware Kernel (The FlashAttention Trick)

Intuition. Do the messy intermediate work on the chip's small, fast scratchpad and write only the final answer to the big, slow main memory.

The selective scan naively needs an intermediate tensor of shape [b, L, D_inner, N]: for Mamba-B at L = 2048 that is 2048 × 1536 × 16 = 50.3M elements per layer per sequence (201 MB in FP32). Writing it to DRAM and reading it back would make the memory traffic N = 16 times larger than the inputs and outputs themselves.

The official selective_scan_cuda kernel does what FlashAttention did for attention:

Fused selective scan: the big states never leave the chip DRAM (big, slow) Δ, A, B, C, x y SRAM (tiny, fast) load once write once 1. discretize 2. scan → h_t 3. y = C·h backward: recompute h

What to notice: only the inputs (O(b·L·D) values: Δ, A, B, C and x) are read from DRAM, which is HBM on an A100 and LPDDR5 on a Jetson, and only y [b, L, D] is written back. The [b, L, D_inner, N] states exist only in on-chip SRAM and registers, so memory traffic drops by a factor of about N. The backward pass recomputes them instead of storing them.

Same philosophy as FlashAttention: keep the big intermediate on chip and recompute it during the backward pass instead of storing it. The paper reports that this IO reduction makes the scan 20–40× faster than a standard PyTorch scan implementation. Very long sequences are split into chunks that fit in SRAM, carrying the state h from one chunk to the next.

6. Code Walkthrough

The core functions and classes from mamba.py. Click to expand.

7. Complexity Calculator

Try different sequence lengths and model sizes to see the scaling. Defaults to Mamba-B (the shape of state-spaces/mamba-130m). Parameters and FLOPs use the same formulas as count_parameters() and compute_flops() in mamba.py.

The comparison transformer has the same d_model, n_layer/2 layers (one attention + MLP layer has about the parameters of two Mamba blocks) and full multi-head K/V. Decode ceilings assume batch 1 and that every weight, plus the state or KV cache, is read once per token at Jetson Orin Nano Super's 102 GB/s; real decoding is slower.

8. Critical Optimizations

For the general versions of these techniques (KV-cache sizing, quantization, kernel fusion, roofline thinking) see the Memory & inference efficiency cookbook. Below are the Mamba-specific ones.

9. Differences from Transformers and VLMs

AspectTransformerMamba
Core mixerSelf-attention, O(L²·d)Selective scan, O(L·d·N)
Positional infoExplicit (RoPE, ALiBi, learned)Implicit in the causal conv and the recurrence
Training parallelismMatmuls over all positionsMatmuls for projections + parallel scan (log-depth)
Inference memoryKV cache grows O(L) per sequenceFixed state, O(1) in L
Decode cost per tokenGrows with L (reads the whole KV cache)Constant
Best atIn-context learning, exact recallLong sequences on a fixed memory budget
Kernel shapeGEMM-heavyGEMMs (projections) + a custom scan kernel
Parameters per layer~12·d² (attention + MLP)~6.4·d² per Mamba block (expand = 2), so twice as many layers
TokenizationStandard BPESame; byte-level input also studied (MambaByte, 2024)

10. On Edge Hardware

Why Mamba is a good fit for edge inference:

Real talk: if you need a production LLM on Jetson today, a quantized transformer (vLLM, llama.cpp, TensorRT Edge-LLM) is still the default path, with the most mature tooling. Hybrid SSM/attention models are where state-space layers are actually shipping in 2025–26 (Nemotron-H and Nemotron 3, Granite 4.0); check that your inference engine supports the hybrid architecture you pick before planning around it.

11. Connection to the Roadmap Ahead

Where this module's ideas come back:

12. Recap, Self-check & Exercises

Key takeaways

Self-check

Try each question before opening the answer.

1. With A = −1, what are Ā and B̄ (B = 1) for Δ = 0.1 and Δ = 2, and which one "remembers"?

Answer

Δ = 0.1: Ā = e^−0.1 = 0.905, B̄ = 0.1, so the old state is mostly kept and the input barely written. Δ = 2: Ā = e^−2 = 0.135, B̄ = 2, so the old state is mostly forgotten and the input dominates. Small Δ remembers.

2. Why can't Mamba use S4's FFT-convolution training trick, and what replaces it?

Answer

A convolution needs one fixed kernel for all positions, which only exists when (Δ, A, B, C) are the same at every step (time-invariant). Mamba's Δ, B, C change per token, so the kernel changes per position. The recurrence is still linear, hence associative, so a parallel prefix scan computes all h_t in O(log L) depth.

3. Compose two steps (a₁, b₁) = (0.5, 1.0) then (a₂, b₂) = (0.9, 0.2), starting from h = 0. What single (a, b) is equivalent, and what is h₂?

Answer

(a₂·a₁, a₂·b₁ + b₂) = (0.45, 1.1). Applied to h = 0 it gives h₂ = 1.1, the same as running the loop (h₁ = 1.0, h₂ = 0.9·1.0 + 0.2 = 1.1).

4. How large is Mamba-130M's recurrent state per sequence in FP16 (24 layers, d_inner = 1536, N = 16, d_conv = 4)? How large is the KV cache of a 12-layer, d = 768 transformer at 16K tokens?

Answer

24 × 1536 × (16 + 4) × 2 B = 1,474,560 B ≈ 1.41 MiB, for any length. KV: 2 × 12 × 16,384 × 768 × 2 B = 576 MiB, about 410× more.

5. Roughly how many parameters does one Mamba block have for d_model = d and expand = 2, and why does Mamba-130M have 24 layers when GPT-3 Small (125M) has 12?

Answer

in_proj 4d² + out_proj 2d² + small x_proj/dt_proj ≈ 6.4d² (3,771,648 for d = 768). A transformer layer (attention + MLP) is ≈ 12d², so two Mamba blocks match one transformer layer's parameters.

6. For Mamba-B at L = 2048, how big is the naive [L, D_inner, N] intermediate per layer and sequence, and how does the fused kernel avoid writing it?

Answer

2048 × 1536 × 16 = 50.3M values (201 MB in FP32). The kernel loads Δ, A, B, C, x into SRAM, discretizes and scans there, multiplies by C, and writes only y [L, D] back; in the backward pass it recomputes the states.

7. Batch-1 decode on a Jetson Orin Nano Super (102 GB/s): what is the bandwidth ceiling for Mamba-130M in FP16, and for a same-size transformer at 32K tokens of context?

Answer

Mamba: weights 258 MB + state 1.5 MB per token step → 102 / 0.26 ≈ 393 tokens/s at any length. Transformer: ≈ 247 MB of weights + 1.21 GB of KV cache → ≈ 70 tokens/s, and it keeps falling as the context grows.

8. Mamba-2 restricts A to a scalar per head. What does that buy on a GPU?

Answer

With a scalar decay per head, the layer becomes a structured (semiseparable) matrix that can be evaluated chunk by chunk with matrix multiplications, so it runs on Tensor Cores. The paper reports a 2–8× faster layer than Mamba-1's scan, and it allows much larger states (d_state = 128 by default).

9. Why do almost all shipping SSM-based LLMs keep a few attention layers?

Answer

A fixed-size state has to compress the past, so exact recall of an arbitrary earlier token is hard for a pure SSM. A small fraction of attention layers (1 in 8 in Jamba, about 8% in Nemotron-H) restores precise look-up, while the SSM layers keep most of the memory and compute savings.

Hands-on exercises

Build it yourself. Start with the guided lab labs/lab07.html: implement the discretization (simple and zero-order hold), the sequential selective scan, a log-depth parallel scan and the one-token recurrent step; all three scans must agree. Check each step with python labs/check.py 7, then do the exercises below.

All exercises use mamba.py; switch to torch.float64 for exact comparisons (blk.double()).

1. Three scans, one answer (easy)

Run demo_equivalence(), then call selective_scan_reference and selective_scan_parallel directly on random inputs with L = 1, 5 and 37 (not powers of two).

y1 = selective_scan_reference(u, delta, A, B, C, D)
y2 = selective_scan_parallel(u, delta, A, B, C, D)
assert torch.allclose(y1, y2, atol=1e-12)          # float64

2. Make the state memory exact (easy)

Check recurrent_state_bytes() against the tensors step() actually carries, and against the calculator above.

m = mamba_base(); blk = m.layers[0].mixer
h = torch.zeros(1, blk.d_inner, blk.d_state); conv = torch.zeros(1, blk.d_inner, blk.d_conv)
assert recurrent_state_bytes(m) == m.n_layer * (h.numel() + conv.numel()) * 2 == 1_474_560

3. ZOH versus first-order B̄ (medium)

The paper writes B̄ = (ΔA)⁻¹(exp(ΔA) − I)·ΔB; for diagonal A that is (exp(ΔA) − 1)/A · B. Add a zoh=True option to the reference scan, and measure how much the outputs change for Δ drawn like the initialization (0.001 to 0.1) and for Δ = 1.

# the two rules agree to first order: (exp(ΔA) - 1)/A = Δ·(1 + ΔA/2 + ...)
assert rel_diff(y_zoh, y_euler, delta_small) < rel_diff(y_zoh, y_euler, delta_large)

4. Greedy generation with a carried state (medium)

Write generate(model, prompt_ids, n_new) that runs the prompt through every layer's step() (keeping h and conv per layer, plus each layer's residual and RMSNorm), then generates greedily. Compare the logits at each position with one parallel model(ids) call.

assert torch.allclose(logits_stepwise, model(ids), atol=1e-4)   # float32
# memory used by the caches must not change between token 10 and token 1000

5. Time it: where is the crossover? (harder)

On a GPU, time one MambaBlock forward (with selective_scan_parallel) against F.scaled_dot_product_attention(q, k, v, is_causal=True) at the same d for L = 512 … 16K. Then install mamba-ssm and repeat with its fused selective_scan_fn. Plot both; compare with the paper's "faster than FlashAttention-2 beyond 2K".

# correctness before speed: the fused kernel must match the reference
assert torch.allclose(selective_scan_fn(u.transpose(1, 2), ...).transpose(1, 2), y_ref, atol=1e-3)

References

Core papers and code

Hybrids, deployment and applications