Why Longer Context Costs More: The O(n²) Bill
Last lesson you got the Big-O ruler—remember that red line taking off? Today we look at the most famous O(n²) inside LLMs—the attention mechanism. You'll suddenly get a pile of old questions: why long chats get slower, why the context window is a “window” not a “warehouse,” why everyone hustles on context compression.
Earlier lessons covered this: when an LLM generates each new token, it has to “look back” at every previous token, assign attention weights, and decide what comes next. One token scanning all tokens—translate that into last lesson's language: n tokens, each looking at n, for n × n “eye contacts” total. That's an n×n table. Drag the slider and see it drawn.
Each row below means “one token looking at every token”; the dark diagonal is it looking at itself. Watch the cell count on the right: the slider moves at a steady pace, but the number jumps harder and harder—that's the feel of “quadratic growth.”
Same ask—“summarize the key points for me.” One person trims history to 10k tokens first; the other dumps a full 100k-token record in. Tokens differ by only 10×—watch how far the bills diverge. Watch the “attention compute” row: it's not ×10, it's ×100.
Trim camp 10k tokens
Stuff-it-all camp 100k tokens
① Why long chats get slower
The longer you chat, the bigger n, and the more “look-backs” each new token needs. Lag isn't a network issue—it's n² snowballing in the background.
② Why context compression exists
Compaction summarizes old turns into a short chunk, then continues. Trade a bit of detail for a much smaller n—halve n, cut compute by three quarters. Worth it.
③ Why KV Cache saves money
Cache attention results already computed for the prefix so the next turn doesn't redo them (sister part ds-6 covered this). Precisely because the raw compute is the expensive O(n²), the cache discount is so valuable.
What this lesson wants to share
- Attention is O(n²): every token looks back at every token—you can't escape the n×n table
- Context isn't a free warehouse: every token you stuff gets looked at again and again by every later token
- 10× → 100× costlier: compute grows with the square—the root of long chats getting slow and expensive
- Trim context = save money and time: compression, summaries, KV Cache—all wrestling this n²