AI SYSTEMS7 MIN READ4 INTERACTIVE LABS

The memory trick that makes language models fast

Watch a language model stream a 300-word reply. It looks effortless. Yet without one quiet piece of GPU memory called the KV cache, every single new word would force the model to re-read its entire past from scratch.

01 / The Recompute Trap

Why generating one word at a time gets painfully slow

Imagine writing an essay where, before typing word #50, you erase your memory and re-read words 1 through 49. Before word #51, you re-read words 1 through 50. By paragraph three, you are spending almost all your energy re-reading instead of writing.

That is exactly how a naive Transformer behaves during autoregressive decoding. Step through the race below to watch how quickly redundant work explodes.

Token-by-Token Compute Race
Without KV Cache (recomputes history) Cumulative token projections: 1
With KV Cache (reuses VRAM shelf) Cumulative token projections: 1
Naive: O(N2)O(N^2) quadratic growth KV Cache: O(N)O(N) linear growth
36 18 0

Across just 8 tokens, naive decoding runs 8×92=36\frac{8 \times 9}{2} = 36 token projections (O(N2)O(N^2)) instead of 88 (O(N)O(N)). Stretch that to a 4,000-token coding reply and the gap becomes 8 million projections versus 4,000.

02 / Inside Attention

Why Keys and Values stay, while Queries vanish

Inside every attention layer, each incoming token gets multiplied into three small vectors: a Query (QQ), a Key (KK), and a Value (VV). Think of a quiet research library.

QQ

Query (Your question)

What the newest token is searching for right now. Once it gathers its answer, nobody will ever ask this exact question again.

KK

Key (Book spine label)

Advertises what an older token is about. Every future token needs to compare its Query against this label.

VV

Value (Pages inside)

The actual meaning pulled out when a Query matches a Key. Future tokens keep reading it, so it stays on the shelf.

Queries are disposable. Keys and Values are permanent.

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{Q K^{\top}}{\sqrt{d_k}}\right) V
Inspect a Decoding Step
CLICK ANY TOKEN
Active token "warm" (step 6)
QQQuery vector DISCARDED AFTER STEP
KKKey vector APPEND TO CACHE
VVValue vector APPEND TO CACHE
GPU VRAM Cache Shelf 5 cached · 1 added

Notice the elegance: the model never modifies an older token’s Key or Value once computed. It only reads them and appends one fresh pair to the end of the shelf.

03 / The Causal Mask

Why changing one early word ruins the whole cache

In our Prompt Caching guide , we saw a strict rule: edit a single word near the top of your prompt, and the API charges you fresh price for everything after it. Now you can see why.

Because language models read left to right, each token ii‘s Key (KiK_i) and Value (ViV_i) depend only on positions j≤ij \le i, and on nothing after it. That creates a lower-triangular dependency grid called the causal mask.

Causal Dependency Ripple

Click any row token on the left to edit it

Watch how an edit leaves every token above it untouched in VRAM, while forcing every token at and below it to recompute its KK and VV tensors.

6 / 6 tokens valid in cache

Practical rule of thumb: Put stable instructions and documents at the top of your prompt, and put timestamps, user queries, or live tool outputs at the bottom. That keeps the blue valid region as large as possible.

04 / The Hidden Bill

When the KV cache outgrows the model itself

KV caching turns compute from O(N2)O(N^2) to O(N)O(N), but it trades compute for GPU memory. Every layer of the network needs its own KK and VV shelf, for every token, for every concurrent user.

Drag the context length and concurrent users below to see how quickly a single 80 GB NVIDIA H100 fills up.

H100 (80 GB) VRAM Footprint Simulator
FITS ON 1× H100
Weights: 16.0 GB KV Cache: 32.0 GB Total: 48.0 / 80 GB
Grouped-Query Attention (GQA) shrinks the KV cache 4× to 8× by letting multiple Query heads share one Key/Value head.
KV Bytes=2⋅Layers⋅Hkv⋅dhead⋅Nctx⋅Batch⋅bprec\text{KV Bytes} = 2 \cdot \text{Layers} \cdot H_{\text{kv}} \cdot d_{\text{head}} \cdot N_{\text{ctx}} \cdot \text{Batch} \cdot b_{\text{prec}}

This memory pressure is why modern inference engines rely on three inventions together: Grouped-Query Attention (GQA) to shrink each token’s footprint, FP8 KV quantization to halve precision bytes, and PagedAttention (pioneered by vLLM) to pack KV blocks into non-contiguous memory pages like an operating system, cutting memory waste from over 60% to under 4%.

05 / Where This Connects

From single-request memory to cross-turn savings

Everything above happens inside a single response. When an API provider saves that exact blue KV cache shelf between requests so your next turn skips the prefill step altogether, you get Prompt Caching.

REFERENCED BY · PHAINO.SPACE

Prompts & Prompt Caching

See how keeping your prefix intact turns KV cache reuse into up to 95% lower API bills across 40-turn agent sessions.

Open guide →