State Space Models for Language
Learn how state space layers replace growing key-value caches with fixed recurrent state. Covers discretization, S4, Mamba, and SSD.
Language AI HandbookAll chapters State Space Models for Language
When you generate the next token after a long document, a full causal attention layer can compare its query with the keys at every processed position. The layer keeps separate key and value vectors for those positions, so both the cache and the work to read from it grow with the prefix. At 100,000 positions, the same cache calculation that was cheap for a short prompt can dominate a memory budget.
A state space layer keeps a fixed-size state per sequence. Each new input updates that state, and a readout produces the layer's output. With the layer sizes and batch size fixed, the amount of recurrent state and the number of arithmetic operations for one recurrent update are independent of how many positions came before. A layer that needs to recall an old detail must recover it from the state its updates have retained. This chapter derives the update, computes a fixed system in two equivalent ways, then uses a small experiment to show how the history can fade when the update retains only a fraction of the previous state.
Two Memory Systems
Efficient Attention introduced methods for evaluating attention more cheaply. Here we compare one conventional full causal attention layer to a recurrent state space layer.
For one attention head, let be the query at position . The cache holds the matching keys and values for already processed positions. A causal attention output is , with . For a completed prefix of length , the cache of this head uses scalars. With equal key and value widths , that becomes .
A scalar-input state space layer updates from and its input at position . It reads an output from the resulting state. With parallel channels of this type, the recurrent state uses scalars per sequence.
An attention query can assign different weights to two occurrences of a name if their keys give it different scores. A recurrent state can track a statistic such as how often a specified name appears. That count alone cannot tell you where a particular occurrence appeared.
The recurrence introduces another practical question. Evaluating one update at a time creates a dependency chain of length . When the transition, write, readout, and direct-path coefficients are fixed and the initial state is zero, the layer's input contribution can be evaluated as a causal convolution. The rest of this chapter develops that equivalence and shows what to compute when the weights vary with the input.
The Continuous-Time State Space Model
Consider a system driven by a scalar signal . At continuous time , the state is a vector of coordinates. A differential equation describes the change of that vector, and a readout produces a scalar output .
- describes the dynamics of the state in the absence of input.
- distributes the scalar input over the state coordinates.
- takes a weighted sum of the state.
- scales the direct path from input to output.
With a diagonal , each coordinate moves independently in response to the same scalar input. If a coordinate has rate , its value in the absence of input changes by a factor of after time . Rates closer to zero decay more slowly. The write and readout vectors determine how strongly each mode participates in the input and output. More general state matrices can also mix state coordinates. Many deep sequence models build a vector-valued layer by applying scalar-input state space computations along several channels and using learned projections to mix channels around them. This development starts from the continuous state equation used by Gu, Goel, and Ré, sections 2 and 3.4.
Why Linearity Matters
The state equation is linear jointly in and . If the initial state is zero, the output due to a sum of input signals is the sum of the outputs due to the individual signals. You can therefore study how the system responds to individual impulses and add those responses together. When the coefficients stay fixed, an impulse at a later time produces a shifted copy of the same response. Together, those two properties give the convolution representation.
A standard recurrent neural network can apply a nonlinearity inside its update from the previous state. That generally invalidates superposition. State space networks can retain a linear state operator and introduce nonlinear operations around it, such as a gate computed from the layer input. We will use that distinction to understand what Mamba can parallelize.
What "Linear Time Invariant" Means
A linear time-invariant (LTI) state space layer uses the same matrices at every position, and its zero-state response is linear in the input. The contribution from an impulse then depends on the lag since it arrived. For a fixed input coordinate and output coordinate, the layer applies that same lag-dependent rule to each signal value it sees.
Discretization with a Zero-Order Hold
A sequence gives one input per position. Choose a step size and hold over . This is a zero-order hold (ZOH). Name the state at the start of the interval and the state at its end , so input updates initial state . We read out by combining the endpoint state with the held input before the next input replaces it. Integrating the linear equation across the interval gives
The first term propagates the initial state. The integrand propagates the contribution made at each instant for the remaining time . Reversing the integration variable and pulling the constant input outside the integral gives the recurrence below.
With our endpoint convention, the output is . The step changes the transition and the write map. The readout and direct path already act on instantaneous values.
For invertible , the integral equals . The integral itself works for singular matrices too. To see why, integrate the matrix exponential's power series term by term.
The factorial in the denominator gives convergence for any finite square matrix. For , the only nonzero term is , so each step adds .
A Diagonal Example You Can Compute by Hand
Take and a single stable rate . The continuous system is . Then
Since and , the factor is negative, so . The discrete system is a geometric decay. Two sanity checks are worth doing.
First, as the fraction tends to , so . With a zero rate, the state simply accumulates the input. Mamba's reference implementation also uses , as a first-order approximation to the write at finite rates.
Second, the continuous half-life is in units of time. The discrete half-life in units of steps is
For a single mode, sets the half-life in step units. This scale can be fractional. The first whole update at which the magnitude is at or below half its starting value is .
When the rate stays fixed, increasing the step size makes one update cover more continuous time. The contribution decays more in each step. Later we will let the input determine the step size separately at each position.
PythonIn [3]Expand
import numpy as np
rate_grid = -np.logspace(np.log10(0.01), np.log10(4.0), 240) # a in [-4, -0.01]
step_grid = np.logspace(
np.log10(0.01), np.log10(2.0), 240
) # Delta in [0.01, 2]
persistence = np.exp(
np.multiply.outer(step_grid, rate_grid)
) # shape (step, rate)
halflife_steps = np.log(2.0) / np.multiply.outer(step_grid, -rate_grid)We now have a grid of over a range of continuous rates and step sizes. The map below makes the joint dependence visible.
VisualizationOut [4]Expand

A point near the upper left combines a large step with a strongly negative rate. Little of the previous state survives that step. As you move toward the lower right, the rate and the step produce a multiplier closer to one. The contour lines pick out combinations with the same half-life.
Linear Time Invariance and the Convolution View
Now set the initial state to zero, , and unroll the recurrence for a few steps to see the pattern.
At each step the state receives another input and propagates every earlier contribution through one more application of the transition. An input from therefore passes through transitions by position . The general form is
Apply the readout to that state.
Define the state-mediated impulse response taps
With zero initial state, a unit input at position zero produces the state-mediated response at lag . An input of amplitude at position contributes to the state-mediated output at position . Summing these scaled, shifted responses gives the causal convolution. The direct path adds .
Three things are doing work here.
Zero initial state. For , add to the convolution output at position . This term propagates the existing state over the same updates.
Causal truncation. The sum at includes only lags through . For the first outputs, it is exact to build a length- kernel and retain the first entries of the full linear convolution. Later taps would apply only at later outputs.
The direct path. The direct contribution changes the lag-zero tap to . The later taps stay at . The example below folds the direct path into the lag-zero tap.
For a known sequence, the convolution can evaluate the outputs together. During autoregressive decoding, an implementation can use the recurrence to update its last state as each new input arrives. For a diagonal transition, updating and reading a state of width uses arithmetic per channel.
The equality between convolution and recurrence holds in exact arithmetic. A numerical comparison needs a tolerance because the two evaluation orders accumulate rounding differently.
Building the Kernel and Applying It
Building a length- kernel and applying it are separate computations.
- Build the taps. In a diagonal system of state size , you can start with and multiply elementwise by the diagonal of for each lag. A dot product with gives each tap. That uses arithmetic for one channel.
- Apply the kernel. Direct convolution over the causal pairs takes arithmetic per channel. FFT convolution with padding for a linear convolution takes for that length. Keep the first outputs for the causal readout.
S4 builds its kernel by evaluating the finite generating function at the roots of unity and transforming those evaluations back to coefficients. For a complex evaluation point , the finite sum is
When is invertible, summing the matrix geometric series gives
At the roots of unity the last factor is . This factor preserves the exact finite kernel, including modes that still carry substantial weight at lag . It can be merged into the readout because it commutes with . This leaves an expression that a structured matrix algorithm can compute across the evaluation points. See S4, section 3.2 and Appendix C.
S4 and Structured State Matrices
The Structured State Space model (S4) makes long convolution kernels practical to compute from a recurrent state space representation. The revised paper reports 86.09% average accuracy for the updated S4 model across its Long Range Arena suite, including 96.35% on Path-X. Those are sequence benchmark results from the evaluated model and tasks. Gu, Goel, and Ré, Table 2 and Appendix D.2 Table 4.
- HiPPO initialization. S4 initializes the state dynamics from HiPPO matrices. At each time, HiPPO projects the signal history onto a finite span of polynomials. The measure for that time assigns weights to different parts of the history. The orthogonal projection minimizes the weighted squared approximation error within the span. The construction supplies an initialization for S4. HiPPO, section 2.2 and S4, sections 2.2 and 4.4.
- Normal plus low rank. S4 exploits a decomposition of the state matrix into a normal part and a low-rank correction . The columns of the unitary matrix provide a stable change of basis that makes the normal part diagonal. In that basis the full state matrix is diagonal plus low rank. The Woodbury identity reduces the inverse of a diagonal matrix with a low-rank correction to diagonal inverses and a small inner solve, when the relevant inverses exist. The resulting kernel evaluations reduce to structured Cauchy matrix products. Gu, Goel, and Ré, section 3.2 and Appendix C.3.
- Bilinear discretization. The original S4 paper computes its discrete transition and write matrices using the bilinear transform. This choice supports an efficient structured recurrent update. Gu, Goel, and Ré, section 2.3 and Appendix C.2.
In the bilinear formula, is the step size and and are the continuous-time matrices. The formulas require to be invertible. This holds for when every eigenvalue of has negative real part.
For a negative scalar rate and a positive step, the discrete pole is . Its magnitude is less than one because the magnitude of the numerator is strictly less than the denominator. The ZOH pole is also stable under these conditions. Both transitions are near , so they agree through the linear term in the step size. The worked example in this chapter uses the exact hold formulas for a diagonal system.
Mamba and Input-Dependent Selection
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 be the channel vector being processed at position . Three learned projections of that vector give a step size for each channel, a write vector, and a read vector. A simplified expression is
Here , , and is a learned bias. The projections are shared across positions. Mamba-1 shares the resulting and vectors across the channels. Each channel has its own learned diagonal continuous-time rates in , which are shared across positions. The input-dependent step size makes the discrete transition 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 in a particular channel, is the multiplier on the previous state. A small positive brings it close to one. A larger makes the multiplier smaller, so less of the old state carries through. The step size also affects the write strength. controls which coordinates receive the input, and controls which coordinates the readout uses.
The Recurrence
For one channel, write its scalar input as and its state as . The channel index is suppressed in the step size and the transition matrix. After discretization the computation takes the form
After computing the coefficients for a given input sequence, the write at position contributes to . For a coordinate with continuous rate , the intervening multipliers are . When , the product has no factors and equals one. The readout then takes the dot product of 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 , the code implements the following recurrence.
The exact held-input term uses as its coefficient on for . Expanding the exponential around gives for the fraction at fixed . This is why the implementation's 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 , where is the transition and is the input contribution. The pair acts on a state as . Applying update and then update gives
The whole segment has the same form as a single update, with transition and write term . Define composition with the later pair on the left.
Composition is associative in exact arithmetic since it is just composition of the represented affine maps. It is generally order-sensitive. The identity pair 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 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 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 compositions in levels.
- Hillis–Steele. In round , positions with a predecessor places away combine the two ordered results from the previous round. Round starts at offset one. Over rounds, work is and span is .
- 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 compositions and levels. An exclusive prefix omits the current update. Composing it with that update yields the inclusive prefix and adds at most compositions on one more level. The work stays and the span stays .
For a power-of-two , there are Hillis–Steele compositions in round , which sum to . 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]Expand
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]Expand

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 for batch size , channel width , sequence length , and state dimension . At , , , and , one such float32 array holds scalars. At four bytes each, it occupies bytes, or 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.
Mamba-2 and Structured State Space Duality
Mamba-2 uses a structured state space duality (SSD) layer. The discrete transition for a head is , so each state coordinate within that head has the same multiplier. Suppress the head index and look at one value channel with zero initial state. Let denote the discrete write vector at input position and the read vector at output position . The sequence mixing matrix for fixed coefficients has entries
The product equals one when . If the discrete inputs in that channel form the vector , the outputs are before any direct path. The inner product resembles a query-key score. SSD multiplies this score by a causal mask of decay products without softmax normalization. In standard scaled dot-product attention, softmax normalizes the scaled scores over each query's allowed positions.
Consider the block of entries with inputs and outputs , for a time boundary after position . Split each decay product at . The factors through carry the write at into the state . The later factors propagate that state to the readout at . The entire block factors through the coordinates of , so its rank is at most . SSD uses this semiseparable structure to apply matrix multiplications within chunks and carry state summaries between chunks. The resulting implementation can use accelerator matrix multiplication units. Mamba-2 also uses a larger head dimension than Mamba-1's single value channel per head. Dao and Gu, sections 2.4, 3.2 and 6.
For the plot, sample the write and read vectors for a synthetic sequence with 32 positions and state size four. Build its dense mixing matrix directly from the positive decay factors. For positions, the mixing matrix has entries. The code allocates a second array for decay products. The decay loop visits factors, since the product for indices has factors. SSD's chunked algorithm applies the mixing through within-chunk products and recurrent boundary states.
PythonIn [7]Expand
import numpy as np
ssd_L = 32
ssd_N = 4
ssd_rng = np.random.default_rng(7)
ssd_C = ssd_rng.normal(size=(ssd_L, ssd_N))
ssd_B = ssd_rng.normal(size=(ssd_N, ssd_L))
ssd_step_decay = 0.90 + 0.07 * np.sin(np.linspace(0.0, 3.0 * np.pi, ssd_L))
ssd_scale = np.ones((ssd_L, ssd_L))
for i in range(ssd_L):
for j in range(i):
ssd_scale[i, j] = np.prod(ssd_step_decay[j + 1 : i + 1])
ssd_matrix = np.zeros((ssd_L, ssd_L))
for i in range(ssd_L):
ssd_matrix[i, : i + 1] = ssd_C[i] @ (
ssd_scale[i, : i + 1] * ssd_B[:, : i + 1]
)
ssd_abs_max = np.abs(ssd_matrix).max()
ssd_diagonal = np.array([0, ssd_L - 1])VisualizationOut [8]Expand

Worked Example
The first NumPy example verifies that a fixed layer's recurrence and causal convolution give the same output within tolerance. The second uses a scalar state to show what happens when a programmed write must survive several updates.
A Fixed Linear SSM, Computed Two Ways
We construct a diagonal system with four stable modes, sample it with a zero-order hold, and then compute the output by (a) running the recurrence and (b) building the kernel and convolving. If the algebra in the previous sections is right, the two outputs agree to floating-point precision.
PythonIn [9]Expand
import numpy as np
rng = np.random.default_rng(11)
N, L = 4, 24
# Draw four rate magnitudes from a log-uniform range.
a = -np.exp(rng.uniform(np.log(0.05), np.log(2.0), size=N))
B = rng.normal(size=N)
C = rng.normal(size=N)
D = 0.25
step = 0.1ConsoleOut [10]Expand
continuous rates a: [-0.0803 -0.3154 -0.4598 -0.0556] input map B: [-0.298 -0.527 0.57 -0.056] readout map C: [ 0.747 -1.847 1.567 -0.096] direct path D: 0.25 step size Delta: 0.1
The rates are all negative, so every mode is stable and every discrete pole lies strictly inside the unit circle. Next we discretize with the zero-order hold from the earlier derivation.
PythonIn [11]Expand
Abar = np.exp(step * a) # diagonal of exp(Delta A)
Bbar = np.expm1(step * a) / a * B # (integral of exp(tau A) dtau) BConsoleOut [12]Expand
mode 0: a=-0.0803 Abar=0.9920 half-life=86.27 steps mode 1: a=-0.3154 Abar=0.9690 half-life=21.98 steps mode 2: a=-0.4598 Abar=0.9551 half-life=15.07 steps mode 3: a=-0.0556 Abar=0.9945 half-life=124.71 steps
The printed half-lives tell you how quickly an existing contribution fades in each mode. Next, draw an input sequence and apply the recurrence from zero initial state.
PythonIn [13]Expand
u = rng.normal(size=L)
x = np.zeros(N)
y_recurrent = np.empty(L)
for k in range(L):
x = Abar * x + Bbar * u[k]
y_recurrent[k] = C @ x + D * u[k]The second computation builds the kernel taps and folds the direct path into the tap. Then it evaluates the causal convolution directly, in fashion, which is fine at this scale.
PythonIn [14]Expand
kernel = np.empty(L)
example_positions = np.arange(L)
power = np.ones(N) # Abar^0
for j in range(L):
kernel[j] = C @ (power * Bbar)
power = power * Abar # Abar^(j+1)
kernel[0] += D # direct path lives on the first tap
y_conv = np.zeros(L)
for k in range(L):
for j in range(k + 1):
y_conv[k] += kernel[j] * u[k - j]
kernel_conv_matches = np.allclose(y_recurrent, y_conv, atol=1e-12, rtol=0.0)
assert kernel_conv_matchesConsoleOut [15]Expand
max |recurrent - convolution| = 4.441e-16 first six kernel taps: [0.4115 0.1548 0.1483 0.1421 0.1362 0.1305] of which the j=0 tap contains D = 0.25 recurrence matches causal convolution: True
The recurrence and causal convolution agree within the absolute tolerance of . In this run the maximum difference is about because the computations accumulate floating-point terms in a different order.
The plots show the first kernel taps and both output sequences. The model can use additional taps if it processes a longer sequence.
VisualizationsOut [16]Expand


The lag-zero bar includes the direct contribution . At other lags the bar is a signed sum of decaying modes. The recurrence and convolution output curves overlap at this plot scale.
A Hand-Programmed Read/Write Toy
A single state coordinate makes the effect of retention visible. Program a write at one position and multiply the state by a chosen retention factor at the other positions.
The scalar recurrence is , where controls how much of the old state survives and is the additive write. We program two actions.
- Overwrite. At the write position, set and so the new state equals .
- Retain. At every other position, set and multiply the state by the chosen retention factor .
PythonIn [17]Expand
def run_toy(retain, write_at=8, tokens=64, value=1.0):
"""Overwrite a scalar state once and apply retention at all other positions."""
x = 0.0
trace = np.empty(tokens)
for k in range(tokens):
if k == write_at:
x = value # programmed overwrite
else:
x = retain * x # zero write, retain part of the state
trace[k] = x
return trace
positions = np.arange(64)
retain_values = [1.0, 0.99, 0.95, 0.90]
traces = {r: run_toy(r) for r in retain_values}
trace_recent = run_toy(0.90, write_at=56)ConsoleOut [18]Expand
retention readout at k=63 relative to write
1.00 1.000000 100.0%
0.99 0.575355 57.5%
0.95 0.059539 6.0%
0.90 0.003043 0.3%
recent write at k=56 with retention 0.90: 0.478297 (47.8% of the written value)The write at position 8 has 55 updates left before the readout at position 63. The remaining value is for retention . At about 58% survives, and at about 0.3% survives. A write at position 56 undergoes only seven updates, so leaves about 48%.
In a learned selective layer, varying the step size changes the corresponding retention factor for that channel. For finite and finite , the exact exponential is strictly between zero and one. A small positive step brings it close to one. The toy uses both endpoints: discards the old state during an overwrite, and preserves it exactly when the write is zero.
VisualizationOut [19]Expand

At position 8, each solid curve rises to one. Once written, its state declines geometrically at the selected retention factor, or stays at one for the ideal hold. The dashed curve moves the write to position 56.
Prefill, Decode, and What "Constant Memory" Counts
The complexity discussion so far has been about arithmetic. Practical deployment cares about three separate quantities, and they scale differently.
- Prefill work. The cost of processing a prompt of length in one pass.
- Decode work. The cost of a single update. The attention row below counts the query at the th processed position, with earlier keys plus its own.
- Persistent storage. The bytes held per sequence after processing positions.
Starting a new step with a cache of positions gives eligible keys once the new key is added. Repeated decode steps can dominate a long completion, depending on the prompt, the completion length, and the implementation. When device memory is the bottleneck, the amount of persistent storage per sequence helps determine how many concurrent sequences fit.
Use a single-sequence calculation with 24 layers, state dimension , and width 1024 on each side. The attention side has 1024 total dimensions for keys and 1024 for values, and matches query and key heads one to one. The state space mixer has 1024 inner channels. These equal widths give a worked comparison of core operations rather than a parameter-matched pair of model configurations.
PythonIn [20]Expand
d_model = 1024 # summed head width and SSM inner width in this example
n_state = 16 # SSM state dimension per channel
n_layers = 24 # number of blocks
L = 4096 # processed positions and eligible keys for query L
bytes_per_scalar = 2 # fp16
# Attention products, counting two FLOPs per multiply-add.
attn_prefill_flops = (
2 * L * (L + 1) * d_model
) # QK^T and weighted V over causal pairs
attn_decode_flops = 4 * L * d_model # one query over L keys, including its own
# Per-layer SSM core: update with a precomputed write, then read out the state.
ssm_prefill_flops = 4 * n_state * d_model * L
ssm_decode_flops = 4 * n_state * d_model
# Persistent per-sequence storage
kv_elements = 2 * L * d_model * n_layers # K and V
ssm_elements = n_state * d_model * n_layers # one state per channel
conv_elements = 4 * d_model * n_layers # depthwise conv buffer, width 4
kv_bytes = kv_elements * bytes_per_scalar
ssm_bytes = ssm_elements * bytes_per_scalar
conv_bytes = conv_elements * bytes_per_scalar
ssm_total_bytes = ssm_bytes + conv_bytes
expanded_state_bytes = (
1 * 2048 * 8192 * 16 * 4
) # batch, channels, length, state, fp32ConsoleOut [21]Expand
configuration: d=1024, N=16, layers=24, L=4096 quantity attention SSM prefill arithmetic (FLOPs per layer) 34,368,126,976 268,435,456 decode arithmetic at L (FLOPs per layer) 16,777,216 65,536 persistent storage (bytes per sequence) 402,653,184 983,040 ratio, prefill arithmetic: 128.0x ratio, decode arithmetic: 256.0x ratio, persistent storage: 409.6x SSM storage across 24 layers: 786,432 bytes of recurrent state + 196,608 bytes of convolution buffer Expanded float32 state array at batch 1: 1.00 GiB
The table counts the two main attention products. Computing the query-key dot product and adding a weighted value uses roughly FLOPs per allowed pair when a multiply-add is counted as two FLOPs and is the sum of key widths over the heads, equal here to the sum of value widths. A length- causal prefill has pairs. At the th processed position the decode count uses allowed pairs. For the SSM core, take the write vector as given. The diagonal update uses FLOPs per channel, and the state readout uses , so the proxy rounds to . The literal worked-example loop also computes and adds . Both operations are outside this estimate.
The table reports arithmetic per layer and persistent storage per sequence across all 24 layers. It counts the attention cache after positions and includes both the recurrent state and the convolution buffer on the SSM side. Each uses two bytes per element. Model weights, temporary activations, allocator overhead, and cache compression are outside the storage count. For the arithmetic comparison, projections, softmax, discretization, and scan overhead are outside the count. The plots therefore describe the scaling of these selected operations rather than wall-clock inference time.
The arithmetic table above is easier to read as scaling curves. The next two cells reuse the fixed dimensions from that configuration and plot the per-layer work as the prefix length grows.
PythonIn [22]Expand
import numpy as np
scale_lengths = np.array([2**k for k in range(6, 19)], dtype=float)
attention_prefill_curve = 2 * scale_lengths * (scale_lengths + 1) * d_model
ssm_prefill_curve = 4 * n_state * d_model * scale_lengths
attention_decode_curve = 4 * scale_lengths * d_model
ssm_decode_curve = np.full_like(scale_lengths, 4 * n_state * d_model)VisualizationOut [23]Expand

The Mamba-1 implementation has a causal convolution before the state space layer. Its v2.2.4 default buffer length is four entries per inner channel. At the same dtype as the state, the buffer uses as many bytes as the state, independent of prefix length. Mamba-1 reference block, v2.2.4.
PythonIn [24]Expand
prefix_lengths = np.array([2**k for k in range(6, 19)], dtype=float)
kv_storage = 2 * prefix_lengths * d_model * n_layers * bytes_per_scalar
ssm_storage = np.full_like(prefix_lengths, ssm_bytes)
ssm_storage_with_conv = np.full_like(prefix_lengths, ssm_total_bytes)VisualizationOut [25]Expand

For the plotted dimensions, the SSM state and convolution buffer stay constant and the full attention cache grows in proportion to the processed prefix length. At the same per-head key and value widths and dtype, fewer key-value heads lower the cache payload. At the same number of cached elements, fewer bytes per element also lower it.
Limitations and Impact
The state carries the information the model needs later. A state that records a running total can preserve that statistic even when many tokens have passed. A model answering arbitrary queries about exact spans has a harder job. At fixed precision a fixed-size recurrent decoder has finitely many carried configurations. Count every buffer that can distinguish histories, including the convolution history. If more equal-length prefixes are possible than complete carried configurations, two prefixes must reach the same state. After processing the same nonempty continuation from that state with identical auxiliary inputs, the decoder computes the same next-token distribution for both histories. The two histories can still call for different answers. The practical question is whether collisions affect the kinds of recall your task needs.
Gu and Dao reported empirical comparisons in specific training and evaluation settings. In their Table 1, Mamba-2.8B averaged 63.3 across six zero-shot accuracy benchmarks, versus 59.1 for Pythia-2.8B and 63.0 for GPT-J-6B. The larger GPT-J comparison used a different tokenizer, and the mean hides which benchmarks favored which model. Treat this as evidence about those evaluations at those scales. To test recall separately, score exact value retrieval on held-out sequences of key-value pairs. Vary the distance from the target pair to the query, and vary the number, positions, and similarity of distractors. Mamba, section 4.2 and Table 1.
Math also leaves an implementation question. The exponentials, products and sums in a long recurrence can round differently across precisions and arithmetic order. Very small retained contributions can underflow, and a stored state in float32 uses twice as many bytes as the same state in float16. Separately, memory traffic and hardware support affect whether a scan is fast. Measure latency and peak memory for the exact workload, including how serving requests are batched and how long the prompts and completions are.
Summary
- A recurrent state space layer stores the state from its last update. In a fixed-width, purely recurrent layer, storage and per-step recurrent work stay constant as the processed prefix grows.
- Exact zero-order hold gives the transition and write map . The integral handles singular . For a negative scalar rate, shorter steps preserve more of the previous state.
- A zero-initial-state LTI recurrence can evaluate the same outputs by causal convolution with taps , plus the direct path at lag zero. Constructing the taps and applying them are distinct operations. S4's structured state matrix makes construction more efficient.
- Mamba-1 conditions the step size, write vector, and read vector on the input. Once those quantities are computed, the state updates can be composed as affine maps and evaluated by an ordered parallel scan.
- Mamba-2's scalar transition within each head yields a mixing matrix built from unnormalized dot products and a causal decay mask. SSD exploits low rank in blocks across chunk boundaries. It uses matrix multiplication inside chunks and propagates the recurrent state between them.
The next chapter looks at using attention and state space layers in one architecture and at what changes when you move either type of layer.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about state space models for language.
State Space Models for Language
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!