Skip to content
datarekha

Sparse & sub-quadratic attention

Beating O(n²) attention — sparse patterns, linear attention, and state-space models like Mamba, plus the hybrids (Jamba) that power today's long context.

Written and reviewed by Last reviewed

11 min read Advanced NLP & Transformers Lesson 26 of 44

What you'll learn

  • Why full attention's O(N²) is a wall, and the two distinct ways past it
  • Sparse patterns — sliding-window, global+local, dilated, block-sparse
  • Linear attention and state-space models (Mamba) — O(N) sequence mixers
  • The recall-vs-efficiency trade, and why hybrid (attention + SSM) models won

Before you start

FlashAttention made full attention cheaper to run without changing the math — but it’s still O(N²) in compute: every token attends to every other. At 100k+ tokens that quadratic wall returns. This lesson is about genuinely sub-quadratic attention — changing what gets computed, not just how memory is touched.

Escape 1 — sparsify the attention matrix

The N×N score matrix is mostly wasted: a token usually cares about its recent neighbours and a few special tokens, not all 100,000 others. So don’t compute the cells you don’t need. Each pattern below keeps only a fraction of the causal matrix lit — the lit cells (query rows down, key columns across) are the ones you actually pay for:

Sliding windowGlobal + localDilatedBlock-sparse~w keys / row · O(N·w)window + 1 global colevery k-th key, wide reachown block + previous8×8 causal matrix · lit = computed · global key column always attended
Each pattern keeps a small, structured slice of the full causal N×N — that is where the sub-quadratic cost comes from.

The workhorse patterns:

  • Sliding window (Mistral): each token attends to the last w tokens — O(N·w). One layer sees w back; stack L layers and the effective receptive field grows to L·w, exactly like depth in a CNN.
  • Global + local (Longformer, BigBird): most tokens stay local, but a handful of global tokens attend to (and are attended by) everyone — cheap long-range shortcuts. O(N).
  • Dilated: attend to every k-th token for wide reach at coarse resolution.
  • Block-sparse: attend within your block and the previous one — the GPU-friendly version, since blocks map cleanly to tiles.

The catch: a fixed sparsity pattern can miss a genuinely long-range dependency it didn’t budget for. That’s why the next escape is more radical.

Escape 2 — change the operator

Instead of pruning attention, replace it with a sequence mixer that’s linear by construction.

Linear attention rewrites softmax attention with a kernel feature map so you can use associativity: compute KᵀV first (a small d×d matrix), then Q(KᵀV). That reorder turns O(N²·d) into O(N·d²) — linear in sequence length. See the associativity that makes it possible:

import numpy as np

rng = np.random.default_rng(0)
N, d = 2000, 64
Q = rng.standard_normal((N, d)); K = rng.standard_normal((N, d)); V = rng.standard_normal((N, d))

# Quadratic order: (Q Kᵀ) V  ->  builds an N×N matrix
A = (Q @ K.T) @ V                 # O(N²·d) work, O(N²) memory

# Linear order: Q (Kᵀ V)  ->  builds only a d×d matrix
B = Q @ (K.T @ V)                 # O(N·d²) work, O(d²) memory

print("same result? ", np.allclose(A, B))
print("N×N matrix floats :", N*N, " vs  d×d floats:", d*d)
# Identical answer, but the linear order never forms the N×N matrix.
# (Real linear attention applies a feature map φ so softmax ≈ φ(Q)φ(K)ᵀ — same trick.)
same result?  True
N×N matrix floats : 4000000  vs  d×d floats: 4096

The two orders give the identical result — but the linear one never materialises the N×N matrix (here 4,000,000 floats versus just 4,096). That reordering is the whole game: O(N²·d) work becomes O(N·d²), linear in sequence length.

State-space models (SSMs) — Mamba. SSMs treat the sequence like a linear recurrence (equivalently a long convolution): a hidden state is carried forward and updated at each step. Mamba’s contribution is making that update selective — input-dependent gates decide what to keep or forget, recovering much of attention’s content-awareness. The payoffs are large:

  • O(N) time, and at inference a fixed-size state per step — there is no KV cache that grows with context. Constant memory, high throughput.
  • The cost: history is compressed into that fixed state. Attention can look up any past token exactly; an SSM must have chosen to remember it. So SSMs can lag on tasks needing precise long-range recall (e.g. “copy this exact ID from 40k tokens ago”).

How to choose

ApproachCostRecallUse it when
Full + FlashAttentionO(N²) computeexactcontext is moderate; quality is paramount
Sliding / block-sparseO(N·w)local + stacked reachlong docs, mostly-local dependencies
Global + localO(N)local + a few globalslong docs with a few key anchors
Linear attentionO(N)approximateextreme length, throughput over precision
SSM (Mamba)O(N), O(1) stateselective, compressedstreaming / very long context, high throughput
Hybrid (Jamba)~O(N)near-exactthe pragmatic long-context default

In one breath

  • Full attention is O(N²) in compute; FlashAttention only makes that cheaper to run, so past ~100k tokens the quadratic wall is still there.
  • Escape 1 — sparsify: compute only a structured slice of the matrix. Sliding-window (O(N·w), reach grows with depth like a CNN), global+local (O(N)), dilated, and GPU-friendly block-sparse — trading guaranteed reach for cost.
  • Escape 2 — change the operator: linear attention reorders Q(KᵀV) to skip the N×N matrix (O(N·d²)); SSMs (Mamba) carry a fixed selective state forward — O(N) time, constant per-step memory, no growing KV cache.
  • The trade is recall: a fixed state or pattern must choose what to remember, so exact long-range lookup can suffer — which is why hybrids (Jamba) mix cheap linear/SSM layers with a few full-attention layers, the pragmatic long-context default.

Check yourself

Quick check

0/3
Q1How is sub-quadratic attention fundamentally different from FlashAttention?
Q2A sliding-window attention layer with window w only sees w tokens back. How does a deep stack still capture long-range dependencies?
Q3What is the core trade-off of a state-space model (Mamba) versus attention?

What to remember

  • Full attention is O(N²); FlashAttention makes it cheaper but not sub-quadratic. Two real escapes change the computation.
  • Sparse patterns (sliding-window, global+local, block) skip most of the matrix — O(N·w) to O(N) — trading guaranteed reach for cost.
  • Linear attention reorders the product to avoid the N×N matrix; SSMs (Mamba) carry a fixed selective state — O(N) time, no growing KV cache, at the cost of exact recall.
  • Hybrids (Jamba) mix cheap linear/SSM layers with a few attention layers — the pragmatic recipe behind much of today’s long context.

Sign in to track your progress

Completed lessons, your XP, level, and streak save to your account — it's free and takes a few seconds.

FAQCommon questions

Questions about this lesson

What is the difference between sparse attention and FlashAttention?

They solve different problems. FlashAttention computes exact full attention but is IO-aware, keeping the N×N score matrix out of slow memory — it stays O(N²) in compute. Sparse (and linear, and state-space) methods change the computation itself so it's sub-quadratic, by not computing most of the matrix or by replacing the operator. They're complementary: a model can run FlashAttention kernels on a sparse pattern.

If sliding-window attention only looks back w tokens, how do transformers capture long-range dependencies?

By depth. One windowed layer reaches w tokens back, but a token at layer 2 attends to neighbours that already summarised their own windows, so the effective receptive field grows roughly as L·w over L layers — the same way stacked convolutions come to span an entire image. A fixed window per layer still yields long effective reach once stacked.

What do state-space models (Mamba) trade away versus attention?

Exact recall. Mamba carries a fixed-size selective state forward, giving O(N) time and constant per-step memory with no growing KV cache — excellent for throughput and very long context. But a fixed state must choose what to remember, so it can't always retrieve an arbitrary far-back token the way attention's full lookup can. Hybrids like Jamba add a few attention layers back to recover that precise recall.

Practice this in an interview

All questions
How do state-space models like Mamba differ from attention, and when would you use one?

Attention lets each token directly weight past tokens, which gives full-sequence quadratic cost and a KV cache that grows with context during autoregressive decoding. A selective state-space model such as Mamba carries a fixed-size recurrent state in linear time, making it attractive for very long or streaming sequences, while attention or a hybrid is safer when exact long-range retrieval matters.

Why is standard self-attention O(n^2) in sequence length, and how is it addressed?

Standard self-attention compares every token with every other token, so its dense score matrix has n squared entries and its compute and memory grow quadratically with sequence length. FlashAttention removes the large intermediate but not the quadratic compute, while sparse, local, low-rank, linear, retrieval, and alternative sequence architectures trade exact all-to-all attention for lower cost.

What problem does FlashAttention solve, and is it an approximation?

FlashAttention computes the same dense softmax attention as the standard formula, but tiles the work so the N by N score matrix stays out of HBM and is never materialized. Online softmax keeps the result exact in mathematical terms, reducing attention's memory footprint from quadratic in sequence length to linear while leaving its quadratic compute cost unchanged.

Why use multiple attention heads instead of one large attention operation?

Multiple attention heads give each token several independently learned attention distributions, so different subspaces can retrieve different tokens or relationships in the same layer. A single full-width head has one distribution and one weighted mixture; standard multi-head attention keeps roughly the same parameter count and leading attention compute by splitting the model dimension across heads.

Related lessons

Explore further