Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 51  /  ATTENTION

The million-token bill.

Ask a model to read a whole codebase and dense attention has to weigh every token against every other — memory grows with the context, compute grows with its square. At a million tokens that bill is the whole cost of serving. Pull two levers — compress each token's key/value, and select only the blocks that matter — and watch it collapse.

Act 1 · The wall
Every token, weighed against all of them
Dense attention caches a key/value for every token, and each new query scores against all of them. Add tokens and the cache grows linearly while the scoring grows with the square. Watch the keys pile up — every one is stored and scored.
KV cache — every token stored & scored (dense)
0
Tokens (context n)
0
KV keys cached
0
Score ops (∝ n²)
KV grows as n, scoring as n². Scale n from 8 to a million and both numbers explode — that's the wall a long-context model hits. The next act attacks both.
Act 2 · The two levers
Compress every token, score only a few blocks
Lever one — compress: cache a small latent per token instead of the full width (yellow). Lever two — select: for this query, score only the top-k blocks (green), skip the rest (dimmed). The dense row scores 32 keys; the sparse row scores far fewer, at a fraction of the memory each.
Dense — score all 32 keys, full width each
Sparse — compressed keys, top-2 blocks selected
Green = the blocks this query actually scores; dimmed = skipped. Each stored key is a compressed latent, not the full width — so you pay less memory per key and score fewer of them. Two discounts, stacked.
Act 3 · Scale it to a million
Where the two levers multiply
KV ratio is d_c / width — a fixed per-token discount. FLOPs ratio is (scored keys / n) × (d_c / width) — the selection ratio keeps shrinking as context grows, and the two multiply. Drag the context to a million and watch both ratios fall.
Context length n1,000,000
Latent width d_c (of 4096)512
Blocks kept k (× block 256)64
—
KV cache vs dense
—
Attn FLOPs vs dense
—
Scored keys (min n, k·b)

Two currencies, two levers

Attention costs you twice. Memory: the KV cache stores a key and value for every token, so it grows linearly with context and batch. Compute: every query scores against every stored key, so attention FLOPs grow with the square of the sequence. At a million tokens both are the dominant serving cost — this is the wall long-context models hit.

Compressed sparse attention (the shape in DeepSeek-V4) attacks both, and the trick is that the two savings multiply. Compression is a constant discount on every token; selection is a growing discount as context lengthens.

The math

KV ratio = d_c / width (per-token, context-invariant). Scored keys = min(n, k·b) — once n > k·b the count freezes while dense keeps paying n. Attention-FLOPs ratio = (min(n,k·b) / n) × (d_c / width) — the product of the two levers. A fixed 8× compression times a selection ratio that keeps shrinking lands the total far below the dense curve.

Doesn't selection lose information?

It bets that for any query, only a small slice of a million past tokens is actually relevant — so scoring the top-k blocks keeps what matters and skips the rest. Below the budget nothing is dropped; above it, the work stops growing with the sequence. It's an approximation, but a well-chosen one, which is why quality holds. Contrast this with the KV-cache visualizer, where the cache grows dense and unbounded.

Compression alone isn't new

The compression lever descends from multi-head latent attention (cache a small latent, reconstruct heads at use time). What compressed sparse attention adds is the second lever — periodic KV compression plus top-k block selection — so the discounts stack instead of competing. Read the full breakdown in DeepSeek-V4.

The picture: one query, eight blocks, two kept

2,048 cached tokens = 8 blocks of 256, each key a 512-wide latent B0256 B1kept B2256 B3256 B4256 B5256 B6kept B7256 query scores 8 block summaries (n/b), keeps the top k = 2 select512 / 2,048 = 25% attend 512 keysB1 + B6, 256 each compress512 / 4,096 = 12.5% attention work = 25% × 12.5% = 3.125% of dense, 32× less
Act 2’s levers on a context small enough to draw. All eight blocks stay in the cache, so memory still grows with n, at an eighth of the width. Skipped is not deleted. The six blocks this query never reads hold 1,536 tokens, and the next query may pick a different two, so the whole cache has to stay resident. The query pays twice before it attends. First it scores the block summaries, one per 256 tokens, to choose which blocks to read. Then it runs ordinary attention over just those blocks. At 2,048 tokens the summary step is 8 scores against 512 keys, which is noise. The next section shows where that stops being true.

Cost and trade-offs: dense, compressed, sparse, windowed

Cost of one decode step for a query at context length n. Here w is the full key width, d_c the latent width, b the block size, k the blocks kept and W a sliding window. The figures use the page’s defaults: 1,000,000 tokens, w = 4,096, d_c = 512, b = 256, k = 64.

CaseTimeSpaceWhy
DenseO(n·w): 1,000,000 keys at full widthO(n·w): 16.4 GB per layer in FP16Exact. Every token can reach every other, and both costs grow without limit.
Compression only (latent KV)O(n·d_c): still 1,000,000 keys, each 8× cheaperO(n·d_c): 2.05 GB per layerA constant discount. Work still grows with n, so at a million tokens you are still scoring a million keys.
Selection onlyO(n/b + k·b·w): about 3,906 summaries + 16,384 keysO(n·w): the full 16.4 GBCaps the attention work but not the memory. Every block has to stay stored in case a later query selects it.
Compression + selectionO((n/b + k·b)·d_c)O(n·d_c): 2.05 GBThe page’s shape. The discounts multiply, and the cache still grows linearly.
Same budget, bigger blocks (b = 1,024, k = 16)977 summaries + 16,384 keys at a million tokensUnchangedFour times fewer summaries to scan, but each pick drags in 1,024 tokens. If the one fact you need sits in a block of noise, the noise uses up the budget and fewer distinct places get read.
Sliding windowO(W·w)O(W·w): boundedThe only option whose memory stops growing. Anything older than W tokens is out of reach, which is why it is usually paired with another mechanism.
Prefill, whole promptDense: 5 × 10¹¹ query-key pairs. Selection: 1.6 × 10¹⁰As aboveEach query attends to at most k·b keys, so building the cache for a million-token prompt is about 31× less attention work before compression.

Look again at the summary term n/b. The page’s ratio counts the keys that are attended, and that count freezes at 16,384. The summary scan does not freeze. It is 64 scores at 16,384 tokens, 3,907 at a million (19% of all the scoring in a step) and 39,063 at ten million (71%), where it costs more than the attention it decides. Long-context designs keep that term small with larger blocks, or with a cheaper scoring pass, or both. Block size trades selection precision against both the scan cost and the kernel efficiency.

Where this shows up in production

  • Latent KV in DeepSeek models

    The compression lever is multi-head latent attention. It was introduced in DeepSeek-V2 and carried into DeepSeek-V3: cache one small latent per token and reconstruct the per-head keys and values at use time. It is the reason those models can serve long contexts without a cache that grows at full width.

  • Trained-in block selection

    DeepSeek’s Native Sparse Attention work combines three branches: compressed blocks for a coarse view, top-k selected blocks at full detail, and a sliding window for nearby tokens. It is trained that way from the start, which is the page’s point that selection cannot be bolted onto a dense model afterward.

  • The fixed-pattern ancestors

    Sparse Transformer, Longformer and BigBird made attention cheaper with patterns fixed in advance: local windows, strided positions and a few global tokens. Top-k selection replaces the fixed pattern with one chosen per query, so the far-away block that matters can be read even when no pattern would have included it.

  • Interviews and capacity planning

    The common question is “why is a million-token context expensive, and what would you cut?”. A strong answer separates the two currencies, sizes the cache with the formula (2 × width × bytes × tokens per layer gives the 16.4 GB above), and names what each lever gives up: compression costs a little fidelity, selection risks missing a block, and a window forgets everything older than W.

Sparse attention, step by step

One decode step under compressed sparse attention, and the Act 3 arithmetic at the widget's defaults: a million tokens, a 512-wide latent against a 4,096-wide key, and 64 blocks of 256 kept.

One query, four moves

  1. Compress. As tokens arrive, store each one's key and value as a small latent of width d_c instead of the full width. This is a fixed discount per token.
  2. Group. Cut the stored sequence into blocks of b tokens (256 here) and keep one summary per block.
  3. Select. Score the query against the block summaries, a list n/b long, and keep the top k blocks.
  4. Attend. Run ordinary softmax attention over only the tokens in those blocks, at most k·b keys.

Worked example: one million tokens

  1. Dense baseline. One query scores 1,000,000 keys; scoring the whole sequence is about n²/2 = 5 × 10¹¹ query-key pairs per head per layer, and the cache holds all 1,000,000 keys at full width.
  2. Selection alone. k·b = 64 × 256 = 16,384 scored keys, a ratio of 16,384 / 1,000,000 = 1.64%, about 61 times fewer. Of the roughly 3,906 blocks, 64 are kept.
  3. Compression alone. d_c / width = 512 / 4096 = 0.125, so the cache is 8 times smaller: if a key and a value are each 4,096 wide in FP16 that is 16.4 GB per layer for a million tokens, down to 2.05 GB.
  4. Together. 0.0164 × 0.125 = 0.00205 of dense attention work, about 488 times less.
  5. The selection ratio is not constant. It is 100% up to 16,384 tokens, 25% at 65,536, 6.25% at 262,144 and 1.6% at a million, so the combined ratio runs 12.5%, 3.1%, 0.78% and 0.20%. The savings grow with context, which is the point.
  6. Sliding the knobs. Cutting k to 16 scores 4,096 keys, 0.05% of dense work. Doubling d_c to 1,024 halves the cache saving to 4× and gives 244×.

Knobs and pitfalls

The cache still grows linearly, so memory capacity matters even when compute does not. Selection is an approximation: a small k can miss a needed block, so test long-range retrieval tasks rather than perplexity alone. Training must match inference, since a model trained with dense attention does not tolerate selection added afterward. Sparse patterns only pay off with kernels that read blocks contiguously, which is why block size is a hardware choice as much as a modeling one.

Check yourself

Four questions. Don't attend to all of them — just the relevant ones.

See every answer, with the reasoning
  1. Why is dense attention expensive at a million tokens?

    Answer: KV memory grows linearly (n) and attention compute grows with the square (n²) of the context — Store a key/value per token, and score every query against every key — both explode with length.

  2. What are the two levers of compressed sparse attention?

    Answer: Compress each token's K/V to a latent, and select only the top-k blocks per query — Compression shrinks memory per token; selection shrinks how many tokens are scored.

  3. Why do the two savings multiply?

    Answer: FLOPs scale with scored-keys × per-key work, so the ratio is (scored/n) × (d_c/width) — A fixed compression ratio times a shrinking selection ratio lands far below the dense curve.

  4. What happens to scored keys once n exceeds the selection budget k·b?

    Answer: They freeze at k·b while a dense model keeps paying n — Above the budget, selection caps the work — that's the growing discount as context lengthens.

Finished this one? 0 / 61 Labs done
NextThe Memory Tax: KV-Cache Visualizer Closest lab to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs