Level 3 In-Depth AI · Transformers and Language Models
Long Context and Efficient Attention
Attention compares every token with every other, so its cost grows with the square of the input length. How FlashAttention, sliding windows and sparse patterns let models read whole books, and how to test whether they really use what they read.
- Level
- ●●●●● Advanced
- Reading
- 12 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 25 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 25 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- GPUs and Why AI Needs Them
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Long Context and Efficient Attention
Read them roughly in this order. See it on the concept map →
Why it matters
The context window is how many tokens a model can take in at once: the prompt, any documents you paste, the conversation so far and its own answer. GPT-3 (2020) had 2,048 tokens, about three pages. In 2024 Google's Gemini 1.5 Pro offered a million tokens, enough for several novels, an hour of video, or a mid-sized codebase, and by 2025 several commercial models accepted a million tokens or more.
Long context changes what you can do. Instead of building a retrieval pipeline (Retrieval-Augmented Generation), you can sometimes paste the whole manual. A coding agent can keep many files in view (AI Coding Assistants and Agents). A reasoning model can think for tens of thousands of tokens (Reasoning Models and Test-Time Compute).
The obstacle is attention itself. Self-attention compares every token with every other token, so doubling the length quadruples the work. This chapter explains that cost, the engineering that tamed it (above all FlashAttention), the approximations that avoid it (sliding-window and sparse attention), how positional encodings are stretched to longer inputs, and the uncomfortable fact that a model accepting a million tokens does not necessarily use them well.
The intuition
Picture a meeting where everyone must have a short private chat with everyone else. With 10 people that is 45 chats. With 100 people it is 4,950. With 1,000 people it is nearly half a million. The number of pairs grows with the square of the headcount. Attention is that meeting: each token "chats" with every earlier token.
There are three broad responses:
- Hold the meeting more efficiently. Every chat still happens, but you organise the room so nobody wastes time walking around. That is FlashAttention: exactly the same maths, computed in an order that suits the GPU's memory.
- Only chat with your neighbours. Each person talks to the 20 people nearest them, plus a few designated "hubs" that talk to everyone. That is sliding-window and sparse attention: less work, at some cost in what can be connected.
- Replace the meeting with a shared notebook that each person reads and updates in turn: a fixed-size summary rather than all pairs. That is the idea behind linear attention and State Space Models and Mamba.
Key idea Full attention costs time proportional to for tokens. FlashAttention keeps that exact computation but removes the memory and most of the memory traffic. Sliding-window and sparse attention cut the work itself by letting each token see only part of the sequence.
How it works
Where the n² comes from
For one attention head, the queries and keys are matrices with rows (one per token) and columns (the head size). The score matrix
is : one score for every (query, key) pair. Then row by row, and the output is . Computing takes about multiply-adds, and so does .
Worked numbers. At tokens (128k), has entries. Stored in 16-bit numbers that is 32 GiB, for one head in one layer. A model with 32 heads and 32 layers would need that a thousand times over if it stored them all. Clearly, nobody can store at that length.
How does attention compare with the rest of the model? Per layer, the linear projections and the MLP cost roughly floating-point operations, and attention's two matrix products roughly . These are equal when . For a model of width 4,096 that is about 25,000 tokens. Below that, the MLPs dominate the compute; well above it, attention does.
FlashAttention: the same maths, less memory traffic
A GPU (GPUs and Why AI Needs Them) has a large but relatively slow main memory (HBM, tens of gigabytes, a few terabytes per second) and a tiny but very fast on-chip memory (SRAM, a few hundred kilobytes per processor block, many times faster). Standard attention writes the full and out to HBM and reads them back. For long sequences that traffic, not the arithmetic, is the bottleneck.
FlashAttention (Tri Dao and colleagues, 2022) never builds in full. It splits , and into blocks that fit in SRAM, loads one block of queries, streams the key and value blocks past it, and accumulates the output on the chip. It is exact: the result equals standard attention up to floating-point rounding. It is not an approximation.
The hard part is the softmax, which seems to need a whole row of scores at once (to find the maximum and the total). The trick is the online softmax: process the row in chunks and keep two running numbers per query, the largest score seen so far and the sum of so far. When a new chunk arrives with a larger maximum , everything accumulated so far is multiplied by to correct it.
Worked example. One query, scores arriving in two chunks: then . Values are .
- After chunk 1: , , accumulator .
- Chunk 2 brings . Rescale by : , accumulator .
- Output accumulator .
Those are exactly the softmax weights of : divided by their sum gives .
The payoff: attention memory falls from to , and the reduced memory traffic made attention several times faster for long sequences. FlashAttention-2 (2023) roughly doubled the speed again through better work partitioning, and later versions targeted newer GPUs. It is now built into PyTorch (torch.nn.functional.scaled_dot_product_attention picks a fused kernel automatically) and into essentially every training and inference stack. Note what it does not change: compute still grows as .
Cutting the work: sliding-window and sparse attention
To reduce the compute itself, restrict which keys each query may see:
- Sliding-window attention: each token attends only to the previous tokens. Cost grows as , linear in . Information can still travel further than because layers stack: after layers a token can be influenced by tokens up to about positions back. Mistral 7B (2023) used with 32 layers, giving a theoretical reach of about 131,000 tokens, and a "rolling" KV cache that keeps only the last entries (The KV Cache and Fast Inference).
- Global tokens: Longformer (2020) combined a local window with a few tokens (such as a classification token) that attend to, and are attended by, everything.
- Sparse patterns: OpenAI's Sparse Transformer (2019) used strided and fixed patterns so cost grows roughly as .
- Hybrids: many recent models interleave full-attention layers with sliding-window layers (Gemma 2 alternates them, for example), keeping most layers cheap while preserving some global access.
A curious detail found by the StreamingLLM paper (2023): models dump a lot of attention onto the very first tokens, which act as attention sinks. Dropping those tokens from a sliding cache wrecks quality; keeping the first few plus a recent window lets a model stream indefinitely.
Stretching positional encodings
A model trained on 4,096-token sequences has never seen position 50,000. With RoPE, the standard positional scheme, positions are encoded as rotation angles that grow with position, and unseen angles confuse the model. Fixes, usually followed by a short phase of training on long documents:
- Position interpolation (Meta, 2023): squeeze the new, longer positions into the trained range by scaling them down.
- Changing RoPE's base frequency so angles grow more slowly (used, for example, by Code Llama).
- YaRN and related methods: scale different frequency components differently.
Long-context training also needs long training documents, and ring attention and related context parallelism methods that split one sequence across many GPUs (Distributed Training).
Does the model actually use it?
Accepting a million tokens is not the same as using them. The first popular test was the needle in a haystack: hide one sentence ("the best thing to do in San Francisco is…") at various depths in a long filler text and ask for it. Many models now score near-perfectly on that simple test, but it only checks retrieval of one obvious fact.
Harder evaluations show the gaps:
- Lost in the middle (Liu et al., 2023): with relevant information placed among many documents, accuracy was highest when it was at the start or end of the context and dropped when it was in the middle.
- RULER (NVIDIA, 2024) added multi-hop tracing, aggregation and multiple needles, and found that many models' effective context length, the length up to which they keep their short-context quality, was much shorter than the advertised window.
Practical consequences: put the most important instructions and the question at the start or end, don't pad context with irrelevant material, and test with your own long inputs (Evaluating LLM Applications).
In code
This NumPy example implements FlashAttention's core idea, the tiled online softmax, and checks that it gives the same answer as ordinary attention while never holding more than a thin slice of the score matrix.
import numpy as np
rng = np.random.default_rng(0)
n, d = 2048, 64
Q, K, V = (rng.standard_normal((n, d)) for _ in range(3))
def naive_attention(Q, K, V):
S = Q @ K.T / np.sqrt(d) # n x n score matrix, all in memory
P = np.exp(S - S.max(axis=1, keepdims=True))
return (P / P.sum(axis=1, keepdims=True)) @ V, S.size
def tiled_attention(Q, K, V, block=128):
"""Visit K, V in blocks, keeping a running max and sum per query (online softmax)."""
out = np.zeros_like(Q)
m = np.full(n, -np.inf) # running max of scores per query
l = np.zeros(n) # running sum of exp(score - m)
for start in range(0, n, block):
Kb, Vb = K[start:start + block], V[start:start + block]
S = Q @ Kb.T / np.sqrt(d) # only n x block scores at a time
m_new = np.maximum(m, S.max(axis=1))
scale = np.exp(m - m_new) # correct what was accumulated so far
P = np.exp(S - m_new[:, None])
l = l * scale + P.sum(axis=1)
out = out * scale[:, None] + P @ Vb
m = m_new
return out / l[:, None], n * block
a, size_a = naive_attention(Q, K, V)
b, size_b = tiled_attention(Q, K, V)
print(f"max difference: {np.abs(a - b).max():.1e}")
print(f"largest score matrix: naive {size_a:,} numbers, tiled {size_b:,} numbers")
# max difference: 5.8e-16
# largest score matrix: naive 4,194,304 numbers, tiled 262,144 numbers
The difference is at the level of floating-point rounding, and the biggest score array is 16 times smaller. The real FlashAttention also tiles the queries and fuses everything into one GPU kernel. In PyTorch you get it for free:
import torch
import torch.nn.functional as F
q = k = v = torch.randn(1, 8, 4096, 64) # batch, heads, tokens, head size
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # fused kernel when available
print(out.shape) # torch.Size([1, 8, 4096, 64])
Common pitfalls
- Treating the advertised window as usable. Test on your own data at the lengths you need. Quality often degrades well before the limit.
- Burying the question. Put instructions and the actual question at the beginning or end of a long prompt, not in the middle.
- Paying for tokens you don't need. Long prompts cost money and latency (prefill time grows with length, and attention's share with its square). Retrieval of the relevant parts is often cheaper and better than pasting everything (Retrieval-Augmented Generation).
- Assuming FlashAttention makes long context cheap. It removes the memory blow-up, not the compute.
- Forgetting the KV cache. At long context the cache, not the weights, usually fills the GPU (The KV Cache and Fast Inference).
Watch out A perfect needle-in-a-haystack score does not mean a model can reason over everything in its context. Tasks that require combining many scattered facts degrade much sooner. Evaluate with tasks that look like yours.
Variations
- Linear attention replaces the softmax with a form that can be computed as a running sum, giving cost linear in ; it usually loses some quality.
- State space models such as Mamba keep a fixed-size state instead of attending to every past token: State Space Models and Mamba.
- Memory and retrieval: instead of a longer window, store and retrieve relevant chunks: Retrieval-Augmented Generation, Context Engineering and Memory.
- KV cache compression: grouped-query attention, latent attention and cache quantisation: The KV Cache and Fast Inference.
- Mixture of experts is about a different cost (the MLPs) but is usually combined with these methods: Mixture of Experts.
A bit of history
The original Transformer (2017) used 512-token sequences. BERT used 512 and GPT-2 1,024. Research into cheaper attention boomed in 2019–2020 with the Sparse Transformer, Reformer, Longformer, BigBird, Linformer and Performer, but most of these approximations saw limited use in large language models. The breakthrough that stuck was an engineering one: FlashAttention, published by Tri Dao, Dan Fu, Stefano Ermon, Atri Rudra and Christopher Ré in May 2022, which made exact attention fast and memory-light.
Context windows then grew quickly: GPT-4 offered 32,000 tokens in March 2023, Anthropic's Claude 100,000 in May 2023, and Google's Gemini 1.5 Pro one million in early 2024. Greg Kamradt's needle-in-a-haystack charts (late 2023) became the popular way to show off long context, and papers such as "Lost in the Middle" and RULER showed why it was not the whole story.
Try it
- Repeat the online-softmax worked example by hand with the chunks in the other order, then . Do you get the same weights?
- In the code, change
blockto 16 and to 2048. What happens to the largest score array and to the result?- For a model with , at what sequence length does attention's compute equal the rest of the layer's? What about ?
Hint for 3: use .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
FlashAttention: Fast and Memory-Efficient Exact Attention
Making attention faster by being careful about GPU memory movement.
FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning
Reorganises the FlashAttention kernel for better GPU utilisation, roughly doubling its speed.
Lost in the Middle: How Language Models Use Long Contexts
Models use information at the start and end of a long context better than information in the middle. Explains why ordering retrieved passages matters.
RULER: What's the Real Context Size of Your Long-Context Language Models?
A harder long-context benchmark than needle-in-a-haystack, showing that many models' effective context is much shorter than their advertised one.
Longformer: The Long-Document Transformer
Combines a sliding attention window with a few global tokens so attention cost grows linearly with length.
Mistral 7B
A 7B model combining grouped-query attention and sliding-window attention with a rolling KV cache.
Generating Long Sequences with Sparse Transformers
Factorised sparse attention patterns that cut attention cost from quadratic to about n·√n.
Efficient Streaming Language Models with Attention Sinks
Finds that models park attention on the first few tokens (attention sinks) and keeps them in a sliding-window cache to stream indefinitely.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/long-context.md