You want a model to read a long document without losing the context near its beginning. Giving it more tokens sounds like a natural solution, but ordinary softmax attention compares tokens in pairs, so the work grows quickly as the document gets longer. Linear attention and state-space models explore ways to carry information through the sequence at a lower cost. Doubling the length quadruples the pairwise attention work and the stored score matrix.
We measure whether avoiding those pairwise comparisons changes the growth in work. Forward-pass time has log-log slope 2.03 for softmax attention, against 0.98 for linear attention and about one for the SSM. Building both alternatives in PyTorch traces the recurrent state behind those cost curves.
Let's Build It
Click the badge to open the full, runnable notebook in Google Colab:
Here are two causal sequence mixers. The first is ordinary softmax attention, which builds the score matrix. The second is linear attention, which never does.
import math, torch
import torch.nn.functional as F
def softmax_attention_causal(q, k, v):
"""Standard causal attention. q,k,v: (B, H, T, d). O(T^2) time and memory."""
d = q.shape[-1]
scores = q @ k.transpose(-1, -2) / math.sqrt(d) # (B, H, T, T) <- quadratic
T = q.shape[-2]
causal = torch.tril(torch.ones(T, T, dtype=torch.bool, device=q.device))
scores = scores.masked_fill(~causal, float("-inf"))
return scores.softmax(dim=-1) @ v
def feature_map(x):
return F.elu(x) + 1.0 # positive map phi(x)
def linear_attention_causal(q, k, v, chunk=128, eps=1e-6):
"""Causal linear attention via a chunked scan. q,k,v: (B, H, T, d). O(T)."""
B, H, T, d = q.shape
qf, kf = feature_map(q), feature_map(k)
out = torch.empty_like(v)
S = torch.zeros(B, H, d, v.shape[-1], device=q.device) # KV state (d x d)
z = torch.zeros(B, H, d, device=q.device) # normaliser state
for s in range(0, T, chunk):
e = min(s + chunk, T)
qc, kc, vc = qf[:, :, s:e], kf[:, :, s:e], v[:, :, s:e]
att = qc @ kc.transpose(-1, -2)
att = att.masked_fill(~torch.tril(torch.ones(e - s, e - s,
dtype=torch.bool, device=q.device)), 0.0) # causal within chunk
num = att @ vc + qc @ S # intra + carried state
den = att.sum(-1, keepdim=True) + (qc * z.unsqueeze(2)).sum(-1, keepdim=True)
out[:, :, s:e] = num / (den + eps)
S = S + kc.transpose(-1, -2) @ vc # advance the state
z = z + kc.sum(dim=2)
return out
Now time both across growing sequence lengths and plot the result:
import time
H, d = 8, 64
for T in [128, 256, 512, 1024, 2048, 4096]:
q, k, v = (torch.randn(1, H, T, d) for _ in range(3))
t0 = time.perf_counter(); softmax_attention_causal(q, k, v)
t_soft = time.perf_counter() - t0
t0 = time.perf_counter(); linear_attention_causal(q, k, v)
t_lin = time.perf_counter() - t0
print(f"T={T:>5} softmax {t_soft*1e3:7.1f} ms linear {t_lin*1e3:6.1f} ms")

The plot tells the whole story (the third curve, a diagonal state-space model, we build later in the post). On a laptop CPU, softmax attention fits a log-log slope of (genuine ) while linear attention sits at (genuine ). At 128 tokens softmax is faster, because linear attention carries some bookkeeping overhead. The two cross near 256 to 512 tokens, and from there the gap widens fast: at 4,096 tokens softmax takes about 298 ms against 18 ms for linear attention, a 17x difference, and the softmax score matrix alone needs 537 MB against 0.13 MB for the linear state, a factor of 4,096. You just watched the quadratic curve get overtaken.
What Just Happened?
The whole difference comes down to the order in which you multiply three matrices.
The associativity trick
Softmax attention computes . The term is an matrix: every query dotted with every key. That matrix is the quadratic cost, and the softmax sits in the middle so you cannot avoid building it.
Linear attention drops the softmax and replaces it with a positive feature map applied to and separately. Once the softmax is gone, the operation is three plain matrix multiplications, and matrix multiplication is associative. You are free to multiply first:
The left grouping builds the matrix. The right grouping builds , which is : its size depends on the head dimension, not the sequence length. For a 64-dimensional head, that state is a fixed 64 by 64 no matter whether the sequence has 500 tokens or 500,000.

The feature_map we used is , the choice from Katharopoulos et al. Its only job is to stay positive so the attention weights and their normaliser stay positive, the property softmax otherwise guarantees.
Attention as a recurrent network
Write the right-hand grouping out token by token and something familiar appears. Define the running state . Then the output at position is , and the state obeys a one-line update:
def linear_attention_recurrent(q, k, v):
"""The same computation as an explicit RNN: one state update per token."""
B, H, T, d = q.shape
qf, kf = feature_map(q), feature_map(k)
S = torch.zeros(B, H, d, v.shape[-1])
z = torch.zeros(B, H, d)
outs = []
for t in range(T):
S = S + kf[:, :, t].unsqueeze(-1) * v[:, :, t].unsqueeze(-2) # outer product
z = z + kf[:, :, t]
num = (qf[:, :, t].unsqueeze(-1) * S).sum(-2)
outs.append(num / ((qf[:, :, t] * z).sum(-1, keepdim=True) + 1e-6))
return torch.stack(outs, dim=2)
This produces the same numbers as the chunked version above (they agree to within in the notebook), but it exposes the duality: linear attention is a linear recurrent network. During training you use the parallel form, one big matmul over all tokens at once. During generation you use the recurrent form, carrying a fixed-size state and paying memory per new token instead of re-reading a cache that grows with every token. That inference-time property is the same problem the KV cache exists to manage, and it connects to the MQA, GQA and MLA tricks that shrink attention's cache. Linear attention removes the growing cache entirely.

Going Deeper
Linear attention gives up something to buy that speed. A fixed state is a lossy summary of the past, so it can blur together information that full attention keeps separate. State-space models attack the same linear-time goal from a different tradition and give you a sharper knob on what the state remembers.
The state-space recurrence
A state-space model is the equation an engineer writes for any linear dynamical system: a hidden state evolves, and you read out an observation from it.
decides how the state carries forward (what it remembers and how fast it forgets), writes the current input into the state, and reads the output back out. If you have seen the Hidden Markov Model, this is its continuous-state cousin: the same "state carries the past" idea without the discrete states. S4 gives a structured form (diagonal in its simplest variants) and initialises it with the HiPPO theory so the state can hold long-range history without exploding or vanishing.
Because , and are fixed, a classical SSM is linear and time-invariant, which means the whole layer is a convolution. You can precompute an impulse-response kernel and apply it with an FFT, exactly the convolution-and-Fourier machinery. That is the SSM's second face: a recurrence for -memory generation, a convolution for parallel training. The green curve in the first plot is this convolutional form, and it tracks the same near-linear slope as linear attention.
Selectivity: the Mamba idea
A time-invariant SSM has one weakness. Because , and never change, the layer processes every token with the same dynamics. It cannot decide, based on what it just read, to store this token and ignore the next. That kind of content-based routing is exactly what a lookup needs.
Mamba's one change fixes it: make , and the discretisation step functions of the input. The state update becomes input-dependent, so the model can choose what to keep. The cost is that the layer is no longer a fixed convolution (it now needs a scan), which is why the Mamba paper spends its engineering on a hardware-aware parallel scan.
Here is a minimal diagonal SSM with a selective switch. Set it to False and you get a classical time-invariant SSM; set it to True and , and come from a linear projection of the input.
import torch.nn as nn
class DiagonalSSM(nn.Module):
def __init__(self, d_model, d_state=16, selective=True):
super().__init__()
self.d_state, self.selective = d_state, selective
self.A_log = nn.Parameter(torch.log(torch.rand(d_model, d_state) * 0.5 + 0.5))
self.D = nn.Parameter(torch.zeros(d_model)) # skip connection
if selective:
self.x_proj = nn.Linear(d_model, 2 * d_state + 1) # -> B_t, C_t, delta_t
else:
self.B = nn.Parameter(torch.randn(d_model, d_state) * 0.1)
self.C = nn.Parameter(torch.randn(d_model, d_state) * 0.1)
self.delta = nn.Parameter(torch.zeros(d_model))
def forward(self, x): # x: (batch, T, d_model)
B_, T, D = x.shape
A = -torch.exp(self.A_log) # diagonal, negative
if self.selective:
proj = self.x_proj(x)
Bm, Cm = proj[..., :self.d_state], proj[..., self.d_state:2 * self.d_state]
delta = F.softplus(proj[..., -1:])
dA = torch.exp(delta.unsqueeze(-1) * A) # input-dependent decay
dBx = (delta.unsqueeze(-1) * Bm.unsqueeze(2)) * x.unsqueeze(-1)
h = torch.zeros(B_, D, self.d_state)
ys = []
for t in range(T):
h = dA[:, t] * h + dBx[:, t] # selective state update
ys.append((Cm[:, t].unsqueeze(1) * h).sum(-1))
y = torch.stack(ys, dim=1)
else:
delta = F.softplus(self.delta)
dA, dB = torch.exp(delta.unsqueeze(-1) * A), delta.unsqueeze(-1) * self.B
h = torch.zeros(B_, D, self.d_state)
ys = []
for t in range(T):
h = dA * h + dB * x[:, t].unsqueeze(-1) # fixed dynamics
ys.append((self.C * h).sum(-1))
y = torch.stack(ys, dim=1)
return y + x * self.D
To see why selectivity matters, train both variants on a small associative-recall task: show the model a handful of key-value pairs, then a query key, and ask it to return the matching value. Answering needs content-based lookup, the exact thing a fixed convolution cannot do. The GIF shows both models' recall accuracy climbing during training.

# both models are identical except for the `selective` flag; ~8,900 params each
sel = SSMClassifier(vocab, d_model=64, d_state=16, n_layers=2, selective=True)
lti = SSMClassifier(vocab, d_model=64, d_state=16, n_layers=2, selective=False)
# ... train each for 800 steps on associative-recall batches ...
print(f"selective recall : {eval_acc(sel)*100:.0f}%") # 100%
print(f"non-selective : {eval_acc(lti)*100:.0f}%") # 41%

The selective SSM solves the task outright at 100%. The time-invariant one climbs to 41%, well above the 12.5% chance line (it learns some structure), but it cannot route information by content, so it stalls. Input-dependence is the single change that separates them.
Hyperparameters and when to reach for these
Three settings shape a state-space layer. The state size (here 16) is how much the state can hold; larger remembers more at more cost. The discretisation step , passed through a softplus so it stays positive, sets the effective timescale: small makes the state forget slowly, large makes it react fast. The diagonal is parameterised as so its entries stay negative, which keeps the recurrence stable (the state decays rather than blows up).
Reach for linear attention or an SSM when the sequence is long and throughput or memory is the bottleneck: long-document modelling, audio, genomics, high-throughput serving. Stay with full softmax attention, or a hybrid that keeps a few attention layers, when the task leans on precise recall over a short-to-medium context, where the quadratic matrix still wins on quality. Most shipping "Mamba" models are in fact hybrids for this reason. The same efficiency-versus-quality tension drives the parallel-decoding and KV-sharing tricks.
Where This Comes From
Four papers trace the line from quadratic attention to linear-time selective models.

Katharopoulos, Vyas, Pappas & Fleuret (2020), "Transformers are RNNs", removed the softmax and made the associativity trick explicit. Their framing is the one we built:
"We express the self-attention as a linear dot-product of kernel feature maps and make use of the associativity property of matrix products to reduce the complexity from to ."
They also derived the recurrent form, showing a transformer with linear attention is a recurrent network you can run token by token at constant memory.
Gu, Goel & Ré (2022), "Efficiently Modeling Long Sequences with Structured State Spaces" (S4), brought the state-space equation into deep learning. Their contribution was the HiPPO structure on , which lets a diagonal-plus-low-rank state compress long histories, together with the convolutional view that makes training parallel.
Gu & Dao (2023), "Mamba: Linear-Time Sequence Modeling with Selective State Spaces", added selectivity. Their diagnosis names the exact failure we reproduced:
"We identify that a key weakness of prior models is the ability to perform content-based reasoning."
Making , and input-dependent broke the convolutional form, so they wrote a hardware-aware selective scan to keep the layer fast on a GPU. Yang, Wang, Shen, Panda & Kim (2024), "Gated Linear Attention", closed the loop by showing linear attention and SSMs are two dialects of the same gated-recurrence idea, with a chunked-parallel training algorithm much like the one in our linear_attention_causal.
The through-line: attention, linear attention and state-space models are all ways to mix a sequence, trading off how much the past is compressed against how cheaply you can process it. Once you see the recurrence hiding inside attention, the whole family falls into place.
Interactive Tools
- Attention Visualizer: The quadratic score matrix these architectures set out to remove. Every query meets every key, and the grid grows with the square of the sequence length.
- 2D Convolution Visualizer: See how a kernel slides across a signal, the exact operation behind an SSM's convolutional training form.
- LLM Cost Calculator: The quadratic-attention wall is what makes long-context inference expensive; estimate the token costs these architectures aim to cut.
- Markov Chain Simulator: A state-space model is the continuous-state cousin of a Markov chain; watch how a state evolves under fixed transition dynamics.
Related Posts
For a constructed attention example, transformer without training tests what hand-set weights can compute.
For recurrent sequence models, LSTM from scratch measures how forget bias affects retention over 100 steps.
Vision Transformers from Scratch: The softmax-attention architecture these models set out to replace.
Shrinking the KV Cache: MQA, GQA, and Multi-Head Latent Attention: The other route to cheaper attention: keep softmax, shrink its cache.
Parallel LLM Decoding: Speculative and Diffusion: More ways to break attention's sequential, quadratic cost at inference.
Fourier Transform for Time Series Forecasting: The convolution-and-FFT machinery behind an SSM's parallel form.
Hidden Markov Models: When Clusters Have Memory: The classical state-space model with discrete states.
Next-Latent Prediction: Autoregression in Latent Space: Both step away from token-by-token softmax attention. One predicts latents, the other replaces attention with a recurrence.








