Mamba: choose what the state retains
Mamba 与选择性状态空间
Inspect input-dependent state updates and associative scanning, with a version map through Mamba-3 in March 2026.
mambaStart with the problem
A fixed linear state-space layer applies the same memory rule to every token. The original Mamba makes parts of that rule depend on the current input: a token can change how much old state is retained and what new information is written or read.
The family has evolved. This chapter’s runnable calculation isolates the original selective-scan core. It is not an implementation of a complete Mamba block, Mamba-2 or Mamba-3. The later versions are mapped explicitly below so a 2023 mechanism is not mistaken for the state of the family at the encyclopedia’s 2026-09-04 cutoff.
Definitions and derivation
For two diagonal state coordinates, use a negative fixed A and input-dependent Δ, B and C. Our small real-valued recurrence is:
All operations on a and h are coordinatewise. The code sets Bₜ=(1,0.5+0.1uₜ), Cₜ=(1,−0.25uₜ) and D=0.1. Positive softplus steps make the chosen negative-A retention factors lie between zero and one. A larger step reduces old-state retention while also changing the injected term; this is not a guarantee that the hand-chosen rule recognizes useful semantics.
The input term ΔBu follows the v2.2.2 reference scan. It is not the exact zero-order-hold input integral derived in state-space models. The original paper’s discretization notation and this implemented convention must be distinguished.
Once the input has fixed every pair (aₜ,bₜ), each state step is an affine map. Composition gives:
The order matters: the later map multiplies the earlier injected state before adding its own. Composition is associative, which permits a tree of prefix compositions:
Associativity is an exact-arithmetic statement; a different floating-point reduction order can give small rounding differences. The coefficients must be available without knowing the evolving state. If they depended on hₜ₋₁ in an arbitrary nonlinear way, this precomputed affine scan would not apply.
Input dependence breaks the single fixed-convolution description. Our program directly checks nonadditivity by comparing outputs for two input sequences and their sum. Conditional on precomputed coefficients the state update is affine, but the overall map from inputs to outputs is nonlinear.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program computes the same eight-token state history with sequential recurrence and a balanced prefix tree. It pads the tree with identity maps and counts affine compositions. The tree is evaluated serially on the CPU; this is not a GPU throughput test.
import numpy as np
def coefficients(inputs):
u = np.asarray(inputs,dtype=float)
if u.ndim != 1 or not 1 <= len(u) <= 64 or not np.isfinite(u).all() or np.any(np.abs(u)>10):
raise ValueError('Use 1 to 64 finite inputs with magnitude at most 10.')
delta = np.logaddexp(0,u)
a = np.exp(delta[:,None]*np.array([-1.,-2.]))
b = delta[:,None]*np.column_stack((np.ones(len(u)),.5+.1*u))*u[:,None]
c = np.column_stack((np.ones(len(u)),-.25*u))
return a,b,c
def compose(earlier,later):
a,b = earlier; c,d = later
return c*a,c*b+d
def prefix_states(a,b,initial):
length = len(a); size = 1 << (length-1).bit_length()
identity = (np.ones(2),np.zeros(2)); tree = [identity for _ in range(2*size)]; calls = 0
for i in range(length):tree[size+i] = (a[i],b[i])
for i in range(size-1,0,-1):tree[i] = compose(tree[2*i],tree[2*i+1]); calls += 1
output = np.zeros((length,2))
def descend(node,prefix):
nonlocal calls
if node >= size:
i = node-size
if i < length:
aa,bb = compose(prefix,tree[node]); calls += 1; output[i] = aa*initial+bb
return
descend(2*node,prefix)
right_prefix = compose(prefix,tree[2*node]); calls += 1
descend(2*node+1,right_prefix)
descend(1,identity)
return output,calls
def selective_scan(inputs,initial=None):
u = np.asarray(inputs,dtype=float); a,b,c = coefficients(u)
h = np.zeros(2) if initial is None else np.asarray(initial,dtype=float)
if h.shape != (2,) or not np.isfinite(h).all():raise ValueError('Use a finite two-coordinate initial state.')
states = []
for aa,bb in zip(a,b):
h = aa*h+bb; states.append(h.copy())
states = np.array(states)
return np.sum(c*states,axis=1)+.1*u,states,(a,b,c)
if __name__ == '__main__':
u = np.array([1.,0,2,-1,0,.5,0,1]); y,states,(a,b,c) = selective_scan(u)
tree,calls = prefix_states(a,b,np.zeros(2))
print('output',y.round(9).tolist(),'tree / sequential state discrepancy',float(np.max(np.abs(tree-states))))
print('affine compositions',calls,'for',len(u),'tokens; tree is evaluated serially on CPU')
first = np.array([1.,0,0,0]); second = np.array([0.,1,0,0])
discrepancy = selective_scan(first+second)[0]-selective_scan(first)[0]-selective_scan(second)[0]
print('superposition discrepancy',discrepancy.round(9).tolist())
print('zero-input state retention',selective_scan([0,0,0],[1,-1])[1].tolist())
Actual output:
output [1.216272434, 0.656630844, 3.041879186, 3.120681058, 1.426888949, 1.035726046, 0.51287355, 1.352758025] tree / sequential state discrepancy 2.220446049250313e-16
affine compositions 22 for 8 tokens; tree is evaluated serially on CPU
superposition discrepancy [0.0, -0.317688511, -0.151720189, -0.075860095]
zero-input state retention [[0.5, -0.25], [0.25, -0.0625], [0.125, -0.015625]]
The state histories differ by about 2.2×10⁻¹⁶. Eight tokens require 22 affine compositions in this tree implementation. The superposition discrepancy is nonzero, ruling out one input-independent linear convolution kernel for this example. With zero inputs and initial state (1,−1), the two coordinates decay by one half and one quarter per step.
A diagonal N-state sequential scan costs O(TN) for T tokens. A work-efficient prefix tree also uses O(TN) arithmetic with O(log T) potential parallel depth, but our reference stores the whole state history for checking. Streaming inference can retain only the current state. The paper’s fused implementation manages expanded-state memory and hardware traffic; those properties are not reproduced by this Python tree.
When the method fails
A full initial-generation Mamba block also contains projections, local causal processing and output gating. Its task performance comes from trained parameters and the surrounding architecture, not merely from the associative law. Bounded state size is not unlimited exact recall, and linear asymptotic work is not a device-independent speed guarantee.
The version map matters. Mamba-2, published at ICML 2024, develops structured state-space duality between SSMs and variants of attention, and reorganizes the selective core for more efficient computation. Mamba-3’s first arXiv version, submitted 2026-03-16, introduces exponential-trapezoidal discretization, complex-valued state updates and a multi-input/multi-output formulation. Its paper also clarifies the earlier discretization convention. These are substantive changes, not just larger copies of the toy scan.
The later papers report performance under their own model scales, hardware and tasks. This chapter does not rerun those experiments, implement their full blocks or infer a universal ranking against Transformers. Its numerical guarantees concern only the explicitly defined recurrence and scan.
Exercises with answers
- Why is a larger Δ associated with less retained state for A<0?
Answer 1: exp(ΔA) decreases as Δ increases. The input injection changes too, so output behavior is not determined by retention alone.
- May affine maps be reordered because composition is associative?
Answer 2: No. Associativity changes parenthesization, not temporal order.
- What does the nonzero superposition discrepancy show?
Answer 3: The whole input-to-output rule is not linear, so one fixed linear convolution cannot represent it.
- Does this CPU prefix tree implement Mamba-3?
Answer 4: No. It checks an original-style selective core. Mamba-3 adds different discretization, complex state and MIMO mechanisms.
Sources and next steps
The original paper’s physical pages 3 and 6 distinguish fixed SSMs from input-selected Δ/B/C. The official versioned reference supplies the exponential transition and ΔBu input convention. Mamba-2’s primary publication and Mamba-3’s dated v1 establish the later family milestones. All coefficients, prefix-tree code and counterexamples here are original; no upstream kernels or paper figures are redistributed.
Make a prediction, then check
Why can the precomputed selective recurrence use a prefix tree?
Learning objectives
- Derive affine scan composition without changing temporal order.
- Distinguish original-core computations from later Mamba family changes.
Prerequisites & connections
Explore related knowledge →References
- Mamba: Linear-Time Sequence Modeling with Selective State Spaces — arXiv v1
Albert Gu; Tri Dao · 2023 - selective_scan_ref — Mamba v2.2.2
Mamba contributors - Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality
Tri Dao; Albert Gu · 2024 - Mamba-3: Improved Sequence Modeling using State Space Principles — arXiv v1
Aakash Lahoti; Kevin Y. Li; Berlin Chen; Caitlin Wang; Aviv Bick; J. Zico Kolter; Tri Dao; Albert Gu · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Bilingual SVGs generated with Matplotlib 3.9.1 from executed article functions: input-dependent state retention, regular-graph collisions and static/dynamic attention score rankings. Figures and samples are hash-bound. Parameters are illustrative, graph IDs are not features, and scores are not probabilities.
Source locations checked:
- Mamba: Linear-Time Sequence Modeling with Selective State Spaces — arXiv v1 · Physical pages 3 and 6, Equations 1–4 and Algorithms 1–2: fixed versus input-dependent state parameters and selective scan.
- selective_scan_ref — Mamba v2.2.2 · Fixed v2.2.2 selective_scan_interface.py lines 91–157: delta softplus, exponential deltaA, deltaB_u, recurrence, readout and optional skip/gate.
- Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality · PMLR 235 official page and linked PDF physical page 1: 2024 authors/publication, structured state-space duality and Mamba-2 refinement; no benchmark reproduction.
- Mamba-3: Improved Sequence Modeling using State Space Principles — arXiv v1 · arXiv v1 history confirms 2026-03-16; PDF physical pages 1–2 and 4: exponential-trapezoidal, complex-state and MIMO contributions, earlier discretization caveat.
Related topics