Context windows have expanded by 250× in three years — from GPT-3's 4,096 tokens to Gemini 1.5 Pro's one-million-token flagship. That leap is not simply a matter of provisioning more GPU memory. It required rethinking how attention is computed, where KV state lives, and which parts of the sequence a head actually needs to attend to. This article traces the engineering decisions behind that scaling, from the quadratic wall that first stopped progress to the production trade-offs that govern deployment choices today.
The Quadratic Attention Wall
Standard scaled dot-product attention computes a full N×N affinity matrix where N is the sequence length. Memory scales as O(N²) and FLOP count follows the same curve. At N=4,096 that is manageable on a single A100. At N=128,000 — the context length of GPT-4 Turbo and Claude 3.5 Sonnet — the naive matrix requires roughly 128² = 16,384 times the memory of the 1K baseline. At N=1,048,576 the matrix alone would need terabytes of HBM, which no single accelerator possesses.
The wall first became visible in 2020 when researchers tried to extend BERT and early GPT-2 variants beyond 2,048 tokens. Training loss improved marginally but memory OOM errors appeared as soon as the sequence crept toward 4K. The fix at the time was simply to truncate inputs. The community accepted that constraint for two years until the demand for document-level and codebase-level reasoning made it untenable.
The core insight that unlocked progress is that attention does not need to be global — it needs to be correct. If a head can faithfully approximate full attention while materializing only a fraction of the N×N matrix, the quadratic scaling becomes a constant or at worst linear term. The question is which approximation preserves enough signal to maintain model quality.
| Model | Context Window | Architecture Note | KV Cache Strategy |
|---|---|---|---|
| GPT-4o | 128K tokens | Sparse attention + GQA | Paged, server-side |
| Claude 3.5 Sonnet | 200K tokens | Ring attention across TPUs | Streamed shards |
| Gemini 1.5 Pro | 1M tokens | MoE + linear attention tail | Hierarchical paging |
| Llama 3.1 405B | 128K tokens | GQA, RoPE extended | vLLM paged blocks |
Sliding Windows and Sparse Attention Patterns
The first practical escape from the quadratic wall was local windowed attention, introduced at scale by Longformer (Beltagy et al., 2020) and later refined in BigBird and Mistral 7B. Rather than attending to every prior token, each position attends only to the W tokens immediately preceding it. Memory drops to O(N·W) and FLOPs follow the same curve. For W=512 and N=128K this is a 256× reduction in the attention term.
The limitation is obvious: information from token 1 cannot flow directly to token 100,000 in a single layer. It must propagate through multiple layers, each passing the signal W positions forward. For tasks requiring precise recall of an early document segment in a 128K context, this multi-hop propagation fails unless the token that carries the fact is explicitly preserved. Longformer addressed this by adding global tokens — designated positions (such as [CLS] or task-specific anchors) that attend to and from every other position, acting as a broadcast bus. BigBird added random attention on top of local and global to theoretically approximate full attention at O(√N) connections per token.
Mistral's sliding window implementation in its 7B model (later 8×7B MoE) demonstrated that for language modelling and instruction following, a window of 4,096 with RoPE positional encoding already achieves strong quality on most practical tasks. The key observation was that most useful cross-document dependencies span fewer than 4K tokens in practice, even when the nominal context is much larger. Where they don't — legal contracts, academic papers, long conversations — the model degrades gracefully rather than catastrophically.
Sparse attention patterns go further than simple windows. Strided attention (every k-th token), dilated attention (windows that skip tokens to reach further), and learned sparsity patterns (Reformer, BigBird random connections) all reduce the N² term in different ways. None has fully displaced dense attention in the frontier labs because they complicate kernel fusion and hardware utilization. The practical winner for production inference has been a combination of windowed attention in lower layers (where local syntax dominates) and denser attention in upper layers (where semantic reasoning requires wider context). GPT-4o's internal architecture reportedly uses this layered strategy.
Ring Attention: Distributed Sequence Parallelism
Ring attention, introduced by Liu et al. in 2023 and deployed by Google and Anthropic at scale, solves the long-context problem by distributing the sequence across devices and passing key-value blocks in a ring topology. Each device holds a contiguous shard of the sequence. Attention is computed locally using the shard's own Q against the locally resident KV block. Then KV is rotated to the next device in the ring, and the process repeats for all D devices. After D steps, every Q has attended to every K and V in the full sequence.
The communication pattern is elegant: each step sends one KV shard to the next device — a volume of O(N/D × d_head) per step, with D steps, for a total communication of O(N × d_head). This is the same order as simply broadcasting the full KV once, but ring rotation allows computation to overlap with communication: while device i computes attention with the KV shard it currently holds, it simultaneously receives the next shard from device i-1. On NVLink-connected H100 clusters the communication is completely hidden behind the compute for sequence lengths above 32K.
Anthropic's Claude 3.5 Sonnet uses ring attention across TPU pods to reach its 200K context limit. Each TPU core holds approximately 25K tokens. With 8 cores in the ring, the full sequence is 200K. The communication overhead at that scale is under 4% of wall-clock time per attention layer. Training at 1M tokens (Gemini 1.5 Pro) requires a ring of 40 devices with similar arithmetic, plus hierarchical grouping to avoid each step spanning a full inter-pod link.
Flash Attention v3 and IO-Aware Computation
Flash Attention (Dao et al., 2022) reframed the attention problem as an IO-bound rather than compute-bound operation. Standard attention materializes the full N×N softmax matrix in HBM (high-bandwidth memory). Flash Attention tiles the Q, K, V matrices into blocks that fit in SRAM (on-chip cache), computes the softmax incrementally using the online softmax trick, and never writes the full attention matrix to HBM. The result is an O(N) memory footprint for the attention layer itself, with FLOPs unchanged but memory reads/writes cut by roughly 5–10× for typical sequence lengths.
Flash Attention v2 (2023) improved parallelism across the sequence dimension, nearly doubling GPU utilization compared to v1. Flash Attention v3 (2024) added asynchronous memory copies and pipeline stages tuned for H100's separate tensor core and memory copy engines, achieving roughly 1.4× speedup over v2 on H100 for forward passes at sequence length 8K–128K. At 128K context, the HBM footprint for a single layer's attention is approximately 16 GiB in BF16 for a 70B-class model with 64 heads and head dimension 128 — a figure that Flash Attention's tiled approach keeps manageable on a single H100 (80 GiB HBM3).
# Flash Attention v3 usage via the flash_attn library
import torch
from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
def long_context_attention(q, k, v, causal=True, window_size=(-1, 0)):
"""
Args:
q, k, v: (batch, seqlen, nheads, head_dim) in BF16/FP16
causal: apply causal mask
window_size: (-1, 0) = full attention; (w, 0) = sliding window
Returns:
out: (batch, seqlen, nheads, head_dim)
"""
# flash_attn_func dispatches to v3 kernel on H100 when available
out = flash_attn_func(
q, k, v,
dropout_p=0.0,
softmax_scale=q.shape[-1] ** -0.5,
causal=causal,
window_size=window_size, # enables local attention when != (-1, 0)
alibi_slopes=None,
deterministic=False,
)
return out
# Example: 128K context, batch=1, 64 heads, head_dim=128
batch, seqlen, nheads, head_dim = 1, 131072, 64, 128
q = torch.randn(batch, seqlen, nheads, head_dim, dtype=torch.bfloat16, device="cuda")
k = torch.randn_like(q)
v = torch.randn_like(q)
out = long_context_attention(q, k, v, causal=True)
# Peak HBM usage for this single layer: ~16 GiB (vs ~65 GiB naive)
print(f"Output shape: {out.shape}") # (1, 131072, 64, 128)
The key algorithmic insight is the reduction from O(N²) to O(N) memory via tiled chunking. Each tile processes a block of Q rows against all K/V blocks sequentially, accumulating the softmax-weighted sum without ever storing the full N×N matrix. The online softmax algorithm (tracking running max and sum) ensures numerical equivalence to the global softmax. This O(N) memory property is what makes 1M-token contexts feasible on a 16-device H100 node: each device sees roughly 62K tokens of KV state, well within the 80 GiB HBM3 budget even at BF16 precision.
Production Trade-offs: Latency, Memory, and Cost
Running million-token contexts in production involves trade-offs that benchmark papers rarely quantify. Prefill latency — the time to process the input before generating the first output token — scales roughly linearly with context length under Flash Attention (the O(N) memory case) but the FLOP count still grows as O(N) per layer, so actual wall-clock prefill for a 1M-token context on a 70B model across 16 H100s is approximately 90 seconds. For a 128K context on a single H100 it is roughly 11 seconds. Applications with real-time requirements must cache the KV state of static context (system prompts, document corpora) so that re-use pays only the autoregressive decoding cost, not a fresh prefill.
KV cache partitioning is the most consequential production decision. vLLM's paged attention divides KV state into fixed-size blocks (typically 16–32 tokens per block) managed like virtual memory pages. This eliminates fragmentation from variable-length sequences and allows prefix sharing across requests that have identical prefixes (the same system prompt, for example). At 128K context in BF16 with 32 KV heads and head dimension 128, a single cached sequence occupies roughly 2 GiB. A serving cluster handling 100 concurrent 128K-context sessions needs 200 GiB of KV cache storage, far exceeding a single H100's HBM. Offloading to CPU DRAM or NVMe (MemGPT/PagedAttention style) becomes necessary, adding microseconds of swap latency per block access.
Speculative decoding, which uses a small draft model to propose multiple tokens that the large model verifies in a single forward pass, interacts poorly with very long contexts because the draft model's KV cache also grows with context. At 1M tokens, the overhead of maintaining even a 7B draft model's cache is prohibitive. Medusa-style self-speculative decoding (adding draft heads to the same model) sidesteps this by sharing the main model's KV cache, but the speedup degrades at long contexts because the token prediction distribution shifts.
The practical engineering recommendation: for contexts under 128K, Flash Attention v3 on a single H100 with paged KV cache is the right stack. For 128K–256K, ring attention across 2–4 devices with prefix caching handles the memory budget. Beyond 256K, hierarchical attention (local layers + periodic global cross-attention) or Mamba-style linear recurrence hybrids reduce prefill cost at the expense of exact recall on arbitrary positions. The frontier of exact million-token attention remains a research deployment, not yet a commodity service cost point.