Phase 01/How generation actually runs/KV cache
PHASE 01 · How generation actually runs

KV cache

0%
7 h5 subtopics2 lessons · 2 required
In plain English

When a model writes a reply one token at a time, each new token has to look back at everything before it. Without help it would recompute the attention keys and values for the whole conversation at every step, like rereading an entire book from page one before writing each new sentence. The KV cache is a notebook where the model writes down the keys and values for each token the first time it sees it, so later steps just read the notebook and add one line. This turns a cost that grows with the square of the length into one that grows linearly, but the notebook takes memory, often more than the model itself when many conversations run at once, so managing that memory is the central problem of LLM serving.

Why it matters

KV cache memory, not weights, is what limits how many requests a GPU can serve at once, and the cache's size per token is a formula you will use weekly. PagedAttention, GQA, quantised caches and prefix caching are all answers to the question this topic raises.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain why keys and values can be cached while queries cannot.
  • Compute KV cache bytes per token from a model config and verify against a real cache object.
  • Measure the speedup of cached versus uncached generation on a CPU.
  • Implement a KV cache in nanoGPT and show identical greedy output.
  • Compare cache size per token for GPT-2, TinyLlama (GQA) and Llama-2-7B.

Key concepts

KV cache
Stored K and V tensors for every past token at every layer, shaped (layers, 2, B, kv_heads, T, head_dim).
Cache bytes per token
2 * n_layers * n_kv_heads * head_dim * bytes_per_element; the number that sizes a serving deployment.
Quadratic vs linear generation
Without a cache, generating N tokens costs O(N^2) token-forwards; with a cache it costs O(N).
past_key_values
The Hugging Face name for the cache object returned by a forward and passed to the next step.
Cache growth
The cache grows by one position per decode step; naive implementations reallocate and copy, which is what PagedAttention later fixes.
Prefix sharing
Requests with an identical prompt prefix can share cache entries; a motivation for block-structured caches.
Cache precision
Storing K and V in fp16, fp8 or int8 halves or quarters cache memory at some accuracy cost.

Subtopics

  1. 1. What can be cached and why

    The causal mask makes K and V of past tokens fixed; Q is only needed for the current token, so it is never stored.

  2. 2. Cache size arithmetic

    Derive bytes per token for GPT-2 small (73,728 fp32), TinyLlama (22,528 fp16 with GQA) and Llama-2-7B (524,288 fp16).

  3. 3. Generation with and without a cache

    The decode loop with past_key_values versus re-running the full sequence; measured timings on CPU.

  4. 4. Implementing a cache

    Concatenating new K and V onto stored tensors inside attention, handling positions, and the memory copies this causes.

  5. 5. Cache memory in serving

    Why cache, not weights, caps concurrency; fragmentation and over-reservation problems that Phase 3 solves.

Resources

Hands-on lessons

L1

Measure cached vs uncached generation and cache memory on CPU

CPU · your Macexperiment90 minrequired

Goal · Produce timing curves for generation with and without the KV cache and verify the cache's byte size against the formula for GPT-2 and TinyLlama.

  1. 1Load gpt2 in fp32 on CPU; build a 64-token prompt; set torch.set_num_threads to your core count.
  2. 2Generate 128 tokens greedily with model.generate(use_cache=True) and again with use_cache=False, timing each; confirm the token ids are identical.
  3. 3Write your own loop that records the wall time of each decode step for both modes; plot step time vs step index.
  4. 4After a 512-token prefill, sum numel()*element_size() over every key and value tensor in past_key_values (DynamicCache exposes per-layer key and value tensors; call to_legacy_cache() if needed).
  5. 5Compare the measured bytes with 2 * 12 * 768 * 4 * 512 and report the ratio.
  6. 6Repeat the byte measurement with TinyLlama in bfloat16 for a 512-token prompt and compare with 2 * 22 * 4 * 64 * 2 * 512.
  7. 7Compute how many 2048-token conversations of TinyLlama cache fit in 16 GB alongside the 2.2 GB of bf16 weights.
Deliverable
A plot of per-step latency for both modes, a table of measured vs formula bytes for both models, and the concurrency number.
Check
Uncached per-step time grows roughly linearly with step index while cached stays flat; measured cache bytes match the formula within 1 percent for both models (37,748,736 for GPT-2 at 512 tokens fp32).
L2

Add a KV cache to nanoGPT

CPU · your Macscript120 minrequired

Goal · Modify nanoGPT's CausalSelfAttention and GPT.generate to use a KV cache and show identical output with a measured speedup.

  1. 1In your annotated nanoGPT, add an optional past_kv argument to CausalSelfAttention.forward that concatenates cached k and v along the sequence dimension and returns the new (k, v).
  2. 2Thread the cache through Block.forward and GPT.forward, returning a list of per-layer (k, v) tuples.
  3. 3Fix position embeddings so a single new token receives position index equal to the current cache length.
  4. 4Write generate_cached that does one full-prompt forward then feeds one token per step; keep the original generate as the baseline.
  5. 5Run both with GPT.from_pretrained('gpt2') on the same 32-token prompt for 100 greedy steps and assert identical token ids.
  6. 6Time both loops and report the speedup; also time 300 steps to see the gap widen.
  7. 7Print the cache tensor shapes and total bytes after 132 tokens and compare with the formula.
Deliverable
A diff against upstream model.py plus a script output showing the assertion, timings and cache bytes.
Check
Token ids are identical for 100 steps, the cached loop is at least 2x faster at 100 steps, and cache bytes equal 2*12*768*4*132 = 9,732,096.

Build your own

Build your own KV cache

PythonCPU · your Mac~6 h

A block-allocated, prefix-sharing KV cache for a tiny decoder, written from scratch and verified against a cache-free forward pass.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/core/kv_cache_manager.py ↗

How you know a stage passes

Write tests/test_kv.py first. Every stage adds a test that compares your cached decoder's logits with an uncached GPT-2-small forward pass on the same tokens (torch.allclose, atol 1e-4), plus a byte-count assertion. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01a contiguous cache for one sequence
    Your decoder accepts past (K, V) tensors per layer and returns new ones; generation feeds one token per step.
    test · 64 greedy tokens from the cached loop equal the uncached loop token-for-token; cache bytes equal 2 * layers * d_model * 4 * seq_len.
  2. 02fixed-size blocks and a block table
    K/V live in a pool of 16-token blocks; each sequence owns a list of block ids; attention gathers through the table.
    test · Same token equality as s1; a 100-token sequence occupies exactly 7 blocks; freeing a sequence returns its blocks to the pool.
  3. 03batching sequences of different lengths
    Several sequences decode together; the block table is [num_seqs, max_blocks] with padding; no sequence reads another's blocks.
    test · Batch of 4 prompts with lengths 10 to 200 produces the same tokens as running each alone.
  4. 04prefix sharing with reference counts
    Sequences that share a prompt prefix share its blocks (copy-on-write on the first divergent block); blocks carry refcounts.
    test · 8 sequences sharing a 64-token system prompt use 4 shared blocks plus their own tails; total blocks equal the formula you derive; tokens still match.
  5. 05eviction under a memory budget
    With a fixed block pool, admitting a new sequence may preempt the most recent one (recompute on resume) instead of crashing.
    test · With a 32-block pool and 6 long sequences, generation completes for all, no out-of-blocks error, and the final tokens still match the reference.
  6. 06measure it
    A benchmark script reports per-step latency and bytes for cached versus uncached decoding at 128 and 512 tokens.
    test · Cached per-step latency is flat with sequence length while uncached grows; your README has the plot and the two numbers.

Knowledge check

QWhy do we cache K and V but not Q?

Past tokens' K and V are reused by every future query, but a token's Q is used only once, at its own step, so storing it would save nothing.

QHow many bytes per token does Llama-2-7B's KV cache need in fp16?

2 * 32 layers * 32 heads * 128 head_dim * 2 bytes = 524,288 bytes, half a MiB per token, about 1 GiB per 2048-token sequence.

QWhat is the asymptotic cost of generating N tokens without a cache versus with one?

O(N^2) token-forwards without (each step reprocesses the whole sequence) versus O(N) with.

QHow does GQA reduce KV cache size without changing the number of attention heads?

Several query heads share one K/V head, so only n_kv_heads of K and V are stored; TinyLlama stores 4 instead of 32, an 8x reduction.

QWhy can the KV cache limit a serving system more than the weights do?

Weights are fixed, but the cache grows with every concurrent request and every token, so at high concurrency or long contexts it exceeds the weight footprint.

Completion

  • All 5 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 checks pass.
  • Can compute KV cache bytes per token for any model from its config.json in under a minute.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →