Lesson 4.7 — State Space Sequence Models
Previous lesson · 4.6 Graph Neural Networks · Course overview · Next lesson · 5.1 Variational Autoencoders
State Space Foundations · From Control to Sequences
A state space model summarizes history in an internal state h and produces outputs through state dynamics and a readout. In control, the state may contain position, velocity, or current. In sequence learning, it often consists of latent coordinates optimized for the task. Those coordinates may lack a direct physical interpretation or a unique identification from the outputs.
The transition matrix A governs state dynamics, B maps the input into the state, C reads the state, and D gives direct feedthrough. A finite-dimensional continuous LTI system is internally asymptotically stable when every eigenvalue of A has negative real part. An invertible coordinate change h′ = Th yields A′ = TAT⁻¹, B′ = TB, and C′ = CT⁻¹ with the same input–output map when the initial state is transformed accordingly.
Continuous State Space Simulator
Continuous to Discrete · Zero-order Hold
Under zero-order hold, input sample x_t is constant on the interval from tΔ to (t + 1)Δ. In this section, h_t is the state at the start of that interval. Variation of constants gives the state at its endpoint.
The input integral also exists when A is singular. The augmented matrix exponential computes both discrete coefficients without taking a matrix inverse.
For scalar A tending to zero, (exp(AΔ) − 1)/A tends to Δ. Use expm1 to compute the numerator near zero. At A = 0 the exact discrete transition is one and the input coefficient is BΔ. Forward Euler instead uses I + ΔA and ΔB. For positive Δ, exact ZOH maps stable continuous poles inside the unit circle. Euler can put them on or outside the unit circle. In a learned sequence model, Δ can be a learned discretization parameter with no physical time unit.
ZOH Discretization Explorer
State Space Sequence Modeling · Memory Modes
From here on, use the sequence convention h[−1] = 0, with h_t and y_t computed after reading x_t. For a diagonal time-invariant transition, each mode carries an exponentially weighted memory at its own timescale. The readout combines information from these modes.
The decay constants below apply to modes with negative real part. Complex conjugate modes can produce decaying oscillations. A non-normal matrix can transiently amplify some states even when all eigenvalues have negative real part. Setting each diagonal pole to −exp(α_j) ensures decay. Multiple learned modes can still be redundant, and scaling or changing coordinates can produce the same input–output map.
Eigenvalue & Memory Timescale
| Mode | Pole λ | Discrete pole | Half-life (steps) | Remaining |
|---|---|---|---|---|
| 1 | -0.15 | 0.9704 | 23.1049 | 1 |
| 2 | -1.2 | 0.7866 | 2.8881 | 1 |
Recurrence–Convolution Duality
Consider a single mode at rest, , with update and readout . A unit pulse writes one unit into the state. Each quiet step retains 65% of what remains. The output following that one pulse is the impulse response for lag .

Read down the column at step 3. The positive pulse still contributes . The new negative pulse contributes , so the output becomes . A recurrent implementation gets there by retaining 65% of the previous state and adding the new input. A convolution gets there by adding the two entries in that column. They agree because time invariance lets us shift the response to the new arrival time, and linearity lets us scale and add the two responses.
For multiple state coordinates, a pulse first writes through , travels through copies of , and is read out by . This gives the lag- kernel below. The term is an additional instantaneous path.
With a nonzero initial state, add C Ā^(t+1) h[−1]. A recurrent implementation processes inputs one at a time and carries the current state. A fixed convolution can also use an FFT with enough zero padding to compute linear convolution. The kernel is indexed by causal lag. When coefficients depend on inputs, a single input-independent convolution kernel generally cannot describe the recurrence.
Compare the two computations on a longer input sequence
Recurrence vs. Convolution
S4 and Parallel Scan for Long Sequences
S4 uses structured state matrices to form long convolution kernels efficiently. Its construction builds on HiPPO, which represents a history function with a finite set of coefficients, and exploits normal-plus-low-rank or diagonal-plus-low-rank structure. The diagonal examples here expose the underlying state update directly.
Another parallel route is an affine scan. Represent each step by f_t(h) = a_t h + b_t. For diagonal states, multiply elementwise. Applying the left map followed by the right map gives the following composition.
Both parenthesizations of three consecutive maps give (a₃a₂a₁, a₃a₂b₁ + a₃b₂ + b₃). The associativity allows prefix computations to run in parallel. In the Hillis–Steele animation, one round combines neighboring blocks at the current stride. Intermediate entries can still represent partial prefixes. After the final round every row covers its complete prefix. This algorithm takes O(log T) parallel rounds and O(T log T) total work. A work-efficient scan can reduce total work to O(T). The animation measures the algorithmic trace.
Parallel Scan Animation
Selective State Space Models · Content-dependent Memory
A fixed LTI state space model uses the same transition, input map, and readout at every step. In Mamba-1, the step size Δ and the maps B and C can depend on the current input. The structured continuous matrix A is learned and shared over time. This scalar demonstration uses exact ZOH for the input coefficient. Implementations can approximate that term differently.
For a negative scalar pole and positive step size, increasing Δ decreases the fraction of old state carried forward and also changes the input coefficient. B determines what writes into the state, and C determines what the output reads. Unrolling the input-conditioned recurrence gives an ordered product of transitions.
Compare two unit pulses of the same age in two different contexts. With a fixed transition, their state contributions have gone through identical transitions. With input-dependent transitions, one pulse may be followed by a token that sharply reduces retention while the other is followed by a token that preserves it. Their age alone no longer determines their contribution. This is the step where the single reusable impulse trace in the figure ceases to suffice.
The product applies earlier transitions first, and an empty product is the identity. The full input–output map is nonlinear because the coefficients depend on the input. For a fixed input sequence, the recurrence is affine in the prior state, so scan composition still applies. Whether selectivity helps depends on the task and evaluation.
Selective State Update
Mamba Block · From One State Update to a Network
A Mamba-1 block projects the input into a main branch and a gating branch. A causal depthwise convolution and SiLU transform the main branch, which produces Δ, B, and C for the selective scan. The gating branch applies SiLU to a separate projection. Multiply the two branches elementwise and apply an output projection. A stack typically surrounds the block with normalization and residual connections. The lab follows these operations through a scalar teaching example.
Each inner channel has N states. In Mamba-1, A is commonly parameterized as a negative diagonal transition in continuous time. Input-dependent B and C can be shared across inner channels, while Δ can vary by channel. Fused selective scan reduces memory traffic from intermediate states. Recurrent inference carries the state and a local convolution buffer. Standard dense Transformer attention uses a key–value cache that grows with context length. With fixed model widths, processing a sequence takes linear work for the state updates and quadratic work for dense full-sequence attention. Actual latency depends on the kernel, sequence length, batch, and hardware.
Mamba Block Dataflow
Engineering Experiment · Long-horizon Robot Dynamics
Reuse the synthetic dynamics task from Lessons 4.1 and 4.3. Train on 32 trajectories and validate on 24, with 12 inputs per trajectory. The hidden states start at zero, and each input is sampled independently from the uniform distribution on [−1, 1]. The model observes only the input history and predicts the terminal output.
Train four diagonal modes using exact scalar ZOH. The readout applies tanh to the terminal state. Both models learn fixed B and C coefficients. In the selective variant, only the step size Δ can depend on the input. Both use the same initialization rule, data, and Adam schedule, and store 22 parameters. The four input-gating coefficients are inactive in the fixed variant, giving 18 effective parameters.
For the manual BPTT derivation, write E = exp(AΔ), F = (E − 1)/A, and A = −exp(α). The local derivatives below separate the transition and input contributions.
Backpropagation through the sequence accumulates gradients for the shared parameters. The derivative of softplus is sigmoid. Click Run training comparison to execute full-batch Adam and inspect the saved checkpoints. The longer-sequence evaluation uses separately generated inputs of length 48 at seed plus 3000. Its error is measured at the terminal output on each trajectory.
Live Fixed / Selective SSM Training
Actual benchmark · PyTorch
| Model | Parameters | Val MSE T=12 | Val MSE T=48 |
|---|---|---|---|
| MLP (0401) | 13 | 0.161051 | — |
| RNN (0401) | 33 | 0.001939 | — |
| LSTM (0401) | 117 | 0.000853 | — |
| GRU (0401) | 89 | 0.001076 | — |
| Transformer + PE (0403) | 157 | 0.033153 | — |
| Fixed SSM | 22 (18 effective) | 0.000233 | 0.001084 |
| Δ-only Selective SSM | 22 | 0.000573 | 0.001130 |
The fixed variant has lower validation MSE at both lengths in this default configuration. Its diagonal memory modes may be a useful structural prior for the generator. This run does not isolate a general advantage of fixed state space models over selective models. The other model families in the table were evaluated at length 12 only. The experiment measures terminal prediction on synthetic data. Hardware performance, closed-loop behavior, and selectivity on a task that requires storing or ignoring an input remain separate questions.
Reproducible PyTorch implementation
Save the script as ssm0407.py and run it with PyTorch installed. It uses float64, a deterministic generator, and autograd. Change the seed, state width, or training sequence length in the run configuration.
import math
import torch
from torch import nn
import torch.nn.functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
class RNG:
def __init__(self, seed): self.s=seed&0xffffffff
def __call__(self):
self.s=(1664525*self.s+1013904223)&0xffffffff
return self.s/4294967296
def dataset(n,T,seed):
r=RNG(seed); X=[]; Y=[]
for _ in range(n):
a=b=0.; seq=[]
for t in range(T):
u=2*r()-1; seq.append(u)
a=.88*a+.3*u; b=.4*b+.2*u
X.append(seq); Y.append(a+.4*b+.1*u+.12*math.sin(2*a))
return torch.tensor(X),torch.tensor(Y)
def initial(seed,H=4):
r=RNG(seed+2000)
return [[math.log(.1*2**i) for i in range(H)], [.4*(2*r()-1) for _ in range(H)], [.8*(2*r()-1) for _ in range(H)], [0.]*H,[0.]*H,[0.],[0.]]
class Model(nn.Module):
def __init__(self,seed=3,H=4,selective=True):
super().__init__(); self.p=nn.ParameterList(nn.Parameter(torch.tensor(p)) for p in initial(seed,H)); self.selective=selective
def forward(self,x):
loga,b,c,d0,d1,skip,bias=self.p
a=-loga.exp(); h=x.new_zeros(x.shape[0],len(a))
for u in x.unbind(1):
u=u[:,None]; delta=F.softplus(d0+(d1*u if self.selective else 0*d1))
ad=(a*delta).exp(); bd=torch.expm1(a*delta)/a*b
h=ad*h+bd*u
return (h.tanh()*c).sum(-1)+skip*x[:,-1]+bias
def run(seed=3,lr=.025,updates=120,selective=True,H=4,T=12):
x,y=dataset(32,T,seed); v,w=dataset(24,T,seed+1000); long,yl=dataset(24,4*T,seed+3000)
m=Model(seed,H,selective); opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for t in range(updates+1):
loss=(m(x)-y).square().mean()
if t%10==0 or t==updates:
with torch.no_grad():
hist.append(dict(t=t,tr=loss.item(),va=(m(v)-w).square().mean().item(),long=(m(long)-yl).square().mean().item(),p=[p.tolist() for p in m.p]))
if t<updates: opt.zero_grad(); loss.backward(); opt.step()
return hist
if __name__=='__main__':
for selective in (False,True):
h=run(selective=selective); print('selective',selective, 'initial',h[0]['va'],'final', {k:v for k,v in h[-1].items() if k!='p'})
AI-native verification workflow
Check discrete poles and their timescales. Compare the matrix exponential with the scalar ZOH coefficients, and compare the recurrence with direct convolution and scan. Check the manual gradient against autograd. To study selectivity, hold the data generation fixed while changing the state width or conditioning the step size, then evaluate terminal prediction at both lengths.
Authoritative References & Chapter Summary
Chapter 04 synthesis
RNNs maintain nonlinear recurrent state. Attention reads values based on content, and Transformers combine it with FFNs and residual streams. GPT trains on causal next-token probabilities, ViT treats image patches as tokens, GNNs pass messages along edges, and SSMs use structured recurrences. Choose the architecture based on the task structure, information available at inference, resource budget, and reproducible evaluation.
Chapter 5 covers generative modeling, including VAEs, GANs, normalizing flows, diffusion, score-based models, flow matching, and conditioning.
Previous lesson · 4.6 Graph Neural Networks · Course overview · Next lesson · 5.1 Variational Autoencoders