State Space Models for Language › Mamba and Input-Dependent Selection

Michael BrenndoerferNovember 17, 20267 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 133State Space Models for Language › Mamba and Input-Dependent Selection
Reading section 7 of 13 · Mamba and Input-Dependent Selection · 7 minSection 7 of 13 · 7 min

Section 7 of 13 · 7 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The fixed S4 kernel gives two inputs at the same lag the same weight before reading their values. An input-conditioned update gives the layer a second way to distinguish them. The Mamba paper motivates this with a selective copying task. The sequence places relevant symbols among distractors with variable spacing, so the location of the information that needs to survive changes from one example to the next.

The Three Projections

In Mamba-1's selective layer, let uk∈RHu_k \in \mathbb{R}^H be the channel vector being processed at position kk. Three learned projections of that vector give a step size for each channel, a write vector, and a read vector. A simplified expression is

Δk=softplus(WΔuk+bΔ),Bk=WBuk,Ck=WCuk.\Delta_k = \mathrm{softplus}(W_\Delta u_k+b_\Delta),\qquad B_k=W_B u_k,\qquad C_k=W_C u_k .

Here Δk∈RH\Delta_k \in \mathbb{R}^H, Bk,Ck∈RNB_k,C_k \in \mathbb{R}^N, and bΔb_\Delta is a learned bias. The projections are shared across positions. Mamba-1 shares the resulting BkB_k and CkC_k vectors across the HH channels. Each channel has its own learned diagonal continuous-time rates in AA, which are shared across positions. The input-dependent step size makes the discrete transition Aˉk\bar A_k vary by position. The reference block implements the step-size projection through a low-rank intermediate. Mamba, Algorithm 2 and section 3.6. Mamba-1 reference block, v2.2.4.

For a negative rate aa in a particular channel, eΔkae^{\Delta_k a} is the multiplier on the previous state. A small positive Δk\Delta_k brings it close to one. A larger Δk\Delta_k makes the multiplier smaller, so less of the old state carries through. The step size also affects the write strength. BkB_k controls which coordinates receive the input, and CkC_k controls which coordinates the readout uses.

The Recurrence

For one channel, write its scalar input as uku_k and its state as xkx_k. The channel index is suppressed in the step size and the transition matrix. After discretization the computation takes the form

xk=Aˉkxk−1+Bˉkuk,yk=Ck⊤xk+Duk.x_k=\bar A_k x_{k-1}+\bar B_k u_k,\qquad y_k=C_k^\top x_k+Du_k .

After computing the coefficients for a given input sequence, the write at position jj contributes Aˉk⋯Aˉj+1(Bˉjuj)\bar A_k\cdots\bar A_{j+1}(\bar B_j u_j) to xkx_k. For a coordinate with continuous rate ana_n, the intervening multipliers are ∏i=j+1keΔian\prod_{i=j+1}^k e^{\Delta_i a_n}. When j=kj=k, the product has no factors and equals one. The readout then takes the dot product of CkC_k with the state. Editing an input can change both its own write and the transition that carries earlier writes forward.

Once those coefficients have been computed, the update is affine in the previous state. The full map from an input sequence to its outputs is generally nonlinear because the coefficients themselves depend on the input. A different input sequence can have a different matrix of lag interactions, so the fixed-kernel convolution from the LTI case gives way to a scan.

The Reference Implementation's Discretization

The Mamba v2.2.4 selective scan reference computes the transition with the same exponential as exact ZOH and uses a first-order approximation for the write. In one channel, for state coordinate nn, the code implements the following recurrence.

xk,n=eΔkanxk−1,n+ΔkBk,nuk.x_{k,n}=e^{\Delta_k a_n}x_{k-1,n}+\Delta_k B_{k,n}u_k .

The exact held-input term uses Bk,n(eΔkan−1)/anB_{k,n}(e^{\Delta_k a_n}-1)/a_n as its coefficient on uku_k for an≠0a_n\ne0. Expanding the exponential around Δk=0\Delta_k=0 gives Δk+12anΔk2+O(Δk3)\Delta_k+\tfrac12a_n\Delta_k^2+O(\Delta_k^3) for the fraction at fixed ana_n. This is why the implementation's Δk\Delta_k coefficient agrees through first order. In a numerical replication, use the discrete update from the code version you intend to match.

The Affine Map and Associative Composition

For scan, represent one update by a pair (Tk,wk)(T_k,w_k), where Tk=AˉkT_k=\bar A_k is the transition and wk=Bˉkukw_k=\bar B_k u_k is the input contribution. The pair acts on a state as x↦Tkx+wkx\mapsto T_k x+w_k. Applying update 11 and then update 22 gives

T2(T1x+w1)+w2=(T2T1)x+(T2w1+w2).T_2(T_1 x+w_1)+w_2=(T_2T_1)x+(T_2w_1+w_2).

The whole segment has the same form as a single update, with transition T2T1T_2T_1 and write term T2w1+w2T_2w_1+w_2. Define composition with the later pair on the left.

(T2,w2)∘(T1,w1)=(T2T1,T2w1+w2).(T_2,w_2)\circ(T_1,w_1)=(T_2T_1,T_2w_1+w_2).

Composition is associative in exact arithmetic since it is just composition of the represented affine maps. It is generally order-sensitive. The identity pair (I,0)(I,0) leaves a state unchanged. A prefix scan can group the compositions in a tree while preserving the order. Applying the resulting pair for each prefix to x−1x_{-1} gives the state at the end of that prefix.

With diagonal transitions, each product of matrices becomes an elementwise product of their diagonals. Each pair composition uses O(N)O(N) arithmetic for one channel. A dense implementation can still use the same pair formula but composes its dense transitions with matrix multiplication.

Work and Depth of a Scan

Keep the state width fixed and count each affine composition as one unit of work. Span counts levels along the longest chain of dependencies. The plot shows the levels used by each schedule, including any wait between phases. The sequential baseline starts from the identity pair and composes one new pair into the running prefix at each position. Under this convention it uses LL compositions in LL levels.

  • Hillis–Steele. In round rr, positions with a predecessor 2r2^r places away combine the two ordered results from the previous round. Round r=0r=0 starts at offset one. Over ⌈log⁡2L⌉\lceil\log_2 L\rceil rounds, work is O(Llog⁡L)O(L\log L) and span is O(log⁡L)O(\log L).
  • Blelloch. An up-sweep combines each adjacent pair of subtrees. A down-sweep distributes the prefix to each position. On a power-of-two input, the exclusive scan schedules the sweeps in order, each with L−1L-1 compositions and log⁡2L\log_2 L levels. An exclusive prefix omits the current update. Composing it with that update yields the inclusive prefix and adds at most LL compositions on one more level. The work stays O(L)O(L) and the span stays O(log⁡L)O(\log L).

For a power-of-two LL, there are L−2rL-2^r Hillis–Steele compositions in round rr, which sum to Llog⁡2L−L+1L\log_2 L-L+1. The plot counts operations and levels in these schedules. Elapsed time also depends on how hardware schedules the work and moves intermediate arrays.

PythonIn [5]
CollapseExpand
scan_lengths = np.array([2**k for k in range(4, 19)], dtype=float)
hillis_steele_levels = np.log2(scan_lengths)
hillis_steele_work = scan_lengths * hillis_steele_levels - scan_lengths + 1
blelloch_levels = 2.0 * hillis_steele_levels
blelloch_work = 2.0 * (scan_lengths - 1)
VisualizationOut [6]
CollapseExpand
Log-log plot of scheduled levels and total compositions. A shared sequential curve shows that its two counts coincide.
Scheduled levels and pair-composition counts on power-of-two inputs. The Blelloch counts show the exclusive scan before forming inclusive prefixes.

One curve shows both sequential counts. The number of scheduled levels grows logarithmically for both parallel scans. Hillis–Steele revisits overlapping prefixes in each round, while Blelloch uses a two-sweep tree and does less work as sequence length grows.

A Teaching Reference and a Fused Kernel

A NumPy loop can implement the recurrence exactly as written and makes a useful reference for checking a faster implementation. Accelerator kernels also need to control which intermediate arrays they write to high-bandwidth memory (HBM).

An implementation that keeps every intermediate state builds an array of shape (B,H,L,N)(B,H,L,N) for batch size BB, channel width HH, sequence length LL, and state dimension NN. At B=1B=1, H=2048H=2048, L=8192L=8192, and N=16N=16, one such float32 array holds 2282^{28} scalars. At four bytes each, it occupies 2302^{30} bytes, or 11 GiB.

Mamba-1's fused design combines discretization, an associative scan, and readout in the same kernel. It works on chunks in fast on-chip memory and carries the scan state across chunk boundaries. The forward implementation can thereby avoid saving the full expanded state array to HBM. Recomputing intermediates in the backward pass reduces the amount that must be saved for differentiation. Compared with an implementation that writes the full state trajectory to HBM, the fused forward pass avoids that write. The backward pass trades some saved intermediates for recomputation. Both evaluate the same recurrence, subject to rounding differences from arithmetic order or precision. Mamba, section 3.3 and Appendix D.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy