State-space models: one memory, two computation paths
序列状态空间模型
Derive recurrence–convolution equivalence, preserve chunk state and compute exact diagonal zero-order-hold discretization.
state-space-modelsStart with the problem
A running total summarizes a history without storing every previous input. A state-space model generalizes this idea: a hidden vector is updated by each input, and an output is read from that vector. Different state coordinates can retain information at different rates.
The term covers a broad family, including models with noise and hidden-state estimation. This chapter studies deterministic linear time-invariant sequence layers. S4, Section 2, explains how continuous, recurrent and convolutional representations connect. We will verify that connection directly before adding input-dependent selection in Mamba.
Definitions and derivation
A continuous-time linear system has a state h, scalar input u and scalar output y. Under a zero-order hold, the input is constant during each interval of length Δ, giving an exact state transition for that assumption:
The integral avoids assuming Ac is invertible. For a diagonal coordinate a, its input factor is (exp(aΔ)−1)/a when a is nonzero and Δ when a is zero. The code uses expm1 to avoid subtracting nearly equal numbers. Other discretizations produce other transitions: S4’s background uses the bilinear rule, while Mamba’s preliminaries, Equation 4, display zero-order hold. These rules should not be silently interchanged.
Once discrete matrices are chosen, the sequence layer is:
Here h₋₁ is the state before consuming u₀. Substituting the recurrence repeatedly yields:
For zero initial state, this is a causal, non-circular convolution with one fixed kernel. Nonzero initial state adds the first term; simply convolving the new chunk as if its initial state were zero loses that history. The D term is a direct input-to-output path and changes only kernel lag zero.
For a finite-dimensional fixed system, spectral radius below one makes unforced state effects decay asymptotically. It does not imply that every intermediate norm decreases, especially for nonnormal matrices. The example uses a diagonal transition with entries 0.5 and 0.8. A zero continuous eigenvalue instead discretizes to one and can act as an integrator, so not every state coordinate forgets.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program uses two state coordinates, eight inputs and a direct coefficient D=0.1. It computes recurrence, direct convolution and zero-padded FFT convolution, then splits the sequence into two chunks.
import numpy as np
A = np.array([.5,.8]); B = np.array([1.,.5]); C = np.array([1.,-1.]); D = .1
def scan(inputs, state=None):
u = np.asarray(inputs,dtype=float); h = np.zeros(2) if state is None else np.array(state,dtype=float,copy=True)
if u.ndim != 1 or not 1 <= len(u) <= 64 or h.shape != (2,) or not np.isfinite(np.r_[u,h]).all():
raise ValueError('Use 1 to 64 finite inputs and a two-coordinate state.')
output = []
for value in u:
h = A*h+B*value
output.append(float(C@h+D*value))
return np.array(output),h
def impulse_kernel(length):
if type(length) is not int or not 1 <= length <= 64:
raise ValueError('Kernel length must be an integer from 1 to 64.')
result = np.array([C@(A**lag*B) for lag in range(length)])
result[0] += D
return result
def fft_convolution(inputs,kernel):
size = len(inputs)+len(kernel)-1
padded = 1 << (size-1).bit_length()
result = np.fft.irfft(np.fft.rfft(inputs,padded)*np.fft.rfft(kernel,padded),padded)
return result[:len(inputs)]
def zoh_diagonal(a,b,step):
a,b = np.asarray(a,dtype=float),np.asarray(b,dtype=float)
if a.ndim != 1 or a.shape != b.shape or not 1 <= a.size <= 8 or not np.isfinite(np.r_[a,b,step]).all() or not 0 < step <= 1:
raise ValueError('Use matching finite diagonal coefficients and a step in (0,1].')
scaled = a*step; abar = np.exp(scaled)
factor = np.full_like(a,step); np.divide(np.expm1(scaled),a,out=factor,where=a!=0)
return abar,factor*b
if __name__ == '__main__':
u = np.array([1.,0,2,-1,0,.5,0,1]); y,state = scan(u); k = impulse_kernel(len(u))
direct = np.convolve(u,k)[:len(u)]; fast = fft_convolution(u,k)
first, saved = scan(u[:4]); second,_ = scan(u[4:],saved); reset,_ = scan(u[4:])
print('kernel first four',k[:4].round(9).tolist(),'output',y.round(9).tolist())
print('recurrence / direct discrepancy',float(np.max(np.abs(y-direct))),'FFT discrepancy',float(np.max(np.abs(y-fast))))
print('chunk restore discrepancy',float(np.max(np.abs(np.r_[first,second]-y))),'reset discrepancy',round(float(np.max(np.abs(reset-y[4:]))),9))
abar,bbar = zoh_diagonal([-1.,0.],[1.,2.],.5)
print('ZOH diagonal A',abar.round(9).tolist(),'B',bbar.round(9).tolist())
Actual output:
kernel first four [0.6, 0.1, -0.07, -0.131] output [0.6, 0.1, 1.13, -0.531, -0.3823, -0.02459, -0.219047, 0.3450749]
recurrence / direct discrepancy 1.1102230246251565e-16 FFT discrepancy 1.3877787807814457e-16
chunk restore discrepancy 0.0 reset discrepancy 0.3823
ZOH diagonal A [0.60653066, 1.0] B [0.39346934, 1.0]
The first kernel values are (0.6,0.1,−0.07,−0.131). The two decaying state components combine into a signed response. Both convolution forms agree with recurrence to floating-point precision. Restoring the saved chunk state gives exact agreement; resetting it changes the second chunk by as much as 0.3823.
A dense N-coordinate state update costs O(N²) per token; this diagonal example costs O(N). Streaming inference needs only the current state besides its fixed parameters. Direct convolution costs O(T²) for a T-long kernel and input, while FFT convolution costs O(T log T) after the kernel is known. Padding to at least the full linear-convolution length prevents circular wraparound. Efficiently generating long structured kernels is part of what S4 addresses, not something this two-state example solves at arbitrary scale.
When the method fails
The fixed-kernel equivalence requires fixed linear transitions and readout. Input-dependent coefficients, nonlinear state updates or changing parameters generally invalidate that single convolution kernel. A fixed state is also a compression bottleneck: representing history with N numbers does not guarantee perfect recovery of every past token.
Distinguish a deterministic sequence layer from a probabilistic state estimator. Adding process noise, observation noise or a filtering posterior requires additional assumptions and algorithms. Neither the toy impulse response nor a stable transition proves that a trained sequence model will learn long-range tasks well. S4 introduces specific structured parameterizations; the present program uses a deliberately small diagonal example.
Exercises with answers
- Which kernel term contains the direct coefficient D?
Answer 1: Only lag zero, because Duₜ affects the current output directly.
- What is missing when a new chunk is processed from a zero state?
Answer 2: The contribution of the previous chunk carried by its final hidden state.
- For continuous a=0, b=2 and Δ=0.5, what are the discrete coefficients?
Answer 3: Abar=1 and Bbar=1, using the integral limit rather than dividing by zero.
- Why pad an FFT beyond the input length?
Answer 4: Multiplication of unpadded discrete spectra produces circular convolution, which wraps the kernel tail into earlier outputs.
Sources and next steps
S4 physical pages 3–4 provide the state model, bilinear discretization and recurrent/convolutional derivation. Mamba physical page 3 supplies the zero-order-hold alternative. The signed two-state kernel, chunk-resume checks and diagonal integral limits are original calculations. Continue with Mamba for a selective recurrence that no longer has one input-independent convolution kernel.
Make a prediction, then check
When does one fixed causal convolution represent the sequence layer without an extra state term?
Learning objectives
- Derive the fixed-kernel representation and initial-state term.
- Compare recurrence, FFT convolution and discretization conventions.
Prerequisites & connections
Explore related knowledge →References
- Efficiently Modeling Long Sequences with Structured State Spaces — arXiv v3
Albert Gu; Karan Goel; Christopher Ré · 2022 - Mamba: Linear-Time Sequence Modeling with Selective State Spaces — arXiv v1
Albert Gu; Tri Dao · 2023
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.
Source locations checked:
- Efficiently Modeling Long Sequences with Structured State Spaces — arXiv v3 · Physical pages 3–4, Sections 2.1, 2.3 and 2.4, Equations 1 and 3–5: continuous model, bilinear rule and zero-state causal convolution.
- Mamba: Linear-Time Sequence Modeling with Selective State Spaces — arXiv v1 · Physical page 3, Section 2 Equations 1–4: state recurrence, kernel and zero-order-hold discretization.
Related topics