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 n × n 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 2.03 (genuine O(n²)) while linear attention sits at 0.98 (genuine O(n)). 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 softmax(QKᵀ)V. The QKᵀ term is an n × n 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 Q and K separately. Once the softmax is gone, the operation is three plain matrix multiplications, and matrix multiplication is associative. You are free to multiply φ(K)ᵀ V first:

The left grouping builds the n × n matrix. The right grouping builds φ(K)ᵀ V, which is d × d: 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 φ(x) = elu(x) + 1, 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 Sₜ = Σ_s ≤ t φ(k_s) v_sᵀ. Then the output at position t is φ(qₜ)ᵀ Sₜ, 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 2 × 10⁻⁷ 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 O(1) 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 d × d 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.

A decides how the state carries forward (what it remembers and how fast it forgets), B writes the current input into the state, and C 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 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 A, B and C 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 bar K_ℓ = C A^(ℓ) B and apply it with an FFT, exactly the convolution-and-Fourier machinery. That is the SSM's second face: a recurrence for O(1)-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 A, B and C 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 B, C 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 B, C 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 N (here 16) is how much the state can hold; larger N 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 A is parameterised as -exp(A_log) 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 O(N²) to O(N)."
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 A, 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 B, C 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.
- 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
Frequently Asked Questions
What is linear attention and how is it different from softmax attention?
Linear attention replaces the softmax in softmax(QKᵀ)V with a positive feature map applied to Q and K separately. That removes the n × n score matrix and lets you reorder the multiplication into φ(Q)(φ(K)ᵀ V), which runs in O(n) time and constant memory in the sequence length. The tradeoff is that its fixed-size state is a lossy summary of the past, so it can be less precise than full attention on recall-heavy tasks.
What is a state-space model in deep learning?
A state-space model (SSM) carries a hidden state through a linear recurrence hₜ = A hₜ₋₁ + B xₜ and reads out yₜ = C hₜ. When A, B and C are fixed the layer is equivalent to a convolution, so you can train it in parallel with an FFT and run it as a constant-memory recurrence at inference. S4 and Mamba are the deep-learning incarnations of this classical equation.
What makes Mamba different from S4?
S4 is time-invariant: its A, B and C are the same at every position, which makes it a fixed convolution but blind to content. Mamba makes B, C and the step size Δ depend on the input, so the model can decide what to store and what to skip. That selectivity is what lets it solve content-based tasks like associative recall, at the cost of needing a custom parallel scan instead of a convolution.
Not outright. On long sequences where memory and throughput dominate they are far cheaper, but full softmax attention still tends to win on tasks that need precise recall over short-to-medium contexts. Most production "Mamba" systems are hybrids that interleave a few attention layers with SSM layers to get both the linear-time bulk and attention's sharp lookup.
Why is softmax attention O(n²) in the first place?
Softmax attention compares every token with every other token, producing an n × n matrix of scores before the softmax normalises each row. Building and storing that matrix costs time and memory proportional to n², so doubling the sequence length quadruples both. The softmax sits between QKᵀ and V, which is what prevents you from reordering the multiplication to avoid the matrix.