Module contents
Lesson 18 of 22Research 110 min

State space models: from linear recurrences to S4

Discretize state-space models, derive recurrent and convolutional forms, study HiPPO and diagonal SSM stability, and compare small models on CIFAR-10.

After this lesson you can

  • Discretize continuous state-space dynamics with zero-order hold and compare stability.
  • Derive the equivalence between invariant recurrence and causal convolution.
  • Explain HiPPO projection and diagonal SSM kernels.
  • Implement a diagonal SSM and verify recurrence against FFT convolution.
  • Interpret a small image experiment alongside published S4D results.

Before you start

A memory that evolves

A linear state-space model compresses the past into a state vector. In continuous time, for scalar input u(t)u(t), state x(t)∈RN\vb x(t)\in\R^N, and scalar output y(t)y(t),

x˙(t)=Ax(t)+Bu(t),y(t)=Cx(t)+Du(t).\dot{\vb x}(t)=\mat A\vb x(t)+\vb B u(t),\qquad y(t)=\mat C\vb x(t)+D u(t).

Matrices may be learned, and a sequence layer can apply systems per channel and combine channels through other operations. Compared with a cache retaining individual keys and values, state mixes history into NN components. Its size does not grow with step count, but that does not guarantee recovery of every old detail.

Matrix AA governs autonomous state evolution; BB determines how a sample enters and CC how memory is read. Term DD creates a direct path from current input to output. Changing only CC can modify readout without changing dynamics; changing AA or step size changes what information persists. With multiple channels, memory accounting multiplies state size by channel count and batch. “Fixed state” refers to sequence length, not zero memory for those axes.

Moving to discrete samples

In zero-order-hold (ZOH) discretization, uu is assumed constant during each interval of duration Δ>0\Delta>0. The exact solution for that interval is

Aˉ=eΔA,Bˉ=∫0ΔesAB ds.\bar{\mat A}=e^{\Delta\mat A},\qquad \bar{\vb B}=\int_0^\Delta e^{s\mat A}\vb B\,ds.

When AA is invertible, Bˉ=A−1(eΔA−I)B\bar B=A^{-1}(e^{\Delta A}-I)B; the integral remains well defined if AA is singular. For diagonal eigenvalue λ=0\lambda=0, the limit of (eΔλ−1)/λ(e^{\Delta\lambda}-1)/\lambda is Δ\Delta. Using expm1 near zero avoids subtracting nearly equal numbers.

The formula follows from variation of constants: from the start of an interval, the solution is x(Δ)=eΔAx(0)+∫0Δe(Δ−s)ABu dsx(\Delta)=e^{\Delta A}x(0)+\int_0^\Delta e^{(\Delta-s)A}B u\,ds. Input leaves the integral because ZOH holds it constant; substitution r=Δ−sr=\Delta-s gives the preceding expression. For general matrices, forming an explicit inverse is undesirable: solving a system or using an augmented matrix exponential may be more stable and also handles singular systems.

The hold assumption matters: ZOH exactly describes a continuous system fed a piecewise-constant signal; it does not reconstruct the unknown signal between samples. Changing Δ\Delta without changing AA observes the same continuous system at another time resolution. A larger step moves a stable pole farther toward the origin per sample and advances an oscillation through a larger angle; this does not necessarily mean shorter memory measured in physical time. A frequency above sampling resolution can also be confused with another discrete frequency.

A safe way to handle singular matrices too is the block exponential of [AB00]Δ\left[\begin{smallmatrix}A&B\\0&0\end{smallmatrix}\right]\Delta. Its upper-left block is Aˉ\bar A and upper-right is Bˉ\bar B. The diagonal example uses a scalar expression to expose poles and calculate the zero limit; a general implementation must consider matrix-exponential precision and cost. Stable discretization does not guarantee every finite-precision computation is accurate for arbitrarily long sequences.

The bilinear or trapezoidal rule approximates the same system with

Aˉ=(I−Δ2A)−1(I+Δ2A),Bˉ=(I−Δ2A)−1ΔB.\bar A=(I-\tfrac\Delta2 A)^{-1}(I+\tfrac\Delta2 A),\qquad \bar B=(I-\tfrac\Delta2 A)^{-1}\Delta B.

For scalar pole λ\lambda, ZOH maps it to eΔλe^{\Delta\lambda} and the bilinear rule to (1+Δλ/2)/(1−Δλ/2)(1+\Delta\lambda/2)/(1-\Delta\lambda/2). If Re⁡λ<0\operatorname{Re}\lambda<0 and Δ>0\Delta>0, both lie inside the unit disk. Explicit Euler uses 1+Δλ1+\Delta\lambda and can leave the disk even for a stable continuous system: with λ=−3\lambda=-3 and Δ=1\Delta=1 it gives -2. Marginal stability and Jordan blocks require more care than pole modulus alone.

To check the bilinear rule, write z=Δλ/2z=\Delta\lambda/2. The difference ∣1−z∣2−∣1+z∣2=−4Re⁡z|1-z|^2-|1+z|^2=-4\operatorname{Re}z is positive if λ\lambda has negative real part; the quotient’s modulus is therefore less than one. ZOH gives ∣eΔλ∣=eΔRe⁡λ|e^{\Delta\lambda}|=e^{\Delta\operatorname{Re}\lambda}. A pole very close to the boundary can retain signal for many steps, but the same parameter can make decay of errors or state changes slow.

InteractiveImpulse response of a pole pair
0.75-0.75031 stepsReIm|z|=1
-0.5
2.0
0.5
Magnitude of Ā0.779
Behaviordecays
First kernel value0.753
Controls define continuous conjugate poles and their ZOH step. Thirty-two kernel values are shown; modulus greater than one indicates growth in this diagonal example.

One recurrence, one convolution

Adopt the convention of reading output after incorporating the sample: xt+1=Aˉxt+Bˉutx_{t+1}=\bar A x_t+\bar B u_t and yt=Cxt+1+Duty_t=Cx_{t+1}+Du_t. With x0=0x_0=0, expanding recurrence-convolution duality gives

yt=∑j=0tKjut−j+Dut,Kj=CAˉjBˉ.y_t=\sum_{j=0}^{t} K_j u_{t-j}+Du_t,\qquad K_j=C\bar A^j\bar B.

Recurrence updates one state per token and is natural for inference. If parameters are constant over the sequence, the same kernel can be applied as a parallel convolution; for length TT, an FFT can perform it in O(Tlog⁡T)\bigO(T\log T) after kernel construction. That figure need not include constructing KK, projections, or the rest of the layer. If AA, BB, or CC depend on each input or position, generally no single invariant kernel exists for the whole sequence.

The kernel is the impulse response: place one at u0u_0 and zeros afterward, and output without the direct path is K0,K1,…K_0,K_1,\ldots. For a general signal, linearity allows shifted copies of that response to be summed, each multiplied by its corresponding input. The same reasoning explains why a linear invariant layer cannot change its write rule based on whether the current token is relevant: the coefficient for an input at a given delay is the same for every input. Other layers and nonlinearities around the SSM can change what enters the system, however; this limit should not be extended to every network containing it.

The timing convention deserves a small test before optimization. With impulse input and zero initial state, this lesson gets y0=CBˉ+Dy_0=C\bar B+D; a library reading CxtCx_t before updating would produce DD first and shift the rest one step. Both conventions can be valid, but mixing one kernel with the other’s recurrence creates a discrepancy that grows through a stack. The figure and cells consistently use the first convention.

In the diagonal case, updating a head of size NN needs an elementwise product and addition per component, O(N)\bigO(N) per token and NN state elements. If complex, each occupies two real components; conjugate pairs can represent real output. Naively building all TT kernel terms costs O(NT)\bigO(NT); FFT accelerates the subsequent convolution and does not automatically eliminate construction. By contrast, dense causal attention with cache retains prior keys and values and calculates the query against history. A nonlinear RNN also has fixed state, but its data-dependent composition is generally not replaced by one fixed convolution.

Proof
For t=0t=0, x1=Bˉu0x_1=\bar B u_0. If xt=∑j=0t−1AˉjBˉut−1−jx_t=\sum_{j=0}^{t-1}\bar A^j\bar B u_{t-1-j}, substituting into the update gives xt+1=∑j=0tAˉjBˉut−jx_{t+1}=\sum_{j=0}^{t}\bar A^j\bar B u_{t-j}. Multiplying by CC and adding DutDu_t gives causal convolution. Nonzero initial state also contributes CAˉt+1x0C\bar A^{t+1}x_0.∎
InteractiveRecurrence and convolution
t=0
u=1
y=0.200
t=1
u=0
y=0.160
t=2
u=-1
y=−0.072
t=3
u=2
y=0.342
t=4
u=0
y=0.274
t=5
u=1
y=0.419
t=6
u=-2
y=−0.065
t=7
u=0
y=−0.052
0
Input u[t]1
Recurrence0.20000
Convolution0.20000
Maximum error0.00e+0
Recurrent arithmetic stages2 (1 updates)
Parallel convolution stages1 (1 product + 0 sum)
Step through eight samples. Both outputs use the same readout convention and zero initial state. The counter compares scalar recurrence and direct convolution under an ideal stage model, not measured times.

For position tt, the figure counts t+1t+1 recurrent updates, each modeled as a sequential product and sum, with Bˉu\bar B u writes already calculated. In direct convolution it assumes the kernel already built: t+1t+1 products can occur in one stage and be reduced in ⌈log⁡2(t+1)⌉\lceil\log_2(t+1)\rceil addition stages. This is a depth model with enough processors and unit operations; it excludes total work, kernel construction, communication, and FFT costs. On real hardware a reduction and recurrence can have very different costs.

To avoid circular convolution, pad input and kernel to at least 2T−12T-1 before multiplying their FFTs and retain the first TT outputs. In a complex diagonal SSM, conjugate pairs yield real output if BB and CC also respect that symmetry. The cell verifies recurrence, direct convolution, and FFT, including λ=0\lambda=0.

An unpadded length-TT FFT gives circular convolution: contributions beyond the end wrap to the start. That wrap introduces a false dependency on the end at early positions. Padding to 2T−12T-1 holds the complete linear convolution of two length-TT vectors; then crop the desired causal portion. The next power of two can be chosen for implementation convenience, but the mathematical requirement is minimum length, not always a power of two.

With complex poles, mode λ=a+iω\lambda=a+i\omega contributes an oscillation whose amplitude decays or grows according to aa. Including the conjugate and conjugate coefficients makes their sum real. Discarding the imaginary part of a system without that symmetry can hide a parameterization error; the example therefore defines explicit pairs. The additional zero pole checks the ZOH limit and is marginal, not an example of strict asymptotic stability.

[ ]Diagonal SSM, recurrence, and FFTBrowser
import numpy as np

def discretize(lam,B,delta):
    lam=np.asarray(lam,dtype=complex); B=np.asarray(B,dtype=complex)
    abar=np.exp(delta*lam)
    scale=np.empty_like(lam)
    nonzero=np.abs(lam)>1e-12
    scale[nonzero]=np.expm1(delta*lam[nonzero])/lam[nonzero]
    scale[~nonzero]=delta
    return abar,scale*B

def ssm_kernel(lam,B,C,delta,T):
    a,b=discretize(lam,B,delta)
    return np.real(np.sum(C[:,None]*b[:,None]*a[:,None]**np.arange(T),axis=0))

lam=np.array([-.4+1.2j,-.4-1.2j,0j]);B=np.array([.7+.2j,.7-.2j,1.]);C=np.array([.3-.1j,.3+.1j,.2])
delta=.1; T=64; a,b=discretize(lam,B,delta)
rng=np.random.default_rng(18); u=rng.normal(size=T); x=np.zeros(3,dtype=complex); recurrent=[]
for value in u:
    x=a*x+b*value; recurrent.append(np.real(C @ x))
kernel=ssm_kernel(lam,B,C,delta,T)
direct=np.convolve(u,kernel)[:T]
size=1 << (2*T-2).bit_length()
fft=np.fft.ifft(np.fft.fft(u,size)*np.fft.fft(kernel,size)).real[:T]
print('error recurrencia/convolución:',np.max(np.abs(np.array(recurrent)-direct)))
print('error FFT/directa:',np.max(np.abs(fft-direct)),'tamaño FFT:',size)
assert np.allclose(recurrent,direct,atol=1e-12) and np.allclose(fft,direct,atol=1e-12)
assert np.isclose(b[-1],delta)
print('escalar a=-1, b=1, Δ=.1:',np.exp(-.1),-np.expm1(-.1))

Projecting history

HiPPO proposes retaining coefficients of past-signal projection onto a polynomial basis with respect to a time-changing measure. In HiPPO-LegS, the measure weights the entire observed interval uniformly and uses rescaled Legendre polynomials. Coefficient dynamics depend explicitly on time; this is not the same invariant system as the preceding convolution.

A projection with NN coefficients chooses the best polynomial of degree below NN for the defined norm and measure, not an exact copy of an arbitrary signal. Reconstruction sums coefficients times basis functions. A signal with abrupt changes or high frequency may need many coefficients; as the historical interval grows, the rescaled basis must represent an increasingly long history. “Optimal” refers to that projection problem, not every classification or language task.

Conceptually, an orthogonal basis lets each coefficient summarize a signal direction rather than storing one isolated sample. A constant signal is represented by the first ideal component; a trend needs additional components and a very irregular sequence can leave considerable energy outside a small basis. A later readout may care only about part of that information. Optimizing reconstruction error for all history and optimizing a particular prediction are distinct problems: the first can spend capacity on details the second never uses.

In the figure, continuous LegS dynamics have form c˙(t)=(−Ac(t)+Bf(t))/t\dot c(t)=(-Ac(t)+Bf(t))/t, with lower-triangular AA and Bn=2n+1B_n=\sqrt{2n+1}. The control approximates each step by freezing 1/t1/t and applying the bilinear rule; it starts at zero state. Its coefficients thus approximate the projection and should not be confused with an exact integral. An independent check with N=6N=6 and 128 samples gives approximate squared error 0.0244 for reconstruction of this signal, versus 0.2593 when drawing the EMA as a constant.

The figure implements a bilinear discretization of LegS dynamics for a fixed signal with NN coefficients. It reconstructs the past with the polynomial basis and compares one exponential moving average drawn as constant across the interval. These memories have different component counts and objectives; comparison illustrates reconstruction, not that HiPPO is best for every task. Error includes discretization and the chosen signal.

InteractiveRemembering with polynomial coefficients
startcurrent

■ Signal ■ LegS ■ EMA

6
128
Squared reconstruction error0.0244
Constant EMA error0.2593
Change coefficient count and observed length. The signal is explicit and LegS dynamics are approximated by the bilinear rule; EMA uses one state and coefficient 0.05.

S4, diagonalization, and stability

S4 exploits state-matrix structure to calculate long kernels efficiently. A diagonal SSM simplifies matrix powers to powers of each pole. S4D studies diagonal variants and initialization; S4D-Lin, for example, initializes continuous poles with negative real part and staggered imaginary frequencies. LRU uses a complex diagonal linear recurrence parameterized for stability and gradients. These families are not identical or reducible to any randomly chosen diagonal matrix.

As a learning control, the next cell fixes 16 stable complex poles and fits only a linear readout to copy an input delayed 24 steps. Validation sequences differ from those used to fit the readout. It uses regularized least squares, not training every S4D parameter; loss indicates what this particular mode set can remember, not universal capacity.

[ ]Fit a readout for delayed copyingBrowser
import numpy as np
rng=np.random.default_rng(218)
T=64; delay=24; N=16
lam=-.05+1j*np.linspace(.04,2.8,N)
a=np.exp(lam); b=np.expm1(lam)/lam
def states(u):
    x=np.zeros((len(u),N),dtype=complex); out=[]
    for t in range(T):
        x=x*a[None,:]+u[:,t,None]*b[None,:]
        out.append(np.concatenate((x.real,x.imag),axis=1))
    return np.stack(out,axis=1)
train=rng.normal(size=(128,T)); valid=rng.normal(size=(64,T))
X=states(train)[:,delay:,:].reshape(-1,2*N)
y=train[:,:T-delay].reshape(-1)
weights=np.linalg.solve(X.T @ X+1e-3*np.eye(2*N),X.T @ y)
V=states(valid)[:,delay:,:].reshape(-1,2*N)
target=valid[:,:T-delay].reshape(-1)
baseline=np.mean(target**2); mse=np.mean((V @ weights-target)**2)
print('MSE de predecir cero:',baseline,'MSE de lectura ajustada:',mse)
assert np.isfinite(mse) and mse < baseline

