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.
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.
🎥 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.
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 Cfunctions 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.)
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:
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)
Parameters
A, B, C, Δ fixed: the same across the whole sequence
Δt, Bt, Ct = f(xt), data-dependent; A a learned constant
Strengths
Time-invariant ⇒ the layer is one long convolution (FFT); handles very long sequences
Learns when to "remember" vs "forget"; Mamba-3B matches Transformers twice its size (paper)
Weaknesses
Same dynamics for every token, no input-dependent gating; worse than transformers on language
Time-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
–
Ā_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:
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.
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).
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.
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.
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.
3A final RMSNorm, then the LM head (d_model → vocab), whose weights are tied to the embedding table.
Two things to notice:
Shape is preserved through every layer: [b, L, d_model] in, [b, L, d_model] out. No downsampling, no upsampling, no cross-attention to another stream. Just n_layer layers of the same thing, stacked.
No positional encoding is added anywhere in the pipeline. The MambaBlock's recurrence (inside each layer) builds position information into the state as it walks left-to-right through the sequence. A transformer needs RoPE or learned positional embeddings; Mamba gets positions for free.
Now zooming in on what happens inside one Mamba layer — specifically the MambaBlock, which is the expand → mix → scan → gate → contract pattern:
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).
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).
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
in_proj: expands dimensionality and creates two streams. Standard Linear.
conv1d (depthwise): small K=4 filter across time. Adds local context that the scan alone doesn't capture well. Depthwise = per-channel, no channel mixing (that's in_proj's job).
Selective scan: the heart. Computes N-dim state updates for every (batch, position, channel). The ONE operation unique to Mamba. x_proj produces Δ (through a low-rank dt_rank = ⌈d/16⌉ bottleneck and dt_proj), B and C from each token; A and D are plain learned parameters.
z gate: SiLU(z) × scan_output — elementwise multiplicative gating. Lets the model modulate what passes through.
out_proj: contracts back to d_model. Standard Linear.
Worked example: parameters of one Mamba-B layer (d = 768, d_inner = 1536, N = 16, dt_rank = 48).
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.
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:
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.
selective_scan_reference — the core operation (sequential)▼
Purpose: Run the selective SSM recurrence. This Python version loops over time steps for clarity; the real implementation is a hardware-aware CUDA kernel.
defselective_scan_reference(u, delta, A, B, C, D_skip):
B_size, L, D_size = u.shape
N = A.shape[-1]
# Discretize: dA = exp(delta · A) (zero-order hold), dB = delta · B (first-order,# as in the official kernel). Input-dependent because delta, B, C come from x.
deltaA = torch.exp(delta.unsqueeze(-1) * A) # [b, L, D, N]
deltaB_u = delta.unsqueeze(-1) * B.unsqueeze(2) * u.unsqueeze(-1) # [b, L, D, N]
h = torch.zeros(B_size, D_size, N, device=u.device, dtype=u.dtype)
ys = []
for t inrange(L):
h = deltaA[:, t] * h + deltaB_u[:, t] # [b, D, N]
y_t = torch.einsum("bdn,bn->bd", h, C[:, t]) # [b, D]
ys.append(y_t)
y = torch.stack(ys, dim=1) # [b, L, D]return y + u * D_skip # per-channel skip
Key insight: the loop over t is what makes this O(L) work but also L sequential steps. Because one step is the affine map h ← a·h + b, applying step 1 then step 2 gives (a₂, b₂) ∘ (a₁, b₁) = (a₂·a₁, a₂·b₁ + b₂), which is associative, so the loop can be replaced by a parallel scan (next panel). The paper writes the zero-order-hold rule for B̄ too, (ΔA)⁻¹(exp(ΔA) − I)·ΔB; the official code uses Δ·B, which agrees to first order in Δ (exercise 3).
selective_scan_parallel — the same scan in log₂L parallel rounds▼
Purpose: Show that the recurrence really can be computed without a loop over time. Each step is an affine map h ← a_t·h + b_t. Doing step 1 then step 2 is again an affine map: (a₂, b₂) ∘ (a₁, b₁) = (a₂·a₁, a₂·b₁ + b₂). Because this combine is associative, every prefix can be built in ⌈log₂L⌉ rounds where each position combines with the one offset places back (Hillis–Steele scan).
defselective_scan_parallel(u, delta, A, B, C, D_skip):
a = torch.exp(delta.unsqueeze(-1) * A) # [b, L, D, N]
b = delta.unsqueeze(-1) * B.unsqueeze(2) * u.unsqueeze(-1) # [b, L, D, N]
offset = 1while offset < L:
# combine with the element `offset` back; identity (1, 0) before the start
a_prev = torch.cat([torch.ones_like(a[:, :offset]), a[:, :-offset]], dim=1)
b_prev = torch.cat([torch.zeros_like(b[:, :offset]), b[:, :-offset]], dim=1)
b = a * b_prev + b # uses the OLD a: order matters
a = a * a_prev
offset *= 2
y = torch.einsum("bldn,bln->bld", b, C) # b now holds every h_treturn y + u * D_skip
Tiny check by hand (L = 2). Steps (a₁, b₁) = (0.5, 1.0) and (a₂, b₂) = (0.9, 0.2), starting from h₀ = 0. Loop: h₁ = 0.5·0 + 1.0 = 1.0, h₂ = 0.9·1.0 + 0.2 = 1.1. Scan: one round with offset 1 gives b₂ ← a₂·b₁ + b₂ = 0.9·1.0 + 0.2 = 1.1. Same answer, but every position is updated at once.
python mamba.py runs demo_equivalence(): in float64 the parallel scan, the sequential loop and the token-by-token step() agree to about 1e-16. Hillis–Steele does O(L log L) work; Blelloch's two-sweep version is O(L), and the CUDA kernel uses a work-efficient scan in SRAM.
MambaBlock — the expand-scan-gate-contract cell▼
Purpose: One complete Mamba layer. In-projection doubles dimensionality into (x_ssm, z), runs conv + SSM on x_ssm, gates with SiLU(z), contracts back.
classMambaBlock(nn.Module):
def__init__(self, d_model, d_state=16, d_conv=4, expand=2):
super().__init__()
self.d_inner = expand * d_model
self.d_state, self.d_conv = d_state, d_conv
self.in_proj = nn.Linear(d_model, 2 * self.d_inner, bias=False)
# Depthwise 1D conv for local mixing before the SSM
self.conv1d = nn.Conv1d(
self.d_inner, self.d_inner,
kernel_size=d_conv,
groups=self.d_inner, # depthwise — no cross-channel mix
padding=d_conv - 1,
)
# x_proj produces Δ_rank, B [N], C [N] — ALL data-dependent
self.dt_rank = math.ceil(d_model / 16)
self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * d_state, bias=False)
self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True)
# A is parameterized as log|A| so A = -exp(A_log) is always negative# Negative A ensures the recurrence decays (stable).
self.A_log = nn.Parameter(torch.log(torch.arange(1, d_state + 1, dtype=torch.float32).repeat(self.d_inner, 1)))
self.D = nn.Parameter(torch.ones(self.d_inner))
self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)
# (mamba.py also initializes dt_proj's bias so softplus(bias) starts in [0.001, 0.1])defforward(self, x):
L = x.shape[1]
xz = self.in_proj(x) # [b, L, 2·d_inner]
x_ssm, z = xz.chunk(2, dim=-1) # each [b, L, d_inner]# Depthwise conv + SiLU
x_ssm = self.conv1d(x_ssm.transpose(1, 2))[..., :L].transpose(1, 2)
x_ssm = F.silu(x_ssm)
# Data-dependent Δ, B, C
x_dbl = self.x_proj(x_ssm)
dt, B, C = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1)
delta = F.softplus(self.dt_proj(dt))
A = -torch.exp(self.A_log.float()) # [d_inner, d_state]# The scan — the only operation unique to Mamba
y = selective_scan_reference(x_ssm, delta, A, B, C, self.D)
# Gate + contractreturn self.out_proj(y * F.silu(z))
Deployment note: The in_proj, out_proj, and conv layers are standard. Only selective_scan_reference needs replacing with the CUDA kernel at inference time.
MambaBlock.step — recurrent inference mode▼
Purpose: Process one token at a time, carry a fixed-size state. This is the mode used in autoregressive generation. Memory is d_inner · (d_state + d_conv) values per layer per sequence — constant in sequence length.
defstep(self, x_t, h, conv_cache):
# x_t: [b, d_model] — ONE token# h: [b, d_inner, d_state] — carried state# conv_cache: [b, d_inner, d_conv] — last d_conv inputs for the depthwise conv
xz = self.in_proj(x_t)
x_ssm, z = xz.chunk(2, dim=-1)
# Conv is a dot product across kernel positions now (no sequence loop)
conv_cache = torch.roll(conv_cache, shifts=-1, dims=-1)
conv_cache[..., -1] = x_ssm
x_ssm = torch.einsum("bdk,dk->bd", conv_cache, self.conv1d.weight.squeeze(1))
x_ssm = F.silu(x_ssm + self.conv1d.bias)
# Δ, B, C for this single token
x_dbl = self.x_proj(x_ssm)
dt, B, C = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1)
delta = F.softplus(self.dt_proj(dt))
A = -torch.exp(self.A_log.float())
dA = torch.exp(delta.unsqueeze(-1) * A) # [b, d_inner, d_state]
dB = delta.unsqueeze(-1) * B.unsqueeze(1) # [b, d_inner, d_state]# Update state — O(d_inner · d_state) compute, same for every token
h = dA * h + dB * x_ssm.unsqueeze(-1)
y = torch.einsum("bdn,bn->bd", h, C) + self.D * x_ssm
y = y * F.silu(z)
return self.out_proj(y), h, conv_cache
Key point: the per-token cost is fully independent of L. A transformer at L=100,000 does an attention over 100,000 cached K/V pairs per token. Mamba just updates a small state tensor. This is the headline performance story for long-context inference.
Mamba (full model) — stack of MambaLayers▼
Purpose: Wrap token embedding, n_layer Mamba layers (each with residual + RMSNorm), final norm, and LM head. Almost identical to a transformer's top-level structure — only the mixer changes.
classMamba(nn.Module):
def__init__(self, vocab_size, d_model=768, n_layer=24, ...):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.layers = nn.ModuleList([
MambaLayer(d_model, ...) for _ inrange(n_layer)
])
self.norm_f = RMSNorm(d_model)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
self.lm_head.weight = self.embedding.weight # tied weightsdefforward(self, token_ids):
x = self.embedding(token_ids)
for layer in self.layers:
x = layer(x) # residual inside
x = self.norm_f(x)
return self.lm_head(x)
What's notably absent: no positional encoding. The causal conv and the scan both process tokens left-to-right, so order is built in. (The official model also keeps the residual stream in FP32 and fuses add + norm; that does not change the math.)
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.
8.1 The hardware-aware selective scan kernel▼
Without a fused kernel, Mamba is impractically slow: the Python loop in mamba.py is for reading, not for running. The official kernel:
Fuses discretize + scan + output into one CUDA kernel.
Keeps the [b, L, D_inner, N] states in SRAM, never in DRAM (IO drops by a factor of about N).
Uses a work-efficient parallel scan on chip, and splits very long sequences into chunks that carry the state across.
Recomputes the states during the backward pass instead of storing them (like activation checkpointing).
Paper numbers (A100): 20–40× faster than a standard PyTorch scan, faster than FlashAttention-2 beyond 2K tokens. Installed via pip install mamba-ssm; source at github.com/state-spaces/mamba.
8.2 Mamba-2 (SSD) and Mamba-3▼
Mamba-2 (Dao & Gu, 2024) connects SSMs and attention through "Structured State-Space Duality" (SSD). The practical wins:
A is restricted to a scalar times the identity per head (instead of a diagonal), which makes the layer a structured matrix that can be computed in chunks with matrix multiplications, so it runs on Tensor Cores.
The paper reports the SSD layer is 2–8× faster than Mamba-1's selective scan.
It supports much larger states with little slowdown: mamba_ssm's Mamba2 defaults to d_state = 128 with head dimension 64 (Mamba-1: 16).
Most 2025–26 hybrid LLMs that use SSM layers use Mamba-2 (8.3). Mamba-3 (Lahoti et al., 2026) goes further with a more expressive discretization, a complex-valued state update and a multi-input multi-output (MIMO) form designed to use more FLOPs per decode step without more latency; at 1.5B scale it reports +0.6 points average downstream accuracy over Gated DeltaNet (+1.8 for the MIMO variant), and Mamba-2-level perplexity with half the state size.
8.3 Hybrid models — SSM layers plus a few attention layers (as of Oct 2026)▼
A fixed-size state must compress the past, so pure SSMs are weaker at exact recall from long contexts, where attention can look up any earlier token. The common answer is a hybrid: mostly SSM (or linear-attention) layers, with a minority of full-attention layers. Open models built this way:
Linear attention rather than Mamba, same hybrid idea; 80B total / 3B active
Deployment implication: the serving stack must manage two kinds of per-request memory, a growing KV cache for the attention layers and a fixed state (SSM state + conv window) for the others. vLLM, for example, added a hybrid cache manager that sizes both so they can share paged GPU memory. Note how many of these models are also Mixture-of-Experts, the topic of the next module.
8.4 No KV cache, but the state still needs to be managed▼
While there's no KV cache, each request still needs its SSM state [d_inner, d_state] and conv window [d_inner, d_conv] in every layer:
Mamba-B, per layer: 1536 × 16 = 24,576 state values + 1536 × 4 = 6,144 conv values = 60 KiB in FP16.
× 24 layers = 1.41 MiB per request, whatever the context length.
A transformer of about the same size (12 layers, d = 768) at L = 16K: 2 × 12 × 16,384 × 768 × 2 B = 576 MiB, 410× more.
This is what makes Mamba attractive for serving many concurrent long-context requests: you can pack far more of them into the same GPU memory, and that larger batch is where the paper's 4–5× throughput gain comes from. One catch: prefix caching is harder, because you can only resume from states you saved, not from an arbitrary earlier token.
8.5 Quantization — the projections are easy, the scan is sensitive▼
The Linear layers (in_proj, out_proj, x_proj) are ordinary GEMMs and hold almost all the weights, so standard weight quantization applies to them. The selective scan is more delicate: errors can compound through the recurrence, and the scan's inputs and outputs have large activation outliers. Quamba (2024), a post-training recipe for 8-bit weights and activations, handles this by clipping the scan input for finer quantization and applying a Hadamard transform to the outputs; on Mamba 2.8B it reports 1.72× lower generation latency on a Jetson Orin Nano 8G with a 0.9% drop in average zero-shot accuracy.
Weights: the projections dominate the bytes; quantize them first.
Scan inputs/outputs and state h: keep higher precision unless you use an SSM-specific recipe like Quamba.
A (stored as log|A|), D, Δ bias: tiny; the official code keeps A in FP32 (A_log.float()) even when the model runs in FP16.
9. Differences from Transformers and VLMs
Aspect
Transformer
Mamba
Core mixer
Self-attention, O(L²·d)
Selective scan, O(L·d·N)
Positional info
Explicit (RoPE, ALiBi, learned)
Implicit in the causal conv and the recurrence
Training parallelism
Matmuls over all positions
Matmuls for projections + parallel scan (log-depth)
Inference memory
KV cache grows O(L) per sequence
Fixed state, O(1) in L
Decode cost per token
Grows with L (reads the whole KV cache)
Constant
Best at
In-context learning, exact recall
Long sequences on a fixed memory budget
Kernel shape
GEMM-heavy
GEMMs (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
Tokenization
Standard BPE
Same; byte-level input also studied (MambaByte, 2024)
10. On Edge Hardware
Why Mamba is a good fit for edge inference:
No KV cache blow-up. On an 8 GB Orin Nano, a 1.41 MiB state per sequence leaves the memory for weights and batch; a same-size transformer's KV cache would need 4.5 GiB at 128K tokens.
Constant per-token cost. Decode at batch 1 is bandwidth-bound for both; Mamba reads its weights plus a tiny state, a transformer its weights plus a KV cache that grows every token. For Mamba-130M in FP16 at 102 GB/s the ceiling is ≈ 393 tokens/s at any length; the same-size transformer falls to ≈ 70 tokens/s at 32K (calculator above).
The scan kernel is the risk factor. The official mamba_ssm build compiles for sm_87 (Jetson Orin) among other architectures when you build from source; check your JetPack/CUDA/PyTorch combination before committing. Quamba's Orin Nano results show 8-bit SSM inference on Jetson is feasible.
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:
Mixture-of-Experts LLMs (Module 6): Jamba, Granite 4.0, Nemotron 3 and Qwen3-Next combine linear-time mixers with MoE feed-forward layers. MoE cuts FLOPs per token; SSM layers cut cache memory. They solve different problems and stack well.
VLA models (Module 8): robot policies run in closed loop over long horizons, so a fixed-size state is attractive. RoboMamba (2024), for example, builds a VLA on a Mamba language model.
World models and robot foundation models (Modules 8–9): latent dynamics over long trajectories are naturally recurrent; the dual parallel/recurrent view from §2 is the same trade-off in a different setting.
12. Recap, Self-check & Exercises
Key takeaways
Mamba's mixer is a linear recurrence per channel: h_t = Ā_t ⊙ h_{t−1} + B̄_t·x_t, y_t = C_t·h_t + D·x_t, with Ā_t = exp(Δ_t·A) and B̄_t = Δ_t·B_t.
"Selective" = Δ, B, C are computed from the current token. Large Δ overwrites the state, small Δ keeps it; fixed (LTI) SSMs like S4 cannot make that choice per token.
Selectivity breaks S4's convolution trick, but the recurrence is still associative, so training uses a parallel scan; generation uses the same math one token at a time.
The fused kernel keeps the [b, L, D, N] states on chip and recomputes them in backward: the FlashAttention idea applied to a scan.
Memory is the headline: Mamba-130M carries 1.41 MiB of state per sequence at any length, while a same-size transformer's KV cache grows 36 KiB per token (1.13 GiB at 32K).
Compute is linear in L; a same-size transformer catches up only when L²·d terms dominate (L ≳ 12·d ≈ 9K for d = 768).
In 2025–26 SSM layers ship mostly inside hybrids (Mamba-2 + a few attention layers, often with MoE): Nemotron-H / Nemotron 3, Granite 4.0, Jamba.
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).
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)