S4 (Structured State Space sequence model) is a way to compute the state space model (SSM), long used in fields such as control engineering, quickly and stably as a layer of a deep learning sequence model. It was proposed by Gu et al. in 2021 in the paper "Efficiently Modeling Long Sequences with Structured State Spaces" and presented at ICLR 2022.
Each of the earlier models for sequences had weaknesses on long sequences.
RNN and LSTM: time steps are computed one by one in order, so training cannot be parallelized, and dependencies between distant time steps are hard to learn because of vanishing gradients.
CNN: seeing farther than the kernel width requires stacking many layers.
Transformer: the computation and memory of attention grow with the square of the sequence length, making sequences longer than 10,000 steps hard to handle.
Before S4, LSSL (Linear State Space Layer) from the same group had shown that an SSM using a special matrix called the HiPPO matrix can learn long-range dependencies. However, LSSL requires O(N2L) computation and O(NL) memory for state size N and sequence length L, which was too heavy for practical use.
By representing the HiPPO matrix in the form "normal matrix â low-rank matrix", S4 reduced this to O~(N+L) computation and O(N+L) memory. The paper reports that it is up to 30 times faster than LSSL and uses 1/400 of the memory. As a result, it became the first model to solve a task called Path-X, with sequences of length 16,384.
S4 was followed by Mamba, which changes the SSM parameters depending on the input; Mamba-2, which connects Mamba and linear attention in a single framework; and Hyena, which builds long convolutions directly instead of using an SSM.
Theory: three views of the state space model
At the core of S4 is a continuous-time state space model that maps a one-dimensional input signal u(t) to a one-dimensional output y(t) through an N-dimensional state x(t) (equation (1) of the paper). A,B,C,D are the learned parameters.
xâē(t)=Ax(t)+Bu(t),y(t)=Cx(t)+Du(t)
The Du term acts like a residual connection, so the paper omits it in the explanation (treating D=0). The steps to use this equation as a sequence model are as follows.
Initialize A with the HiPPO matrix: a random A performs poorly. The HiPPO matrix is derived from theory so that the state x(t) can remember the past history of the input (the equation below, equation (2) of the paper).
Discretize with step size Î: the sequence u0â,u1â,âĶ is regarded as samples of a continuous signal at interval Î (ukâ=u(kÎ)), and the bilinear transform converts A,B into the discrete AË,BË (equation (3) of the paper).
It can be computed in recurrent form: the discretized equation has the same form as an RNN that updates the state xkâ from the previous one.
It can also be computed in convolutional form: unrolling the recurrence, the output can be written as a convolution of the input with a single kernel K (equations (4)(5) of the paper).
HiPPO matrix (n,k are the row and column indices):
The right side of the figure at the top of the article shows these two forms. The recurrent form has per-step computation independent of the sequence length, so it suits inference that generates one step at a time. The convolutional form can compute the whole sequence at once with the FFT as long as the kernel K is known, so it suits training, where parallel computation is desired. The ability to switch how the same SSM is computed depending on the situation is the strength of SSMs.
According to the LSSL paper, simply changing the SSM's A from a random matrix to the HiPPO matrix raised the accuracy on sequential MNIST (classification reading pixels one at a time) from 60% to 98%. The S4 paper cites this result as evidence that HiPPO is effective for long-range dependencies.
The S4 technique: computing the kernel quickly
To use the convolutional form, the kernel K=(CAËiBË)i<Lâ must be computed. Computing it naively means multiplying by AËL times, which costs O(N2L). This was the source of LSSL's heavy cost.
If A were diagonal, powers would reduce to powers of the diagonal entries, and the computation would be much lighter. However, diagonalizing the HiPPO matrix directly makes the entries of the diagonalizing matrix grow exponentially in N (up to about 24N/3 according to Lemma 3.2 of the paper), so it cannot be computed numerically.
S4 solves this problem by combining the following three techniques (Section 3.2 and Algorithm 1 of the paper).
Split into normal plus low-rank form: the HiPPO matrix is not normal, but it can be split into "a normal matrix â a low-rank matrix" (Theorem 1 of the paper; the HiPPO matrix of equation (2) has rank 1). A normal matrix can be stably diagonalized by a unitary matrix, so A can be represented as "diagonal Î â low-rank PQâ".
Compute the kernel's frequency components instead of the kernel: the generating function of K is evaluated at the L-th roots of unity, and an inverse FFT recovers K. This replaces the powers of AË with a matrix inverse.
Remove the low-rank part with the Woodbury identity: reducing the computation to a diagonal matrix alone leaves a Cauchy kernel computation, which is well studied in numerical analysis and can be computed stably in nearly linear time.
As a result, the kernel computation needs only O~(N+L) computation and O(N+L) memory (Theorem 3 of the paper). In recurrent form, too, one step can be computed in O(N) (Theorem 2 of the paper). The learned parameters are the 5N (complex) values of Î,P,Q,B,C, plus the step size Î.
Use as a layer (Section 3.4 of the paper): since an SSM maps a one-dimensional sequence to a one-dimensional sequence, for an input with H features, H independent SSMs, one per feature, are used. A position-wise linear layer then mixes the H features, and a nonlinear activation function is placed between layers. The paper describes this as similar to a depthwise separable convolution whose kernel spans the whole sequence. The input and output shapes are (batch, sequence length, number of features), so it can be swapped in for a Transformer layer.
Why it can learn long-range dependencies
The reason S4 can learn long-range dependencies is the initialization with the HiPPO matrix, not the "normal plus low-rank" form used for fast computation itself.
HiPPO is a matrix designed so that the state x(t) keeps compressing and remembering the past history of a continuous-time signal as polynomial coefficients. As an analogy, it is a mechanism that keeps rewriting the story so far as "summary notes" in a notebook of fixed size, so old inputs are not lost from the state. The paper explains that since the solution of a simple linear ODE is exponential, with a random A the gradients tend to vanish or explode exponentially in the sequence length.
Section 4.4 of the paper verifies this on sequential CIFAR-10 (at most 100K parameters).
When A is trained, every initialization reaches 100% accuracy on the training data. However, the validation accuracy differed by more than 15% depending on the initialization. The HiPPO initialization gave the best result.
A randomly initialized "normal plus low-rank" A performs poorly. This shows that the effect of S4 comes mainly from the HiPPO initialization, not from the form used for fast computation.
S4 initialized with HiPPO reached 84.27% accuracy with dropout 0.1 added (100K parameters).
Looking at the kernels after training on Path-X (128 Ã 128 images turned into sequences of 16,384 pixels), the lower layers learned kernels that look only at a few nearby rows, and the upper layers learned kernels that span the whole sequence (16,384 pixels) (Figure 2 of the paper).
Experimental results
Long-sequence benchmark Long Range Arena (6 tasks with lengths 1,000â16,000, accuracy %. Table 4 of the paper)
â indicates insufficient memory or compute, or accuracy no better than chance (50%). S4 is the best on every task and was the first to solve Path-X, which no model had solved before. Note that in the latest version of the paper (the third version on arXiv), this table is updated with the results of S4 with slightly different hyperparameters from later work (Appendix D.5 of the paper).
Speech classification (Speech Commands, 10 classes, accuracy %. Table 5 of the paper)
Model
MFCC features (length 161)
Raw waveform (length 16,000)
Raw waveform, half sampling rate
Transformer
90.75
Not computable
Not computable
Performer
80.85
30.77
30.68
WaveGAN discriminator (CNN for audio)
â
96.25
â
S4
93.96
98.32
96.30
S4 classified directly from raw waveforms without hand-crafted MFCC features and reached 98.32%. Even when the sampling rate was halved at test time, simply doubling the step size Î kept the accuracy at 96.30% without retraining. This is an advantage of being built from a continuous-time model.
Language modeling (WikiText-103, Table 8 of the paper): replacing the attention layers of a strong Transformer baseline with S4 gave a test perplexity of 20.95 versus 20.51 for the Transformer (247M and 249M parameters respectively). It was the best among models without attention, and generation ran at 48,000 tokens per second, about 60 times faster than the Transformer.
Computational efficiency (Tables 2 and 3 of the paper): compared with LSSL, with 512 features one training step was 29.6 times faster and used 1/392 of the memory. At length 4,096, it was 5.19 times faster than the Transformer with 0.091 times the memory, about as efficient as linear attention and Performer.
Practical notes
Keep the following points in mind when using S4.
Use a small learning rate for the SSM parameters: the paper states that capping the learning rate of Î,P,Q,B,C,Î at 0.001 keeps training stable (Appendix D.2). Using the same learning rate as the other layers tends to destroy the initial properties built by HiPPO.
Compute the convolutional form with the FFT: the kernel K is as long as the sequence length L, so it is computed with the FFT rather than an ordinary convolution layer. S4's convolution is non-circular, so when using the FFT, pad to length 2L so that the ends do not wrap around to the other side.
Fast computation requires a dedicated implementation: the official implementation (state-spaces) has dedicated code for the Cauchy kernel computation. The naive computation that multiplies by AËL times, as in the implementation example below, is useful for checking the equations but becomes heavy for long sequences.
The paper's original form A=ÎâPQâ can become numerically unstable if the eigenvalues of A move into the right half of the complex plane during training. The latest version of the paper notes that later work (Goel et al., 2022) fixed this problem by changing it to ÎâPPâ. When implementing it yourself, use this corrected form.
S4's A,B,C,Î are constant regardless of the input (linear time-invariant). Therefore, the same kernel K is used for every input, and it cannot make content-dependent choices such as "ignore this word, remember that word". The Mamba paper showed that because of this property S4 is weak on tasks that select and copy specific symbols at distant positions and on discrete data such as language, and proposed making the parameters depend on the input.
Comparison with other models
Table 1 of the paper compares the computational cost of the main ways of mixing sequences (L is the sequence length, H is the number of features, and B is the batch size. For S4, the state size N is set equal to H. The tilde omits logarithmic factors).
Method
Parameters
Training compute
Training memory
Parallel training
Compute per inference step
Convolution (kernel spanning the whole sequence)
LH
L~H(B+H)
BLH
Yes
LH2
Recurrence (RNN)
H2
BLH2
BLH
No
H2
Attention
H2
B(L2H+LH2)
B(L2+HL)
Yes
L2H+H2L
S4
H2
BH(H~+L~)+BL~H
BLH
Yes
H2
S4 can be computed in parallel like a convolution in training, and at inference each step costs an amount independent of the sequence length, like an RNN.
Lining up sequence models that replace the Transformer from the same viewpoints gives the following.
For long sequences close to continuous signals, such as audio waveforms, time series, or pixel sequences: S4 is a good fit. Changes in sampling rate can be handled through Î.
When the model must choose what to remember or forget based on content, as in text: Mamba, whose parameters depend on the input, or the Transformer is a good fit.
When sequences are a few thousand steps long and a Transformer training setup already exists: first try a Transformer with a fast implementation such as FlashAttention.
PyTorch example
âķShow code
python
import math
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
"""
A small SSM layer that computes equations (1)-(5) of the S4 paper directly, and a model that stacks it
- A is initialized with the HiPPO matrix (eq. 2) and discretized with the bilinear transform (eq. 3)
- Training uses the convolutional form (eqs. 4 and 5, FFT); generation uses the recurrent form (eq. 3)
- The kernel K is built by multiplying by Ä L times (naive O(N^2 L) computation). For S4's actual fast computation
(normal plus low-rank, Cauchy kernel, FFT), use the official implementation state-spaces
Task: remember the first symbol of the sequence and answer at the end (a small example that needs no data download)
"""
# Hyperparameters
seq_len = 200 # time gap to remember
num_noise = 10 # number of noise symbol types (0-9)
num_classes = 2 # number of first-symbol types (A=10, B=11)
d_model = 64 # number of features H
d_state = 32 # state size N
n_layers = 2
batch_size = 64
steps = 1000
learning_rate = 1e-3
# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
def hippo_legs(N):
"""HiPPO matrix (eq. 2 of the paper). -sqrt(2n+1)sqrt(2k+1) for n > k, -(n+1) for n = k, 0 for n < k"""
n = torch.arange(N, dtype=torch.float32)
A = torch.sqrt(2 * n[:, None] + 1) * torch.sqrt(2 * n[None, :] + 1)
A = torch.tril(A, diagonal=-1) + torch.diag(n + 1)
return -A
class SSM(nn.Module):
"""Independent SSMs for each of the H features (B, C, Î are learned per feature; A is a fixed shared HiPPO matrix)"""
def __init__(self, H, N):
super().__init__()
self.register_buffer('A', hippo_legs(N))
self.B = nn.Parameter(torch.randn(H, N) / math.sqrt(N))
self.C = nn.Parameter(torch.randn(H, N) / math.sqrt(N))
self.D = nn.Parameter(torch.ones(H)) # residual-like term D u
# Keep the step size Î in log space (initialized spread over 0.001-0.1 as an example)
self.log_dt = nn.Parameter(torch.empty(H).uniform_(math.log(1e-3), math.log(1e-1)))
def discretize(self):
"""Bilinear transform (eq. 3 of the paper): Ä = (I - Î/2 A)^-1 (I + Î/2 A), BĖ = (I - Î/2 A)^-1 Î B"""
N = self.A.shape[0]
dt = self.log_dt.exp()[:, None, None] # [H, 1, 1]
I = torch.eye(N, device=self.A.device)
left = torch.linalg.inv(I - dt / 2 * self.A) # [H, N, N]
Ab = left @ (I + dt / 2 * self.A) # [H, N, N]
Bb = (left @ (dt * self.B[..., None])).squeeze(-1) # [H, N]
return Ab, Bb
def kernel(self, L):
"""Convolution kernel K = (C BĖ, C Ä BĖ, ..., C Ä^(L-1) BĖ) (eq. 5 of the paper)"""
Ab, Bb = self.discretize()
ks, x = [], Bb
for _ in range(L):
ks.append((self.C * x).sum(-1))
x = (Ab @ x[..., None]).squeeze(-1)
return torch.stack(ks, dim=-1) # [H, L]
def forward(self, u): # u: [B, H, L]
"""Convolutional form (for training). FFT with length 2L to make the convolution non-circular"""
L = u.shape[-1]
K = self.kernel(L)
y = torch.fft.irfft(torch.fft.rfft(u, n=2 * L) * torch.fft.rfft(K, n=2 * L), n=2 * L)[..., :L]
return y + self.D[:, None] * u
def step(self, u_t, x): # u_t: [B, H], x: [B, H, N]
"""Recurrent form (for generation). x_k = Ä x_{k-1} + BĖ u_k, y_k = C x_k + D u_k"""
Ab, Bb = self.discretize()
x = (Ab @ x[..., None]).squeeze(-1) + Bb * u_t[..., None]
y = (self.C * x).sum(-1) + self.D * u_t
return y, x
class S4Block(nn.Module):
"""Normalization -> SSM -> activation -> position-wise linear layer -> residual connection"""
def __init__(self, H, N, dropout=0.1):
super().__init__()
self.norm = nn.LayerNorm(H)
self.ssm = SSM(H, N)
self.act = nn.GELU()
self.drop = nn.Dropout(dropout) # active only in model.train()
self.out = nn.Linear(H, H) # mixes the H features
def forward(self, x): # x: [B, L, H]
z = self.norm(x).transpose(1, 2) # [B, H, L]
z = self.ssm(z).transpose(1, 2) # [B, L, H]
return x + self.drop(self.out(self.act(z)))
class S4Classifier(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(num_noise + num_classes, d_model)
self.blocks = nn.ModuleList([S4Block(d_model, d_state) for _ in range(n_layers)])
self.head = nn.Linear(d_model, num_classes)
def forward(self, tokens): # tokens: [B, L]
x = self.embed(tokens)
for blk in self.blocks:
x = blk(x)
return self.head(x[:, -1]) # answer at the last position
def make_batch(n):
label = torch.randint(0, num_classes, (n,))
noise = torch.randint(0, num_noise, (n, seq_len - 1))
x = torch.cat([(label + num_noise).unsqueeze(1), noise], dim=1) # put the answer symbol at the start
return x.to(device), label.to(device)
model = S4Classifier().to(device)
# Use a small learning rate for the SSM parameters (B, C, Î) (at most 0.001 in Appendix D.2 of the paper)
ssm_params = [p for n, p in model.named_parameters() if '.ssm.' in n and not n.endswith('.D')]
other_params = [p for n, p in model.named_parameters() if not ('.ssm.' in n and not n.endswith('.D'))]
optimizer = optim.AdamW([{'params': ssm_params, 'lr': 1e-3, 'weight_decay': 0.0},
{'params': other_params, 'lr': learning_rate}])
criterion = nn.CrossEntropyLoss()
model.train()
for step in tqdm(range(steps)):
x, y = make_batch(batch_size)
loss = criterion(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
x, y = make_batch(1000)
acc = (model(x).argmax(-1) == y).float().mean().item()
print(f'Accuracy: {acc:.3f}')
# Check that the two forms return the same output (SSM of the first layer)
ssm = model.blocks[0].ssm
u = torch.randn(2, d_model, 50, device=device)
y_conv = ssm(u) # convolutional form
state = torch.zeros(2, d_model, d_state, device=device)
y_rec = []
for t in range(50): # recurrent form (one step at a time)
y_t, state = ssm.step(u[..., t], state)
y_rec.append(y_t)
y_rec = torch.stack(y_rec, dim=-1)
print('Max difference between convolution and recurrence:', (y_conv - y_rec).abs().max().item())
FAQ
Q. Is S4 an RNN or a CNN?
A.
It is a linear state space model that can be computed as either. Updating the state xkâ=AËxkâ1â+BËukâ computes it like an RNN, and convolving with the unrolled kernel K=(CBË,CAËBË,âĶ) computes it like a CNN. The standard approach is to compute in parallel with the convolution in training and one step at a time with the recurrence in generation. Unlike an RNN, however, the state update is linear in the input, and nonlinear activations are placed between layers.
Q. Does the HiPPO matrix change during training?
A.
In S4, the HiPPO matrix is the initial value, and it then changes during training as Î,P,Q. Section 4.4 of the paper shows that training A is better than fixing it for every initialization, and that among those, the HiPPO initialization generalizes best.
Q. What does the step size $\Delta$ do?
A.
It represents the interval at which the input sequence is regarded as samples of a continuous signal (the time resolution). With a large Î, the state turns over quickly; with a small one, it persists longer. In the paper, when the sampling rate of the audio was halved, simply doubling Î kept the accuracy at 96.30% without retraining.