With the cell’s seeds and parameters, validation produced MSE 0.0984 versus 1.0206 when predicting zero. The readout is fit on examples after the delay and evaluated on new sequences from the same Gaussian distribution; it does not prove exact copying or extrapolation to longer delays. Another mode count, regularization, or outlier distribution can change the result. Least-squares readout fitting also differs from gradient training of all matrices.

For a stable discrete diagonal matrix, each component is multiplied by its pole each step. Modulus much below one forgets quickly; near one can retain signal longer, though BB, CC, inputs, and gradient scales still matter. Modulus above one can amplify a perturbation without bound. In nonnormal matrices, even spectral radius below one can allow transient amplification; the earlier graph represents only a diagonal system.

Diagonalization also changes computation: for a scalar mode the kernel term is CiBˉiλˉijC_i\bar B_i\bar\lambda_i^j, without dense matrix multiplication per delay. This simplification alone does not say all diagonal methods have equal capacity or speed: initialization, step parameterization, channel mixing, and convolution implementation are part of the model. A complex pair represents two coupled real components that can oscillate; making all poles real removes that direct representation of damped oscillations.

During training, forward-dynamics stability and useful gradients are related but distinct conditions. Repeated multiplication by a pole of modulus 0.1 attenuates a perturbation and may also attenuate long-distance learning signal. A pole near one avoids some forgetting but accumulates effects over many steps. Inspect step and pole distributions, finiteness of activations and gradients, and length sensitivity rather than relying only on a stable-architecture label.

In S4D table 5, authors report 87.93% for S4D-Lin and 42.44% for the reference transformer on the Long Range Arena image task with that work’s configurations and evaluation. These are published results, not local-lab results or a law for every implementation. The original task converts CIFAR-10 to grayscale and processes 1024 pixels as a sequence; results also depend on splits, preprocessing, and training budget.

A small comparison with real images

The lab uses CIFAR-10, the image dataset for the LRA task, and processes each image as grayscale intensity sequence. The pipeline uses an explicit RGB combination and rounds to 256 levels; for T=64T=64 and T=256T=256 it downsamples by averaging, while T=1024T=1024 keeps the 32 by 32 pixels. Smaller resolutions are our own ablation. Splits use torchvision indices and do not claim to exactly reproduce TFDS order or the complete LRA protocol.

A diagonal SSM inspired by S4D and a two-block bidirectional transformer are trained from scratch, both with pixel embeddings and width 32. Their parameters, accuracy on 256 validation examples, time, and peak training memory are printed. Both see the same batches at each length; the training set has 2048 images and does not overlap validation. The SSM uses stable complex poles parameterized with negative real part, ZOH, and FFT convolution; it is an educational implementation, not the full paper code. The cell’s test compares FFT with explicit recurrence.

The experiment requires CUDA, PyTorch, and torchvision. The first run downloads official CIFAR-10 if absent from cifar10-data; ORYON_CIFAR_DIR chooses another folder and ORYON_STEPS changes updates, default 50. Forward/backward warmup precedes measurement, but time includes first AdamW initialization and batch transfers. Memory is total PyTorch-allocated peak during training, not traffic. One short run, one seed, and shared GPU cannot conclusively compare architectures; reducing resolution also changes available information.

The figure records a real RTX 3060 run with PyTorch 2.11.0+cu128 and 50 updates per combination. At T=1024T=1024, the SSM achieved 9.77% and transformer 8.98% on small validation, near the 10% expected by uniform guessing among ten classes. The SSM had 56330 parameters and transformer 58442. These barely trained models and shared-load times do not reproduce published LRA figures; they check the procedure and explore cost.

An additional 500-step run with the same initial batches and windows gave T=1024T=1024 accuracies of 11.33% and 16.02% respectively. The graph retains 50-step measurements; the longer trial remains small and does not justify a general architecture ranking. Repeating seeds and expanding data and training are needed to study quality, while a profiler may explain timing differences for these particular implementations.

Interpret the comparison through three separate questions. Accuracy counts correct answers on a fixed sample of 256 images, so one example corresponds to approximately 0.39 percentage points; it alone is not a precise generalization estimate. Time includes PyTorch-specific work such as batch preparation and optimization as well as model computation. Peak memory counts active allocations during that training run; it is not the persistent storage required by token-by-token recurrence at inference.

As TT grows, both models’ learned positional tables grow here too. That choice controls part of the comparison but makes total parameters vary with resolution and does not show a model able to directly extrapolate to arbitrary length. Full pixel sequence has fixed row-major order; attention is bidirectional because the goal is whole-image classification, while this SSM is causal and its classifier averages outputs. This affects what each architecture can mix and is another reason not to attribute an accuracy difference solely to memory mechanism.

InteractiveA short CIFAR-10 run
12.10642561024%

■ SSM diagonal ■ Transformer

Metric
2
Length1024
SSM diagonal9.77 %
Transformer8.98 %
Chance with 10 classes10 %
Switch between accuracy, 50-step time, and allocated peak. Shorter lengths are downsampled images, not merely shorter versions of the same intact input.
[ ]SSM and transformer on CIFAR-10Local GPU
import json, math, os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import CIFAR10

assert torch.cuda.is_available(), 'se necesita CUDA'
root=os.environ.get('ORYON_CIFAR_DIR','cifar10-data')
dataset=CIFAR10(root=root,train=True,download=True)
steps=int(os.environ.get('ORYON_STEPS','50'))
assert steps>0
train_n=2048; val_start=45000; val_n=256; batch=8
indices=np.r_[np.arange(train_n),np.arange(val_start,val_start+val_n)]
raw=torch.from_numpy(dataset.data[indices].copy()).float().permute(0,3,1,2)
gray=(.2989*raw[:,0]+.5870*raw[:,1]+.1140*raw[:,2]).unsqueeze(1)
labels=torch.tensor(np.asarray(dataset.targets)[indices],dtype=torch.long)

class DiagonalSSM(nn.Module):
    def __init__(self,width,N):
        super().__init__(); self.width=width; self.N=N
        self.log_real=nn.Parameter(torch.full((width,N),math.log(.5)))
        self.imag=nn.Parameter(torch.arange(N).float().repeat(width,1)*math.pi)
        self.log_dt=nn.Parameter(torch.full((width,1),math.log(.02)))
        self.cr=nn.Parameter(torch.randn(width,N)*.05); self.ci=nn.Parameter(torch.randn(width,N)*.05)
        self.D=nn.Parameter(torch.ones(width))
    def kernel(self,T):
        lam=-self.log_real.exp()+1j*self.imag
        dt=self.log_dt.exp(); a=torch.exp(dt*lam); b=torch.expm1(dt*lam)/lam
        C=torch.complex(self.cr,self.ci)
        t=torch.arange(T,device=lam.device)
        return 2*torch.real((C*b)[:,:,None]*a[:,:,None]**t).sum(dim=1)
    def forward(self,x):
        T=x.shape[1]; size=1 << (2*T-2).bit_length()
        k=self.kernel(T)
        u=x.transpose(1,2)
        y=torch.fft.irfft(torch.fft.rfft(u,n=size)*torch.fft.rfft(k,n=size)[None,:,:],n=size)[...,:T]
        return (y+self.D[None,:,None]*u).transpose(1,2)

class SSMBlock(nn.Module):
    def __init__(self,width,N):
        super().__init__(); self.n1=nn.LayerNorm(width); self.n2=nn.LayerNorm(width)
        self.ssm=DiagonalSSM(width,N); self.mix=nn.Linear(width,width)
        self.ff=nn.Sequential(nn.Linear(width,2*width),nn.GELU(),nn.Linear(2*width,width))
    def forward(self,x):
        x=x+self.mix(F.gelu(self.ssm(self.n1(x))))
        return x+self.ff(self.n2(x))

class Model(nn.Module):
    def __init__(self,kind,T):
        super().__init__(); width=32
        self.embedding=nn.Embedding(256,width);self.position=nn.Parameter(torch.zeros(1,T,width))
        if kind=='ssm': self.layers=nn.ModuleList([SSMBlock(width,16) for _ in range(2)])
        else: self.layers=nn.ModuleList([nn.TransformerEncoderLayer(width,4,64,dropout=0.,batch_first=True,norm_first=True) for _ in range(2)])
        self.norm=nn.LayerNorm(width); self.head=nn.Linear(width,10)
    def forward(self,x):
        x=self.embedding(x)+self.position
        for layer in self.layers: x=layer(x)
        return self.head(self.norm(x).mean(dim=1))

# Verifica la convolución FFT de un canal frente a una recurrencia explícita.
torch.manual_seed(8)
check=DiagonalSSM(1,4).cuda(); seq=torch.randn(2,12,1,device='cuda')
with torch.no_grad():
    lam=-check.log_real.exp()+1j*check.imag;dt=check.log_dt.exp()
    a=torch.exp(dt*lam);b=torch.expm1(dt*lam)/lam; C=torch.complex(check.cr,check.ci)
    state=torch.zeros((2,1,4),device='cuda',dtype=torch.complex64); direct=[]
    for t in range(12):
        state=a[None,:,:]*state+b[None,:,:]*seq[:,t,:,None]
        direct.append(2*(C[None,:,:]*state).real.sum(-1)+check.D[None,:]*seq[:,t,:])
    error=(check(seq)-torch.stack(direct,dim=1)).abs().max().item()
    print('error máximo FFT/recurrencia:',error)
    assert error<1e-5
del check,seq,state,direct

records=[]
for side in (8,16,32):
    if side==32: resized=gray
    else: resized=F.avg_pool2d(gray,kernel_size=32//side)
    pixels=resized.round().clamp(0,255).long().reshape(len(indices),side*side)
    generator=torch.Generator().manual_seed(310)
    choices=torch.randint(train_n,(steps,batch),generator=generator)
    for kind in ('ssm','transformer'):
        torch.manual_seed(47); model=Model(kind,side*side).cuda();opt=torch.optim.AdamW(model.parameters(),lr=.001)
        warm_x=pixels[choices[0]].cuda();warm_y=labels[choices[0]].cuda()
        F.cross_entropy(model(warm_x),warm_y).backward();opt.zero_grad(set_to_none=True)
        torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats();start=time.perf_counter()
        for ids in choices:
            xx=pixels[ids].cuda();yy=labels[ids].cuda()
            opt.zero_grad(set_to_none=True); loss=F.cross_entropy(model(xx),yy)
            loss.backward();opt.step()
        torch.cuda.synchronize(); elapsed=time.perf_counter()-start
        peak=torch.cuda.max_memory_allocated()/2**20
        model.eval(); correct=0; val_loss=0.
        with torch.no_grad():
            for j in range(train_n,train_n+val_n,16):
                xx=pixels[j:j+16].cuda();yy=labels[j:j+16].cuda(); logits=model(xx)
                correct+=(logits.argmax(-1)==yy).sum().item()
                val_loss+=F.cross_entropy(logits,yy,reduction='sum').item()
        assert torch.isfinite(loss).item() and math.isfinite(val_loss)
        row={'model':kind,'side':side,'T':side*side,'steps':steps,
             'train_size':train_n,'validation_size':val_n,'accuracy':correct/val_n,
             'validation_loss':val_loss/val_n,'seconds':elapsed,'peak_mib':peak,
             'parameters':sum(p.numel() for p in model.parameters())}
        records.append(row); print(row,flush=True)
        del model,opt,loss,xx,yy,logits,warm_x,warm_y
Path('cifar-ssm-results.json').write_text(json.dumps(records,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
With a = -1, b = 1, and Δ = 0.1, what is Ā under zero-order hold?
Numeric
In the same system, what is B̄?
Proof
Prove: Prove that an invariant SSM with zero initial state produces a causal convolution.
0
Output is read after incorporating uₜ: xₜ₊₁ = Āxₜ + B̄uₜ, yₜ = Cxₜ₊₁ + Duₜ.

Step 1 of 3. What is the state after the first input?

Quiz
If A, B, and C change with each input, can one fixed-kernel convolution be used directly?
Quiz
To generate a new token in an invariant diagonal SSM, what is usually stored and updated?
Quiz
To convolve two length-T vectors by FFT without wrapping the end to the start, what minimum padded length is needed?
Code
Implement ssm_kernel(Lambda, B, C, Delta, T) for a diagonal SSM with ZOH. Return the T complex values Kⱼ = Σ Cᵢ Āᵢʲ B̄ᵢ; Lambda = 0 uses the Delta limit.
import numpy as np
def ssm_kernel(Lambda, B, C, Delta, T):
  pass
Shift+Enter to run
Key idea
The same invariant linear dynamics admit a fixed-state recurrence and a causal convolution. Discretization, stability, and invariance assumptions determine when that equivalence is useful.