Skip to content
mentoor

Topic 5 of 5 · 5 min read

Attention cost and long-context tricks

Goal: Explain why attention cost grows with context length and match an efficiency technique to the cost it reduces.

Attention compares every token with every earlier token, so its cost grows with the square of the context length; KV caching, grouped-query attention and sliding windows each cut a different part of that cost.

Check yourself · 1 of 3

A prompt grows from 2,000 to 4,000 tokens. Roughly how does the attention score grid change?

Choose one answer

Why it matters

This is why a 200,000-token prompt is slower and costlier than a 2,000-token one by much more than 100 times in attention work, why providers price long contexts higher, and why GPU memory runs out when many users share a server. The original transformer paper compares per-layer cost with recurrent layers and gives attention a cost that grows with the square of the sequence length.

The quadratic term

For n tokens, attention scores form an n by n grid (half of it masked in a decoder). Double the context and the grid has four times the cells.

Context length Score grid cells
1,000 1,000,000
2,000 4,000,000
4,000 16,000,000

Per layer, per head. Memory-efficient kernels such as FlashAttention avoid writing the grid out, but the arithmetic still grows with the square.

Technique 1: KV caching

When generating, the keys and values of earlier tokens do not change. The server stores them (the KV cache) and, for each new token, computes one new query and one new key and value, then scores the new query against the cache. This turns a full grid recompute at every step into one row. The trade-off: the cache lives in GPU memory and grows with context, layers, heads and number of users.

Technique 2: grouped-query attention (GQA)

Standard multi-head attention stores keys and values for every head. In GQA, several query heads share one key-value head; multi-query attention is the extreme of one shared head. The KV cache shrinks by the sharing factor, and the quality loss is small. Many open-weight models, such as Llama, use it.

Technique 3: sliding-window attention

Each token reads only the last w tokens instead of all of them, so cost grows with n times w, not n squared. Longformer uses this. Information from farther back can still arrive indirectly, because stacked layers extend the reach. The trade-off: a detail outside every window can be lost.

Before and after

Weak: "Long context is just a bigger window; it is free." Better: "Each extra token adds to the grid, to the KV cache and to the bill. Long contexts are supported by cache, sharing and window tricks, each with its own trade-off."

What goes wrong

  • Pasting whole repositories. Slow, costly, and the useful lines compete with thousands of irrelevant ones.
  • Assuming KV caching removes the cost. It saves recomputation, but memory still grows.
  • Assuming a large advertised window means equal recall everywhere. Test retrieval at the lengths you actually use.

Examples

Matching technique to cost

Problem Technique What it reduces
Recomputing all keys and values for every new token KV caching repeated compute during generation
KV cache too big for GPU memory Grouped-query attention cache size per token
Cost grows too fast for 100k-token documents Sliding-window attention compute from n squared to n times w

A back-of-envelope cache estimate

layers, kv_heads, head_dim, bytes_per = 32, 8, 128, 2   # fp16
per_token = 2 * layers * kv_heads * head_dim * bytes_per  # keys and values
print(per_token)                 # 131072 bytes = 128 KiB
print(per_token * 32_000 / 2**30)  # about 3.9 GiB for one 32k-token chat

With 32 key-value heads instead of 8 the same chat would need four times as much. That is why grouped-query attention matters when many users share a GPU.

Key points

  • Attention scores form an n by n grid, so doubling the context roughly quadruples the attention arithmetic.
  • KV caching stores earlier keys and values so each new token costs one new row, at the price of GPU memory.
  • Grouped-query attention lets several query heads share key-value heads, shrinking the KV cache.
  • Sliding-window attention limits each token to the last w tokens, so cost grows with n times w instead of n squared.
  • A long advertised context window does not guarantee equal recall at every position; test at your real lengths.

Common mistakes

  • Expecting cost to double when the context doubles, instead of roughly quadrupling for attention.
  • Thinking KV caching makes long context free, when the cache itself fills GPU memory.
  • Filling the window with an entire repository and expecting the model to find the one relevant line.
  • Trusting an advertised window size without testing recall at the lengths you actually send.

Check yourself · 2 of 3

What does a KV cache store?

Choose one answer

Check yourself · 3 of 3

Which technique mainly shrinks the KV cache by letting several query heads share key-value heads?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic