Beyond vanilla attention: state space models, long context and hybrids
Sliding windows, linear attention, S4 and Mamba, and why 2026 models are hybrids
Attention's quadratic cost and ever-growing KV cache are the limits that million-token contexts run into. This lesson maps the alternatives — windowed and linear attention, state space models such as S4 and Mamba, and the hybrid architectures that most efficient 2026 models use — and explains the one thing attention still does better than any of them: exact recall. That trade-off is why long context and retrieval (9.1 Why RAG, and the canonical pipeline) are complements, and why agent memory design (10.4 Memory and context engineering) matters even with huge context windows.
You'll be able to
- Quantify the quadratic-attention problem and explain how sliding-window and linear attention reduce it
- Explain the state space recurrence, its convolutional training form, and what Mamba's selectivity adds
- Compare transformers, linear attention, SSMs and hybrids on training parallelism, inference cost and exact recall
- Describe the main long-context techniques for transformers and how to evaluate long-context ability
Key ideas
- Attention costs O(n²d) per layer with a KV cache that grows with context; at long contexts attention dominates compute and memory.
- Sliding-window attention costs O(nwd) with a fixed rolling cache; receptive field grows by w per layer but exact long-range lookup degrades.
- Linear attention drops the softmax: φ(Q)(φ(K)ᵀV) costs O(nd²) and becomes a fixed-size recurrent state S_t = S_{t−1} + φ(k_t)v_tᵀ.
Show 4 more key ideas
- An SSM is a discretized linear system h_t = Āh_{t−1} + B̄x_t, y_t = Ch_t; linearity makes it a convolution (parallel training) and a recurrence (O(1) inference).
- Mamba makes B, C and Δ input-dependent (selective) and computes the recurrence with a parallel scan; Mamba-2 shows SSMs are structured masked attention.
- Fixed-size states summarize; attention stores verbatim — so pure SSMs lag on exact-recall tasks, and hybrids (a few attention layers among many SSM layers) are the practical answer.
- Long context in transformers comes from RoPE scaling, ring attention and sparse/compressive variants; evaluate with needle-in-a-haystack and remember lost-in-the-middle.
Suggested path through this lesson
The quadratic wall
Attention gives every token a direct line to every other, at compute per layer and a KV cache that grows linearly with context (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization). At 128k tokens the attention term dominates the forward pass (7.4 Inside the block: residuals, LayerNorm, FFN and embeddings); at 1M tokens a single Llama-3-8B-style KV cache is 128 GB. Three families of answers exist: make attention cheaper (sparse, windowed, linear), replace it with a recurrence that trains in parallel (state space models), or mix the two (hybrids). A fourth answer — retrieve only what you need — is the subject of Phase 9.
Cheaper attention
Sliding-window attention (Mistral 7B, Gemma's local layers) lets each token attend only to the previous tokens (for example 4,096). Cost per layer drops to and the KV cache to a rolling buffer of entries. Information still travels far because the receptive field grows by per layer — after layers a token can be influenced by positions — but precise long-range lookup degrades. Many 2025–26 models alternate local and global attention layers to get most of the savings while keeping some exact global access.
Linear attention removes the softmax so that associativity can be exploited. With a feature map ,
because is a matrix computed once. Causally, this becomes a recurrence , : a fixed-size state instead of a growing cache. The catch is quality — a state cannot store an arbitrary number of exact key–value pairs, which is precisely what softmax attention does well.
State space models
An SSM starts from a continuous linear system, , , and discretizes it with step into a recurrence
Because the recurrence is linear, unrolling it gives — a convolution with a kernel determined by . S4 (2021) exploited this duality: train in parallel as a long convolution (via FFT, ), infer as a recurrence with cost and constant memory per step, with a structured (the HiPPO initialization) that remembers long histories. S4 excelled on long-range benchmarks but lagged transformers on language.
Mamba (2023) diagnosed why: with fixed the model cannot decide what to remember based on content. Mamba makes , and functions of the input — a selective SSM — so a token can open or close the memory gate the way an LSTM (6.5 LSTM and GRU) does. Selectivity breaks the convolution trick, so Mamba computes the recurrence with a hardware-aware parallel scan that keeps the state in fast SRAM. Result: linear time in sequence length, constant inference memory, and language-modelling quality matching transformers of the same size at the scales tested. Mamba-2 (2024) showed that selective SSMs are a form of structured masked attention — the state space duality — enabling matrix-multiplication-based implementations and borrowing transformer tricks. RWKV reached similar goals from the RNN side with a time-mixing operator that trains in parallel.
Intuition. Attention keeps a verbatim transcript and re-reads it for every new word. An SSM keeps a running summary of fixed size. Mamba lets the model decide, word by word, what to write into the summary and what to let fade.
Where recurrence struggles
A fixed-size state is a compressed summary. Tasks that need exact retrieval of an arbitrary earlier token — copying a long string, looking up a phone number from page 3, multi-needle "needle in a haystack" tests, in-context learning over many examples — favour attention, whose cache stores everything verbatim. This is why pure SSMs lag on retrieval-heavy evaluations, and why the practical answer became hybrids.
Hybrids: the efficiency default in 2026
Interleave a few attention layers among many SSM or linear-attention layers: Jamba (Mamba + attention + MoE), Griffin/RecurrentGemma, Zamba and several newer models follow this pattern. The attention layers supply exact recall; the recurrent layers supply cheap long-range context. Typical ratios use one attention layer per 4–8 recurrent layers, cutting the KV cache by a similar factor while matching transformer quality on most benchmarks.
| architecture | training | per-token inference | state or cache | exact long-range recall |
|---|---|---|---|---|
| transformer (softmax attention) | parallel, | grows with | yes | |
| sliding window | parallel, | fixed, entries | within the window | |
| linear attention | parallel, | fixed, | approximate | |
| SSM (S4, Mamba) | parallel (convolution or scan) | fixed | approximate | |
| hybrid | parallel | mostly fixed | small cache | yes, through the attention layers |
| classic RNN / LSTM | sequential | fixed | approximate |
Long context in transformers
Instead of changing the mechanism, you can stretch the transformer: RoPE scaling and YaRN (7.3 Positional information: sinusoidal, learned, RoPE, ALiBi) extend positions; ring attention splits a sequence across devices and passes K/V blocks around a ring so that a million tokens fit in aggregate memory; block-sparse and dilated patterns and Infini-attention-style compressive memories bound the cost. Evaluate with needle-in-a-haystack and multi-hop long-document tasks, and remember "lost in the middle" (9.6 Generation side: context assembly, citations, structured outputs and tool calling): a model that accepts 1M tokens does not necessarily use them.
What is settled in 2026
Softmax attention remains the core of frontier models because exact recall and in-context learning matter most; GQA, MoE and FlashAttention made it affordable. Linear and SSM layers are mainstream as components of hybrids, especially for long-context and on-device inference, and the SSM–attention duality has turned "attention versus recurrence" into a design spectrum rather than a contest. Long context and retrieval are complements, not substitutes (9.1 Why RAG, and the canonical pipeline).
Where this shows up later
- Long context versus retrieval, and lost-in-the-middle effects — 9.1 Why RAG, and the canonical pipeline, 9.6 Generation side: context assembly, citations, structured outputs and tool calling.
- Hybrid and MoE architectures shape the model landscape and its costs — 8.1 The LLM lifecycle and model landscape; serving costs — 7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization.
- Recurrent memory and compaction reappear as agent memory design, where the context window is the working memory — 10.4 Memory and context engineering.
Common pitfalls (4)
- Believing SSMs made attention obsolete — frontier models still center on attention; SSMs mostly appear as hybrid components.
- Assuming a larger advertised context window means the model uses all of it; test retrieval across positions.
- Confusing linear attention's fixed d×d state with a KV cache: it cannot store an arbitrary number of exact key–value pairs.
- Treating sliding-window attention as losing all long-range information — the receptive field grows with depth, only precise lookup suffers.
Recap: all 7 key points
- Attention costs O(n²d) per layer with a KV cache that grows with context; at long contexts attention dominates compute and memory.
- Sliding-window attention costs O(nwd) with a fixed rolling cache; receptive field grows by w per layer but exact long-range lookup degrades.
- Linear attention drops the softmax: φ(Q)(φ(K)ᵀV) costs O(nd²) and becomes a fixed-size recurrent state S_t = S_{t−1} + φ(k_t)v_tᵀ.
- An SSM is a discretized linear system h_t = Āh_{t−1} + B̄x_t, y_t = Ch_t; linearity makes it a convolution (parallel training) and a recurrence (O(1) inference).
- Mamba makes B, C and Δ input-dependent (selective) and computes the recurrence with a parallel scan; Mamba-2 shows SSMs are structured masked attention.
- Fixed-size states summarize; attention stores verbatim — so pure SSMs lag on exact-recall tasks, and hybrids (a few attention layers among many SSM layers) are the practical answer.
- Long context in transformers comes from RoPE scaling, ring attention and sparse/compressive variants; evaluate with needle-in-a-haystack and remember lost-in-the-middle.
Watch
Derives the discretization, the convolution view, selectivity and the scan — follow with the equations above open.
Read
Exercises
- Linear vs softmax attention on copying
Implement linear attention with in the tiny GPT from 7.8 Build GPT from scratch (nanoGPT walkthrough) and train both variants on a synthetic task: copy a random 64-token string that appears earlier in the context. Expected: softmax attention solves it near-perfectly; linear attention plateaus well below, showing the limits of a fixed-size state.
- A selective scan by hand
Implement the recurrence , for a 1-D input with input-dependent and . Feed a sequence where is large only on "important" tokens. Expected: the state ignores unimportant tokens and jumps on important ones — selectivity as a learned gate.
- Needle in a haystack
Using a small long-context open model, insert a fact at 10%, 50% and 90% depth of a 32k-token document and ask for it. Expected: retrieval accuracy varies by position (often worst in the middle, 9.6 Generation side: context assembly, citations, structured outputs and tool calling); repeat with a hybrid or sliding-window model if available and compare.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →