Skip to content

Bridges: DSA to LLMs

Big-O to the O(n squared) attention wall

Why context length is so expensive

The most expensive number in a modern LLM isn't a weight - it's an exponent. Self-attention is in the prompt length, and that single "2" is why long context costs real money.

Back in Big-O notation, Big-O was an abstract way to say how does the work grow as the input grows? Here it stops being abstract. In a Transformer, every token in the prompt looks at every other token to decide what to pay attention to - that's an grid of comparisons for a prompt of tokens. Filling an grid is work. So double the prompt and you roughly quadruple the compute and the size of the attention matrix. That quadratic is the "wall" the whole industry is trying to climb over.

The core picture

Attention asks one question for every ordered pair of tokens: how much should token listen to token ? With tokens there are such pairs, so the scores form a square matrix. A square's area grows quadratically with its side: make the side twice as long and the area is bigger. That is the entire intuition behind the cost - the demo below just lets you watch the square grow.

Big-O, the part that bills you

Three growth shapes matter here. barely moves - binary search on a doubled list adds just one step. is a fair deal - twice the tokens, twice the work, like scanning a list once. is the trap - twice the tokens, four times the work, because the cost is an area, not a length. Self-attention lives squarely in that last class, and unlike a textbook sorting example, the "input" here is your prompt, billed per token, per request, forever.

Watch the wall build itself

Drag to grow the sequence. On the left the attention matrix fills in cell by cell - each cell is one query-key comparison. On the right, live operation counts race: the dashed red curve is the pure wall, and the thick teal curve is self-attention sitting right on it. Now flip linear attention and watch the teal curve peel away from the wall and bend down toward the linear floor - because each token now only looks at a fixed window of neighbours, not all .

The O(n2) attention wall drag n · toggle linear attention

attention matrix — query i × key j

operations vs sequence length n

O(n) — linear floorO(n log n)O(n²) — the wallself-attention

n = 8 tokens · every query attends to every key → n² = 64 score cells. Compute and the attention matrix are O(n²). Double n to 16 256 cells: a jump.

The gap is the invoice

At the full matrix is cells while the sliding window is only . That gap looks modest here - but it is the quadratic, and quadratics don't stay modest. At a -token context the full attention matrix has entries; a fixed window has . Same model, same question, a ten-thousand-fold difference in attention work - purely from the exponent. That is why doubling your context window roughly quadruples the bill, and why frontier labs pour research into bending this curve.

Where the n² comes from

You can read the exponent straight off the code, exactly the way Big-O analysis teaches: count the nested loops. Full attention has a loop over queries wrapped around a loop over keys - two loops over the same , so . Cap the inner loop to a fixed window and one of the 's becomes a constant.

# Full self-attention: every token scores every token
for i in range(n):              # query i  - n of them
    for j in range(n):          # key j    - n each  => n*n pairs
        score[i][j] = dot(Q[i], K[j])
# work grows as n*n   ->  O(n^2)

# Sliding-window attention: each token sees only w neighbours
for i in range(n):              # query i  - n of them
    for j in range(i - w, i + 1):  # only w keys  => n*w pairs
        score[i][j] = dot(Q[i], K[j])
# work grows as n*w   ->  O(n) when w is fixed
Reading the exponent off the loops

The arithmetic, precisely

With sequence length and head dimension , the score matrix is . Building it is dot products of length , then softmax· costs the same again:

Hold fixed and it is in the sequence length - replace with and you get . The KV cache itself is only , linear, but you re-scan all cached keys to generate each new token, so producing an -token reply is again overall - which is exactly why caching and its tricks matter.

Bending the parabola

Two different escapes, often confused. FlashAttention keeps the same FLOPs but tiles the computation so the giant matrix is never stored - it turns memory from into and runs far faster, yet the exponent on compute is unchanged. Sliding-window, sparse, and linear attention (Longformer, Mistral, Performer) change the exponent itself: give each token a fixed window or a low-rank summary and the cost drops to . The switch in the demo is that second kind - you literally see the diagonal band replace the full square.

Check yourself

Full self-attention builds an n×n score matrix. Double the prompt length n, and its compute plus attention-matrix memory each...

Sliding-window attention caps each token to a fixed window of w neighbours. With w held constant, its cost per layer grows like...

Recall: why does a context window twice as long cost roughly four times as much?

Try to state it, then check.

Lock it in

  • Self-attention is in sequence length: every token scores every token, filling an grid.
  • Because the cost is an area, doubling the prompt roughly quadruples both compute and attention-matrix memory - .
  • Read the exponent off the loops: two nested loops over give ; cap the inner loop to a fixed window and it drops to .
  • FlashAttention keeps the FLOPs but tiles so the matrix is never stored (memory ); sparse and linear attention change the exponent itself.

Primary source

For the asymptotic-analysis foundations behind the claim, see MIT 6.006 - Introduction to Algorithms (Spring 2020). For the mechanics of attention that produce the matrix - queries, keys, and the score grid - Jay Alammar's The Illustrated Transformer is the clearest visual walkthrough.

Ask your teacher

This is Big-O with real money on the line: the of self-attention is literally why long-context models are expensive, and why KV caching matters so much for fast generation. Want the exact FLOP and memory formulas for a real model - say GPT-scale with per head and 96 layers - or a deeper look at how FlashAttention's tiling beats the memory wall without touching the exponent? Ask and I'll build the follow-up.