Slides · Inference engineering
Memory and the KV-cache
1 / 34
Memory and the KV-cache
Turn a memory budget into a number of users, and see what paging, prefix caching and smaller caches change.
By the end you can size the cache from a model’s configuration, convert free memory into concurrent sequences, explain PagedAttention and prefix caching, compare ways to shrink the cache, and say what a server does when the pool is full.
Concept
How many fit?
- Every customer being answered keeps a set of notes in server memory, and each set grows with every word of the conversation.
- Ananya looks at the memory gauge, then the queue. The question is simple: how many conversations fit?
- Overestimate and the server thrashes. Underestimate and money goes to GPUs that were not needed.
- The answer is arithmetic on the model’s configuration, not a guess.
Concept
What the KV-cache trades
- For every token already in a conversation, attention layers keep the keys and values they computed, so a new token computes only its own and reads the rest.
- The cache saves recomputing the whole history at each step. It costs memory that grows with context length, batch size, layers and KV heads.
- On a serving GPU that memory, more than arithmetic, usually decides how many requests fit.
- NVIDIA’s inference post gives the per-token size as
2 * layers * (heads * head dim) * bytes per value.
Math
Sizing the cache
KV bytes per token=2×layers×KV heads×head dim×bytes per valueKV total=bytes per token×tokens per sequence×sequences| Symbol | Meaning |
|---|---|
| 2 | One key vector and one value vector |
| layers | Transformer layers; each keeps its own cache |
| KV heads | Key-value heads, which can be fewer than query heads |
| head dim | Width of each head (model dimension divided by attention heads) |
| bytes per value | 2 for 16-bit, 1 for FP8 or INT8 |
kipply’s post gives the same count for a multi-head model as 4×layers×model dim bytes at 16 bits.
Sources[1] Mastering LLM Techniques: Inference Optimization[2] Transformer Inference Arithmetic
Concept
Use KV heads, not query heads
- Query heads are not cached; only keys and values are.
- With grouped-query attention several query heads share one KV head, so the KV-head count is smaller.
- Sizing with the query-head count overstates the cache by the ratio of the two. At 32 query heads and 8 KV heads that is 4 times.
- The GQA paper (EMNLP 2023) introduced grouped-query attention as a middle road between multi-head and multi-query attention.
Source[3] GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Worked example
Worked: Llama 3 at 16-bit
Layer and head counts from the Llama 3 paper’s architecture table (arXiv, version 3). Head dimension is model dimension divided by attention heads, 128 for all three.
| Model | Layers | KV heads | KV per token | One 8,192-token sequence |
|---|---|---|---|---|
| 8B | 32 | 8 | 128 KiB | 1.0 GiB |
| 70B | 80 | 8 | 320 KiB | 2.5 GiB |
| 405B | 126 | 8 | 504 KiB | 3.9 GiB |
Check one row: 2×80×8×128×2 bytes=327,680 bytes=320 KiB. A hypothetical 7B-class model with 32 KV heads would need 512 KiB per token, four times the 8B figure.
Check yourself
Check: work backwards from a measured size
A model has 28 layers, 28 query heads and head dimension 128, with a 16-bit cache. Its measured cache is 56 KiB per token. How many KV heads does it have, and what size would someone get by wrongly using the query-head count?
Answer
56 KiB is 57,344 bytes. Each KV head costs 2×28×128×2=14,336 bytes per token, so 57,344/14,336=4 KV heads. Using 28 query heads gives 28×14,336=401,408 bytes, which is 392 KiB, 7 times too large.
Math
From memory to concurrency
KV budget=GPU memory×utilization−weights−overheadsequences=bytes per token×tokens per sequenceKV budget| Symbol | Meaning |
|---|---|
| utilization | Fraction of GPU memory the engine may use; vLLM calls the setting gpu_memory_utilization |
| weights | Model weight bytes, summed over the GPUs |
| overhead | Activation workspace and engine overhead (an assumption; it varies by engine and settings) |
vLLM’s tuning page says the engine pre-allocates its KV cache using that percentage of GPU memory.
Diagram
Worked: Llama 3 8B on one 80 GB GPU
Code
The same arithmetic as code
Python
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value):
"""Keys plus values, for every layer and every KV head."""
if not all(v > 0 for v in (layers, kv_heads, head_dim, bytes_per_value)):
raise ValueError("all sizes must be positive")
return 2 * layers * kv_heads * head_dim * bytes_per_value
def max_sequences(gpu_gb, n_gpus, util, weights_gb, overhead_gb, per_token, seq_len):
"""Whole sequences the cache pool holds; 0 when no budget is left."""
if not 0 < util <= 1:
raise ValueError("util must be in (0, 1]")
if not all(0 < v < float("inf") for v in (gpu_gb, n_gpus, per_token, seq_len)):
raise ValueError("memory, GPU count, bytes per token and length must be positive and finite")
if not (0 <= weights_gb < float("inf") and 0 <= overhead_gb < float("inf")):
raise ValueError("weights and overhead must be finite and not negative")
budget_gb = gpu_gb * n_gpus * util - weights_gb - overhead_gb
if budget_gb <= 0:
return 0
return int(budget_gb * 1e9 // (per_token * seq_len))
llama8b = kv_bytes_per_token(32, 8, 128, 2)
print(llama8b // 1024, "KiB per token") # 128
print(max_sequences(80, 1, 0.9, 16, 5, llama8b, 8192)) # 47
print(max_sequences(80, 1, 0.9, 16, 5, llama8b, 2048)) # 189A non-positive or infinite size, GPU count or length, a negative or infinite weights or overhead value, or a utilization outside (0, 1], raises ValueError; NaN fails the same tests. A budget at or below zero returns 0 instead of a negative count.
Concept
Fits is not serves
- The weights of a hypothetical 38B model in BF16 take 76 GB. With a single 80 GB card and 90 percent allowed, the budget is 72 - 76 - overhead, below zero.
- The model fits in the card’s memory on paper and still cannot hold a single sequence.
- The fixes: fewer weight bytes (8-bit weights), more GPUs, or shorter contexts.
- Long context is expensive for the same reason. One 128,000-token sequence on a 320 KiB-per-token model needs about 39 GiB of cache for a single user.
Check yourself
Check: how many GPUs for a target?
A team wants 64 concurrent sequences of 8,192 tokens on the 8B example (128 KiB per token at 16 bits, 16 GB of weights, 0.9 utilization, 5 GB assumed overhead). Using 80 GB GPUs and the budget formula with memory summed over the GPUs, how many are needed?
Answer
The pool must hold 64×8,192×131,072 bytes, about 68.7 GB. One GPU leaves 72−16−5=51 GB, which is too little. Two leave 144−16−5=123 GB, which is plenty. So 2 GPUs under this simplified formula; a real multi-GPU setup has per-GPU overheads and communication that the formula leaves out.
Worked example
The cache also costs speed
Each step reads the weights once for the batch, plus every sequence’s own cache. 8B model, 16 GB of weights, 16,000-token contexts (2.1 GB of cache each), a GPU with 3.35 TB/s.
| Batch | Cache read per step | Step at least | Aggregate tokens/s at most |
|---|---|---|---|
| 1 | 2.1 GB | 5.4 ms | about 185 |
| 4 | 8.4 GB | 7.3 ms | about 549 |
| 16 | 33.5 GB | 14.8 ms | about 1,082 |
The weights are shared by the whole batch, but each cache is not. Aggregate speed stops growing in proportion to the batch as the cache term overtakes the weights.
Check yourself
Check: explain the scaling gap
In the table above, batch 1 gives about 185 tokens per second and batch 16 gives about 1,082, not 16 times 185. Using the byte counts, say why the step time grows and which term is responsible.
Answer
The step grows from 5.4 ms to 14.8 ms. The weights, 16 GB, are read once whatever the batch, but each extra sequence adds its own 2.1 GB of cache: 16+33.5=49.5 GB at batch 16 against 18.1 GB at batch 1. Sixteen tokens per step are produced, but each step takes 2.7 times longer, so output grows by about 5.9 times (1,082/185).
Concept
The fragmentation problem
- The simple design gives each sequence one contiguous slab sized for the longest sequence the server allows.
- Most requests never get that long, so most of the slab sits empty, and gaps between slabs are unusable.
- The PagedAttention paper reports that in the existing systems it profiled, only 20.4 to 38.2 percent of KV-cache memory held actual token states.
- Wasted memory means a smaller batch, which means lower throughput.
Source[7] Efficient Memory Management for Large Language Model Serving with PagedAttention
Diagram
Blocks and a block table
The idea borrows virtual memory from operating systems. The original paper’s default block size was 16 tokens.
Source[7] Efficient Memory Management for Large Language Model Serving with PagedAttention
Worked example
Worked: waste for a 700-token sequence
| Storage scheme | Slots reserved | Slots wasted |
|---|---|---|
| Contiguous slab for an 8,192-token maximum | 8,192 | 7,492 (91%) |
| 16-token blocks | 704 (44 blocks) | 4 (0.6%) |
Blocks are allocated as the sequence grows, so only a sequence’s final block is ever partly filled. Waste per sequence is at most the block size minus one token.
Compare
What paging changes, and what it does not
| Changes | Does not change |
|---|---|
| Memory utilization, so the reachable batch size | The bytes a real token’s keys and values need |
| Sharing of blocks between sequences (parallel sampling, shared prefixes) | The attention arithmetic |
| Preemption: blocks can be swapped to CPU memory or recomputed later | The weights read on each step |
The paper reports 2 to 4 times higher throughput than FasterTransformer and Orca at similar latency. That gain comes from the larger batches the freed memory allows.
Source[7] Efficient Memory Management for Large Language Model Serving with PagedAttention
Check yourself
Check: trace the block table
A sequence has 37 tokens and the engine uses 16-token blocks. How many blocks does it hold, how many more tokens fit before another block is allocated, and what does the block table store for each logical block?
Answer
37 tokens fill two blocks (32 tokens) and put 5 in a third, so it holds 3 blocks. That third block has 11 free slots, so a new block is allocated when the sequence reaches token 49. For each logical block, the block table stores the physical block that holds it, which can be any free block in the pool. That mapping is what removes the need for a large contiguous slab.
Process
How prefix caching finds a match
- Split the prompt into blocks. Only full blocks are cached.
- Hash each block from its parent block’s hash, its own tokens and extra values (such as a LoRA adapter ID or a cache salt).
- Look each hash up. A hit reuses the stored block and skips its prefill.
- Count references: a block in use by any request stays; unreferenced blocks are evicted least-recently-used when memory is needed.
This follows the vLLM design page, retrieved 2026-10-24. The hash chain is why the prefix must match from the very first token.
Diagram
Many requests, one copy
Worked example
Worked: a 3,000-token shared prefix on the 8B model
| Quantity | Calculation | Result |
|---|---|---|
| Full blocks in the prefix | 3,000/16, rounded down | 187 |
| Tokens cached | 187×16 | 2,992 |
| Tokens still recomputed | 3,000−2,992 | 8 |
| One shared copy | 2,992×128 KiB | about 0.39 GB |
| Twenty private copies | 20×0.39 GB | about 7.8 GB |
The partial last block is not cached. With a 400-token unique tail, about 88 percent of each 3,400-token prompt avoids prefill.
Compare
Prefix cache versus response cache
| Prefix cache | Response cache | |
|---|---|---|
| Stores | Attention keys and values of a shared prompt start | Whole finished answers |
| Hit needs | Identical tokens from the first token, same adapter and model | The same request again |
| After a hit | The model still processes the unmatched tokens, then generates | The stored answer is returned without running the model |
| Helps | Prefill time (TTFT) and memory | Whole-request cost and latency |
A prefix cache does not speed up decode. Put static content first and per-request content last, because the match must start at the first token.
Check yourself
Check: where does the match stop?
Two requests share an identical 1,000-token prompt except that token number 500 (counting from 0) differs. With 16-token blocks, how many tokens of the second request can reuse the first request’s cache?
Answer
Token 500 sits in block 31 (tokens 496 to 511). Blocks 0 to 30 are identical, so 31×16=496 tokens match. Block 31 has a different hash, and every later block’s hash depends on its parent, so nothing after it matches either, even though those tokens are identical.
Concept
Another way to organise reuse
- SGLang’s RadixAttention targets the same goal: reuse the KV-cache across requests.
- Its paper keeps cached token sequences in a radix tree and, when memory runs short, frees the least recently used leaves.
- A tree suits branching conversations and agent runs, where many requests share a common start and then diverge.
- The aim is the same as block hashing; the data structure differs.
Source[9] SGLang: Efficient Execution of Structured Language Model Programs
Compare
Shrinking the cache by design
| Technique | Idea | Effect | Cost |
|---|---|---|---|
| Multi-query attention | All query heads share one KV head | Smallest cache | Can lead to quality degradation (GQA paper) |
| Grouped-query attention | Groups of query heads share a KV head | Cache shrinks by query heads over KV heads | Built into the model; multi-head checkpoints can be uptrained using 5 percent of the original pre-training compute |
| Multi-head latent attention | Cache a compressed latent vector | DeepSeek-V2 reports a 93.3 percent smaller cache than DeepSeek 67B (a model-to-model comparison) | Part of the model architecture, so it is not a serving-time switch |
| KV-cache quantization | Store keys and values in fewer bits | Capacity roughly doubles at 8 bits | vLLM docs give no accuracy figures and recommend dataset-calibrated scales |
GQA and MLA are fixed when the model is built; cache quantization is a serving-time setting.
Sources[3] GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints[10] DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model[11] Quantized KV Cache[1] Mastering LLM Techniques: Inference Optimization
Concept
Quantizing the cache: validate first
- vLLM’s quantized-cache page (retrieved 2026-10-24) lists FP8 data types and says that without calibration all scales default to 1.0.
- It recommends calibrating against a dataset for the best quality, and notes that some layer types, such as sliding-window attention, are more sensitive.
- It publishes no accuracy numbers, so the cost for any given model must be measured.
- Test on your own evaluation set, with the longest contexts you serve, and compare the answers with a 16-bit cache run.
Source[11] Quantized KV Cache
Check yourself
Check: which lever buys what?
A cache-limited server wants more concurrency. Using the 8B example (80 GB, 16 GB weights, 5 GB overhead), compare: (a) raise utilization from 0.90 to 0.95, (b) store the cache in FP8, (c) move to a model with half the KV heads. Roughly what does each buy, and which need validation?
Answer
(a) The pool grows from 72−21=51 GB to 76−21=55 GB, about 8 percent more sequences, with less headroom for spikes. (b) Capacity roughly doubles, but it is a serving choice whose accuracy cost must be measured on long inputs. (c) Also roughly doubles, but it is a different model, so quality has to be compared on your own evaluation set.
Diagram
When the pool is full
Sources[5] Optimization and Tuning[7] Efficient Memory Management for Large Language Model Serving with PagedAttention
Concept
Reading the symptoms and the levers
- vLLM’s tuning page says preempted requests are recomputed when space returns, that this can raise end-to-end latency, and that in V1 the default mode is recompute. The original paper also describes swapping blocks to CPU memory.
- The cumulative preemption count is available through vLLM’s Prometheus metrics. Alert on it, not only on GPU utilization.
- Repeated preemption (this course calls it a preemption storm; the term is not vLLM’s) shows as busy GPUs and falling goodput: the engine spends its time evicting sequences and redoing their work.
- Levers on that page: raise
gpu_memory_utilization, lowermax_num_seqsormax_num_batched_tokens, or add tensor or pipeline parallelism, each with a cost in latency or synchronization.
Sources[5] Optimization and Tuning[7] Efficient Memory Management for Large Language Model Serving with PagedAttention
Summary
Summary
- KV bytes per token=2×layers×KV heads×head dim×bytes. Use KV heads.
- KV budget=memory×utilization−weights−overhead; divide by bytes per sequence for concurrency.
- Fits is not serves: weights that fit can leave no room for a cache.
- Each decode step also reads every sequence’s cache, so it limits speed as well as count.
- PagedAttention cuts waste and raises batch size; it changes neither the bytes per token nor attention speed.
- Prefix caching needs an identical start, the same adapter and the same engine, and saves prefill and memory.
- GQA, MLA and KV quantization shrink the cache; each has a cost to validate. A full pool means queueing, preemption or shedding.
References
References & Sources (1 of 3)
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
Shashank Verma, Neal Vaidya2023Article
https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/
Used for The KV-cache size per token formula and the role of the cache in decoding.
Transformer Inference Arithmetic (opens in a new tab)
kipply2022Article
https://kipp.ly/transformer-inference-arithmetic/
Used for The 4 x layers x model-dimension byte count of the cache at 16 bits for a multi-head model.
Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, et al.2023EMNLP 2023Paper
DOI 10.18653/v1/2023.emnlp-main.298 (opens in a new tab)arXiv 2305.13245 (opens in a new tab)https://aclanthology.org/2023.emnlp-main.298/
Used for Grouped-query attention as a middle road between multi-head and multi-query, MQA quality degradation, and uptraining with 5 percent of pre-training compute.
The Llama 3 Herd of Models (opens in a new tab)
Aaron Grattafiori, Abhimanyu Dubey, Abhinav Jauhri, et al.2024Preprint
arXiv 2407.21783 (opens in a new tab)https://arxiv.org/abs/2407.21783
Used for Layer, attention-head and KV-head counts for the 8B, 70B and 405B models.
Optimization and Tuning (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/latest/configuration/optimization.html
Used for The gpu_memory_utilization setting, preemption by recompute, the V1 default, and the remedies for preemption.
References
References & Sources (2 of 3)
NVIDIA H100 Tensor Core GPU (opens in a new tab)
NVIDIA2026Documentation
https://www.nvidia.com/en-us/data-center/h100/
Used for The 3.35 TB/s H100 SXM bandwidth used in the speed table.
Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, et al.2023Preprint
arXiv 2309.06180 (opens in a new tab)https://arxiv.org/abs/2309.06180
Used for The 20.4 to 38.2 percent memory use figure, block tables, the default block size of 16, preemption by swapping or recomputing, and the 2 to 4 times throughput result.
Automatic Prefix Caching (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/stable/design/prefix_caching/
Used for Block hashing from the parent hash, tokens and extras, full-block-only caching, reference counts, LRU eviction and cache salt.
SGLang: Efficient Execution of Structured Language Model Programs (opens in a new tab)
Lianmin Zheng, Liangsheng Yin, Zhiqiang Xie, Chuyue Sun, et al.2023Preprint
arXiv 2312.07104 (opens in a new tab)https://arxiv.org/abs/2312.07104
Used for RadixAttention as a radix tree over token sequences with LRU eviction of leaves.
DeepSeek-AI2024Preprint
arXiv 2405.04434 (opens in a new tab)https://arxiv.org/abs/2405.04434
Used for The reported 93.3 percent KV-cache reduction against DeepSeek 67B using multi-head latent attention.
References
References & Sources (3 of 3)
Quantized KV Cache (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/latest/features/quantization/quantized_kvcache.html
Used for FP8 cache data types, calibration advice, default scales without calibration, and the absence of accuracy figures.
Keys: ← → move, Home End first and last, F full screen.