Why long context is expensive: the attention compute and memory ledger
Start with a concrete case: dump a 200-page product manual into the prompt. The window is large enough, yet the first token takes tens of seconds and the bill is many times that of a short chat. Nothing is "broken": as context grows, the internal compute and cache footprint grow with it. This article separates those two bills.
The one-paragraph answer
A longer context costs you twice: the attention score matrix and its theoretical memory grow quadratically in sequence length n, while the K/V tensors that decoding must cache grow linearly in n. FlashAttention answers "how to compute without blowing up memory"; grouped-query attention (GQA) answers "can we cache less". Neither removes the quadratic term.
Two squares and one line
Every decoder layer first projects its input into Q, K and V. Roughly: Q is what each token is looking for, K is what each token offers, V is the content actually taken. Each token's Q is dotted against every token's K, softmaxed into weights, producing an n×n attention score matrix that then weights the V sum.
That structure fixes three things:
- Quadratic compute: QKᵀ plus the weighted V sum come to roughly 4n²·d_model FLOPs per layer per forward pass. Quadruple the input length and prefill attention demand grows about 16×.
- Quadratic theoretical memory for the score matrix: n×n scores, one copy per head per layer.
- Linear KV cache: during decode, past tokens' K and V are reused on every step, so they must be cached — 2×n×d_model×layers elements, growing linearly with context.
- Attention compute / score matrixlength ×16 → demand ×256
- KV cachelength ×16 → demand ×16
A memory bill you can recompute
The numbers below are derived from formulas, not measured on a specific GPU. Assumptions: 32 decoder layers, d_model = 4096, 32 attention heads, fp16 (2 bytes per element) — a typical 7B–8B configuration.
| Same assumptions | 8,192 tokens | 131,072 tokens (length ×16) |
|---|---|---|
| MHA KV cache | ≈ 4 GiB | ≈ 64 GiB (×16) |
| GQA KV cache (KV heads = 1/4 of query heads) | ≈ 1 GiB | ≈ 16 GiB |
| One layer's n×n score matrix (theoretical bound) | ≈ 4 GiB | ≈ 1 TiB (×256) |
What those numbers mean:
- 4 GiB (8K KV cache): after ~15 GB of fp16 weights for a 7B model on a 24 GB consumer card, a single request barely fits; push the context further and you run out.
- 64 GiB (128K KV cache): on an 80 GB flagship card, weights and activations leave very little headroom. Concurrent requests are basically out of reach.
- 1 TiB (single-layer score matrix): far beyond any single GPU. No framework allocates it; they change the algorithm instead — exactly the problem FlashAttention solves.
A window advertised in the millions does not erase the bill
As of the official docs in November 2026, OpenAI GPT-5 lists a 400,000-token context window, and the newer gpt-5.6-sol lists 1,050,000 tokens. The window number answers "how much can I fit", not "does it cost and run the same at any length".
Two cost segments have to be budgeted separately:
- Prefill: the model ingests the whole input at once, and the quadratic attention work lands here. This drives time-to-first-token (TTFT). A hundred-thousand-token request is in a different league from a short chat.
- Decode: every generated token re-reads all historical K/V for one more attention pass. KV reads grow linearly with context and are bound by memory bandwidth, so longer context means slower and costlier per output token.
"1M window" means the request will not be truncated. It does not mean a million-token prefill and decode are free.
Two mainstream savings, each covering one segment
FlashAttention: reorder the computation, keep the result
FlashAttention (Dao et al., 2022) is IO-aware exact attention. GPUs have two memory tiers: HBM, large but relatively slow, and SRAM, small on-chip cache that is much faster. The kernel tiles Q, K and V into SRAM-sized blocks, computes locally, and avoids writing the full n×n matrix back to HBM. Three points must be kept apart: it is exact, not an approximation — output matches standard attention; it reduces extra memory to linear and cuts HBM traffic sharply; and the paper's speedups (roughly 3× on GPT-2 at 1K sequences) depend on hardware and sequence length, while the quadratic FLOPs remain — longer sequences still make prefill slower.
GQA: let several query heads share one KV
Standard MHA gives every query head its own K/V. MQA shares a single K/V across all heads: fast, at some quality cost. GQA (Ainslie et al., 2023) takes the middle path — query heads are grouped, and each group shares one K/V pair. It cuts decode-time KV memory and bandwidth only; it does not touch prefill's quadratic compute. The two extremes (fully shared, fully independent) are MQA and MHA.
Standard multi-head attention (MHA)
- Every query head holds its own K/V heads
- Under the example assumptions, a 128K context needs ~64 GiB of KV cache
- Heavy decode-time bandwidth pressure; limited concurrency
Grouped-query attention (GQA)
- Query heads in a group share one K/V pair; GQA-1 equals MQA
- KV heads cut to 1/4, so the same context needs ~16 GiB
- Paper results: quality close to MHA, speed close to MQA
Three calls for the application side
- Ask first whether everything must be stuffed in. Most workflows do not need the entire history in one prompt. Retrieval augmentation (see chapter 04), rolling summaries and external memory all shorten the effective context, and what you save is real prefill money.
- Do not trust the advertised window — measure your own TTFT. Feed the same question at 8K, 32K and 128K, 20 runs each, take medians, and record TTFT, per-token decode latency and total time. Skeleton below, deliberately model- and price-agnostic:
import time, tiktoken
from openai import OpenAI
client = OpenAI() # any OpenAI-compatible endpoint works
enc = tiktoken.get_encoding("o200k_base") # swap for the tokenizer of the model under test
def pad_to(token_count: int) -> str:
base = enc.encode("hello") # single token as the repeat unit
ids = (base * (token_count // len(base) + 1))[:token_count]
return enc.decode(ids) # deterministic input of an exact length
for n in (8_000, 32_000, 128_000):
t0 = time.perf_counter()
stream = client.chat.completions.create(
model="your-model", # replace with the real model id
messages=[{"role": "user",
"content": pad_to(n) + "\nSummarize the content above in one sentence."}],
stream=True,
)
next(stream) # first token arrival ends TTFT
ttft = time.perf_counter() - t0
# Drain the stream for total decode time; take the median of 20 runs per level
print(n, "tokens, TTFT =", round(ttft, 2), "s")- Budget cost in two segments: estimate input from prefill compute and output from KV reads and decode steps. Long-input/short-output and short-input/long-output are two different bills; the serving trade-off continues in chapter 08.
Revision (2026-11-22): added the opening scenario, plain-language term notes, the growth-curve and MHA/GQA diagrams, the memory table, and the TTFT benchmark skeleton. Core conclusions and derived numbers are unchanged.