◆ AI All-in-One

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
↗ Plan a path here

Read first

Self-Attention and Multi-Head AttentionGPUs and Why AI Needs Them

This leads to

—
The full path from zero — 25 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. GPUs and Why AI Needs Them
  13. Supervised Learning
  14. Linear Regression
  15. The Perceptron
  16. Logistic Regression
  17. Neural Networks
  18. Recurrent Neural Networks
  19. Backpropagation
  20. Activation Functions
  21. Vanishing and Exploding Gradients
  22. LSTMs and GRUs
  23. Sequence-to-Sequence Models
  24. Attention
  25. Self-Attention and Multi-Head Attention
  26. 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:

  1. 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.
  2. 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.
  3. 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.
Full causal ≈ n²/2 cells: 136 Sliding window, w = 4 ≈ n·w cells: 58 Window + global token green: all also see token 1 (70) rows: query tokens, first at topcolumns: keys each query may attend to, first at left
Fig. 1 Three attention patterns for a sequence of 16 tokens. Each row is a query token and each coloured cell a key it may attend to. Full causal attention fills a triangle (cost grows with n²). A sliding window of 4 keeps a diagonal band (cost grows with n). Adding a global token lets information still travel across the whole sequence.

Key idea Full attention costs time proportional to n2n^2 for nn tokens. FlashAttention keeps that exact computation but removes the n2n^2 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 Q\mathbf{Q} and keys K\mathbf{K} are matrices with nn rows (one per token) and dd columns (the head size). The score matrix

S=QK⊤d\mathbf{S} = \frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}

is n×nn \times n: one score for every (query, key) pair. Then P=softmax(S)\mathbf{P} = \mathrm{softmax}(\mathbf{S}) row by row, and the output is PV\mathbf{P}\mathbf{V}. Computing S\mathbf{S} takes about n2dn^2 d multiply-adds, and so does PV\mathbf{P}\mathbf{V}.

Worked numbers. At n=131,072n = 131{,}072 tokens (128k), S\mathbf{S} has 131,0722≈1.7×1010131{,}072^2 \approx 1.7 \times 10^{10} 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 S\mathbf{S} at that length.

How does attention compare with the rest of the model? Per layer, the linear projections and the MLP cost roughly 24ndmodel224 n d_{\text{model}}^2 floating-point operations, and attention's two matrix products roughly 4n2dmodel4 n^2 d_{\text{model}}. These are equal when n=6dmodeln = 6 d_{\text{model}}. 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 S\mathbf{S} and P\mathbf{P} 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 S\mathbf{S} in full. It splits Q\mathbf{Q}, K\mathbf{K} and V\mathbf{V} 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.

GPU main memory (HBM)large, slower Q K V each split into blocks of rows on-chip memory (SRAM)tiny, very fast Q blk K blk V blk S tileone small tile of scoresexists at a time, neverthe full n × n matrix running max m, running sum ℓ,output accumulator for the Q block loop: for each K, V block, load it, update m, ℓ andthe output, discard it. Write only the final output back.memory O(n) instead of O(n²); far less HBM traffic; exact result
Fig. 2 FlashAttention's tiling. A block of queries stays in fast on-chip memory while blocks of keys and values stream past. For each pair of blocks, only a small tile of scores exists at any moment. A running maximum and running sum let the softmax be computed correctly without ever seeing a whole row at once.

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 mm and the sum ℓ\ell of es−me^{s - m} so far. When a new chunk arrives with a larger maximum m′m', everything accumulated so far is multiplied by em−m′e^{m - m'} to correct it.

Worked example. One query, scores arriving in two chunks: (1,2)(1, 2) then (3)(3). Values are v1,v2,v3v_1, v_2, v_3.

  • After chunk 1: m=2m = 2, ℓ=e1−2+e0=0.368+1=1.368\ell = e^{1-2} + e^{0} = 0.368 + 1 = 1.368, accumulator =0.368 v1+1⋅v2= 0.368\, v_1 + 1\cdot v_2.
  • Chunk 2 brings m′=3m' = 3. Rescale by e2−3=0.368e^{2-3} = 0.368: ℓ=1.368×0.368+e0=0.503+1=1.503\ell = 1.368 \times 0.368 + e^{0} = 0.503 + 1 = 1.503, accumulator =0.135 v1+0.368 v2+1⋅v3= 0.135\, v_1 + 0.368\, v_2 + 1 \cdot v_3.
  • Output == accumulator / ℓ=0.090 v1+0.245 v2+0.665 v3/\ \ell = 0.090\, v_1 + 0.245\, v_2 + 0.665\, v_3.

Those are exactly the softmax weights of (1,2,3)(1, 2, 3): e1,e2,e3e^1, e^2, e^3 divided by their sum gives 0.090,0.245,0.6650.090, 0.245, 0.665.

The payoff: attention memory falls from O(n2)O(n^2) to O(n)O(n), 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 n2n^2.

Cutting the work: sliding-window and sparse attention

To reduce the n2n^2 compute itself, restrict which keys each query may see:

  • Sliding-window attention: each token attends only to the previous ww tokens. Cost grows as n⋅wn \cdot w, linear in nn. Information can still travel further than ww because layers stack: after LL layers a token can be influenced by tokens up to about L×wL \times w positions back. Mistral 7B (2023) used w=4,096w = 4{,}096 with 32 layers, giving a theoretical reach of about 131,000 tokens, and a "rolling" KV cache that keeps only the last ww 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 nnn\sqrt{n}.
  • 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 n2n^2 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

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

  1. Repeat the online-softmax worked example by hand with the chunks in the other order, (3)(3) then (1,2)(1, 2). Do you get the same weights?
  2. In the code, change block to 16 and to 2048. What happens to the largest score array and to the result?
  3. For a model with dmodel=8192d_{\text{model}} = 8192, at what sequence length does attention's compute equal the rest of the layer's? What about dmodel=2048d_{\text{model}} = 2048?

Hint for 3: use n=6 dmodeln = 6\, d_{\text{model}}.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You double a prompt from 4,000 to 8,000 tokens. Roughly what happens to the attention score computation per layer?

  2. What exactly does FlashAttention change compared with standard attention?

  3. A model uses sliding-window attention with window 4,096 and 32 layers. Why can information still travel much further than 4,096 tokens?

  4. A model scores perfectly on needle-in-a-haystack at 1 million tokens. You paste a long contract and ask a question needing facts from five sections. What should you expect?

  5. Given the "lost in the middle" finding, where should you put the key instruction in a long prompt?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Longformer: The Long-Document Transformer

Beltagy, Peters & Cohan (AllenAI) · 2020 · Advanced · Free

Combines a sliding attention window with a few global tokens so attention cost grows linearly with length.

Paper

Mistral 7B

Mistral AI · 2023 · Intermediate · Free

A 7B model combining grouped-query attention and sliding-window attention with a rolling KV cache.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/long-context.md