Phase 04/Faster kernels and memory/KV cache optimization
PHASE 04 · Faster kernels and memory

KV cache optimization

0%
7 h6 subtopics3 lessons · 1 required
In plain English

While a model writes an answer it keeps notes about every word it has seen so far, so it does not have to reread the whole conversation for each new word. Those notes are the KV cache, and for long chats they take more GPU memory than the model itself. Optimizing the cache is like managing a crowded parking garage. You can make each car smaller (compress the notes to fewer bits), share one spot between cars that are identical (reuse notes for a repeated system prompt), tow cars that have not moved in a while (evict old tokens), or change how spots are assigned so there are no half-empty rows (avoid fragmentation). Every spot you free lets one more request run at the same time, which is how throughput goes up.

Why it matters

KV cache size sets the maximum batch size and therefore throughput of a serving engine; it is also the per-token memory read during decode. Prefix caching, FP8 KV, GQA and eviction policies are the knobs an inference engineer turns daily, and fragmentation is why PagedAttention exists.

Hiring signal

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

Learning objectives

  • Compute KV cache bytes per token for a given model config and precision and compare with weight memory.
  • Quantify internal and external fragmentation under naive contiguous allocation versus paged allocation in a simulation.
  • Explain prefix caching, FP8 KV cache, GQA/MQA and eviction policies as four different ways of reducing cache cost.
  • Measure the throughput effect of enabling prefix caching and FP8 KV in vLLM.

Key concepts

KV bytes per token
2 * n_layers * n_kv_heads * head_dim * bytes_per_element; the number that bounds concurrency.
Internal fragmentation
Memory reserved for a request's maximum length but never used because the request finished early.
External fragmentation
Free memory split into gaps too small for any new request, even though the total free is large.
Block table
The per-request mapping from logical token positions to physical cache blocks in PagedAttention.
Prefix caching
Hashing completed blocks so identical prompt prefixes (system prompts, few-shot examples) share physical blocks.
GQA / MQA
Grouped-query and multi-query attention share K and V across query heads, shrinking the cache by the group factor.
FP8 KV cache
Storing K and V in 8-bit floating point with per-tensor or per-head scales, halving cache bytes versus FP16.
Eviction and preemption
Policies for what to drop when the cache is full; recompute versus swap to CPU, and token-level eviction schemes like H2O or StreamingLLM.

Subtopics

  1. 1. Sizing the cache

    Derive bytes per token from config.json, compute max concurrent tokens on a given GPU, and compare Llama-style MHA against GQA models.

  2. 2. Fragmentation in contiguous allocation

    Why pre-reserving max_tokens per request wastes 60-80 percent of memory and why variable-length completions make it worse.

  3. 3. Paged allocation and block tables

    Fixed-size blocks (16 tokens), a free list, and per-request block tables remove external fragmentation and cap internal waste to one block.

  4. 4. Prefix caching and copy-on-write

    Hash-based block reuse for shared prompt prefixes, reference counting, and copy-on-write for beam search and parallel sampling.

  5. 5. Compressing the cache

    FP8 or INT8 KV with scales, GQA at model-design time, and token eviction methods that keep only attention sinks and recent tokens.

  6. 6. Cache offload and preemption

    Swapping blocks to CPU memory versus recomputing on preemption; the bandwidth math that decides which is cheaper.

Resources

Hands-on lessons

L1

Simulate contiguous versus paged KV allocation

CPU · your Macscript120 minrequired

Goal · Write a discrete-event simulator that admits requests with random prompt and output lengths under two allocators and reports utilization and throughput.

  1. 1Define a GPU with a fixed KV budget in tokens (e.g. 65,536) and a request generator with prompt lengths from a lognormal and output lengths capped at max_tokens=1024.
  2. 2Implement a contiguous allocator that reserves prompt_len + max_tokens per request up front and frees on completion.
  3. 3Implement a paged allocator with 16-token blocks, a free list and per-request block tables that grows one block at a time.
  4. 4Run both for 10,000 simulated decode steps, admitting new requests whenever memory allows; log used tokens, reserved tokens and completed requests.
  5. 5Compute internal fragmentation (reserved minus used) and the number of concurrent requests over time for both.
  6. 6Add prefix caching by giving 50 percent of requests a shared 512-token system prompt and reference-counting those blocks; re-run.
  7. 7Plot concurrency and utilization over time for the three configurations.
Deliverable
The simulator script and a plot comparing contiguous, paged and paged+prefix-cache runs.
Check
Paged allocation sustains at least 2x the concurrent requests of contiguous allocation; prefix caching raises it further and the internal waste of paged is under one block per request.
L2

Size the cache for real models

CPU · your Macnotebook45 minoptional

Goal · Compute KV bytes per token and maximum concurrent tokens for five Hub models on a 24 GB and an 80 GB GPU.

  1. 1Fetch config.json for gpt2, Llama-2-7B, Llama-3-8B, Mistral-7B and a Qwen model using huggingface_hub without downloading weights.
  2. 2Extract n_layers, hidden size, num_attention_heads, num_key_value_heads and compute head_dim.
  3. 3Compute KV bytes per token in FP16 and FP8, and weight memory in FP16.
  4. 4For each model compute the tokens that fit in the remaining memory of a 24 GB and an 80 GB GPU after weights, with 90 percent utilization.
  5. 5Tabulate and note which models use GQA and by how much it reduces the cache.
Deliverable
A table of bytes-per-token, weight memory and max resident tokens per model and GPU.
Check
Llama-2-7B shows about 0.5 MB per token in FP16 and Llama-3-8B shows about 4x less due to GQA.
L3

Measure prefix caching and FP8 KV in vLLM

Colab T4 · freeexperiment90 minoptional

Goal · Show the throughput change from enabling prefix caching and an FP8 KV cache on a small model with a shared system prompt workload.

  1. 1In Colab, start vllm serve with a small instruct model and --max-model-len 2048; note the "GPU KV cache size" line in the startup log.
  2. 2Build a workload of 64 requests sharing a 600-token system prompt followed by a unique 50-token question; send with an asyncio client and record total time and TTFT.
  3. 3Restart with --enable-prefix-caching and repeat; compare TTFT and total time.
  4. 4Restart with --kv-cache-dtype fp8 and compare the reported KV cache size in tokens and the throughput. (FP8 KV storage works on the T4 via software conversion; if vLLM refuses on your build, skip this configuration and note it, or run this step on a rented L4.)
  5. 5Write a short paragraph explaining each delta in terms of the lesson l1 simulation.
Deliverable
A table of KV cache tokens, TTFT and total time for the three configurations.
Check
Prefix caching cuts TTFT substantially on the shared-prefix workload; FP8 KV roughly doubles the reported cache token capacity.
Fallback
Skip the GPU run and instead compute the expected capacities from the l2 notebook for the same model and configurations.

Build your own

Build your own KV cache compressor

PythonCPU · your Mac~7 h

A drop-in KV cache for Qwen2.5-0.5B that stores keys and values in int8 or fp8, keeps only the GQA heads, and slides a window with attention sinks, reporting bytes per token and the accuracy each trick costs.

The real thing: docs.vllm.ai/en/latest/features/quantization/quantized_kvcache.html ↗

How you know a stage passes

Write tests/test_kvc.py first. Every stage plugs your Cache subclass into transformers' Qwen2.5-0.5B (fp32 on CPU, 24 layers, 14 query heads, 2 KV heads, head_dim 64) and asserts two things on 5 fixed prompts: a bytes-per-token figure that equals a formula you derive, and an accuracy figure (mean KL of next-token logits against the uncompressed cache over 64 decode steps, or perplexity on a fixed 2,048-token passage). A CLI `kvc.py --kv fp16|int8|fp8 --window N --sinks S` prints the same numbers and writes results.csv. 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. 01an instrumented pass-through cache
    Your Cache subclass stores K and V exactly as transformers does but exposes bytes_per_token() and total_bytes().
    test · Greedy tokens are identical to the stock cache for 64 steps; bytes_per_token() returns 12,288 for fp16 storage (2 * 24 layers * 2 heads * 64 * 2 bytes), asserted against the formula and against the sum of tensor nbytes.
  2. 02int8 keys and values with per-head, per-token scales
    K and V are quantized on write with absmax scales per (layer, head, token) and dequantized on read.
    test · Mean KL against the fp16 cache over 64 steps is below 0.01 on all 5 prompts; bytes_per_token() equals 6,144 plus 2 * 24 * 2 * 2 bytes of scales, asserted exactly.
  3. 03fp8 e4m3 keys and values
    The same cache with torch.float8_e4m3fn storage (or your Phase-4 float-formats encoder) and a per-head scale so that values are brought into the e4m3 range.
    test · Mean KL is below 0.02 on all prompts and the test prints int8 versus fp8 KL side by side; bytes_per_token() is the same as int8 minus the per-token scales you no longer need.
  4. 04make GQA sharing visible
    A naive layout that materialises repeat_kv for all 14 query heads is implemented next to the correct 2-head layout, and attention reads gather through a head-group map.
    test · Both layouts produce identical attention outputs; the naive layout's bytes_per_token() is exactly 7x the correct one, and the test asserts the ratio.
  5. 05sliding window with attention sinks
    The cache keeps the first S tokens and the most recent W tokens, evicting the rest in place, with positions handled so the model does not see a gap.
    test · Cache bytes never exceed (S + W) * bytes_per_token during a 1,024-token generation; perplexity on the fixed passage with W 512 and S 4 is within 1.0 of the full cache, while W 512 with S 0 is more than 5.0 worse, both printed by the test.
  6. 06the budget report
    `kvc.py report --budget-gb 1` evaluates every combination of storage type and window and prints bytes per token, max context that fits the budget, KL and perplexity delta.
    test · results.csv has a row per configuration; the fp8 configuration fits at least 1.9x more tokens than fp16 in the same budget; the README has the table and a paragraph on which configuration you would ship for a 32k-context chat workload.

Knowledge check

QWhy does the KV cache often matter more than weight memory for throughput?

Weights are fixed, but the cache grows with every concurrent token, so the free memory after weights decides how many requests can be in flight.

QWhat is the maximum internal fragmentation per request under PagedAttention with 16-token blocks?

Less than one block, i.e. at most 15 unused token slots in the last block.

QHow does GQA reduce KV cache size?

Several query heads share one K and one V head, so the cache stores n_kv_heads instead of n_heads; Llama-3-8B uses 8 KV heads for 32 query heads, a 4x reduction.

QWhen is swapping KV blocks to CPU worse than recomputing them?

When PCIe bandwidth makes the round trip slower than re-running prefill, which is common for short prompts on fast GPUs.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 simulator and plot saved and the check passes.
  • Can compute KV bytes per token for any config.json without looking up the formula.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →