Beyond Attention: Linear Attention & Mamba SSMs

Build linear attention and a diagonal state-space model (Mamba) from scratch in PyTorch, and watch the O(n²) attention cost curve bend to O(n).

Cover Image for Beyond Attention: Linear Attention & Mamba SSMs

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:

Open In Colab

Here are two causal sequence mixers. The first is ordinary softmax attention, which builds the n×nn \times 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")

Left: forward-pass time versus sequence length on log-log axes; softmax attention has slope 2.03 while linear attention and the diagonal SSM sit near slope 1. Right: peak interaction memory; the softmax score matrix grows quadratically while the linear and SSM state stays flat.

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.032.03 (genuine O(n2)O(n^2)) while linear attention sits at 0.980.98 (genuine O(n)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\text{softmax}(QK^\top)V. The QK⊤QK^\top term is an n×nn \times 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 ϕ\phi applied to QQ and KK 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\phi(K)^\top V first:

(ϕ(Q) ϕ(K)⊤)V  =  ϕ(Q)(ϕ(K)⊤V)\big(\phi(Q)\,\phi(K)^\top\big)V \;=\; \phi(Q)\big(\phi(K)^\top V\big)

The left grouping builds the n×nn \times n matrix. The right grouping builds ϕ(K)⊤V\phi(K)^\top V, which is d×dd \times 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.

Two panels showing the same three matrices multiplied in two orders. Left, softmax groups Q times K-transpose first and builds an n by n matrix marked O(n squared). Right, linear attention groups K-transpose times V first and builds a d by d state marked O(n).

The feature_map we used is ϕ(x)=elu(x)+1\phi(x) = \text{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 St=∑s≤tϕ(ks)vs⊤S_t = \sum_{s \le t} \phi(k_s) v_s^\top. Then the output at position tt is ϕ(qt)⊤St\phi(q_t)^\top S_t, 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−72 \times 10^{-7} 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)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.

Two views of one computation. Left, the parallel training view: all four token positions feed a single matmul phi(Q) times phi(K)-transpose times V. Right, the recurrent inference view: a fixed-size state S is carried from token to token, each producing one output, labelled O(1) memory per step.

Going Deeper

Linear attention gives up something to buy that speed. A fixed d×dd \times 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.

ht=Aht−1+Bxt,yt=Chth_t = A h_{t-1} + B x_t, \qquad y_t = C h_t

AA decides how the state carries forward (what it remembers and how fast it forgets), BB writes the current input into the state, and CC 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 AA 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 AA, BB and CC 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 Kˉℓ=CAℓB\bar K_\ell = C A^\ell 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)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 AA, BB and CC 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 BB, CC and the discretisation step Δ\Delta 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 BB, CC and Δ\Delta 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.

Animated learning curves. The selective SSM climbs to 100 percent recall accuracy by around 250 steps while the non-selective SSM plateaus near 41 percent, both starting from the 12.5 percent chance line.

# 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%

Bar chart of final recall accuracy: the non-selective LTI model reaches 41 percent while the selective Mamba-style model reaches 100 percent, both above the 12.5 percent chance line.

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 NN (here 16) is how much the state can hold; larger NN remembers more at more cost. The discretisation step Δ\Delta, passed through a softplus so it stays positive, sets the effective timescale: small Δ\Delta makes the state forget slowly, large Δ\Delta makes it react fast. The diagonal AA is parameterised as −exp⁡(A_log)-\exp(\text{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.

A timeline from Attention (2017, softmax QK-transpose, O(n squared)) to Linear Attention (2020, phi(Q) times phi(K)-transpose V, O(n) and equal to a linear RNN) to S4 (2022, structured SSM, HiPPO init, O(n log n)) to Mamba (2023, selective SSM, input-dependent, O(n)).

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(N2)O(N^2) to O(N)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 AA, 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 BB, CC and Δ\Delta 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.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions