Slides · Inference engineering

Memory and the KV-cache

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.

Source1 Mastering LLM Techniques: Inference Optimization

Math

Sizing the cache

KV bytes per token=2×layers×KV heads×head dim×bytes per value\text{KV bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes per value}KV total=bytes per token×tokens per sequence×sequences\text{KV total} = \text{bytes per token} \times \text{tokens per sequence} \times \text{sequences}
SymbolMeaning
22One key vector and one value vector
layers\text{layers}Transformer layers; each keeps its own cache
KV heads\text{KV heads}Key-value heads, which can be fewer than query heads
head dim\text{head dim}Width of each head (model dimension divided by attention heads)
bytes per value\text{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 dim4 \times \text{layers} \times \text{model dim} bytes at 16 bits.

Sources1 Mastering LLM Techniques: Inference Optimization2 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.

Source3 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.

ModelLayersKV headsKV per tokenOne 8,192-token sequence
8B328128 KiB1.0 GiB
70B808320 KiB2.5 GiB
405B1268504 KiB3.9 GiB

Check one row: 2×80×8×128×2 bytes=327,680 bytes=320 KiB2 \times 80 \times 8 \times 128 \times 2\ \text{bytes} = 327{,}680\ \text{bytes} = 320\ \text{KiB}. A hypothetical 7B-class model with 32 KV heads would need 512 KiB per token, four times the 8B figure.

Source4 The Llama 3 Herd of Models

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,3362 \times 28 \times 128 \times 2 = 14{,}336 bytes per token, so 57,344/14,336=457{,}344 / 14{,}336 = 4 KV heads. Using 28 query heads gives 28×14,336=401,40828 \times 14{,}336 = 401{,}408 bytes, which is 392 KiB, 7 times too large.

Math

From memory to concurrency

KV budget=GPU memory×utilization−weights−overhead\text{KV budget} = \text{GPU memory} \times \text{utilization} - \text{weights} - \text{overhead}sequences=KV budgetbytes per token×tokens per sequence\text{sequences} = \frac{\text{KV budget}}{\text{bytes per token} \times \text{tokens per sequence}}
SymbolMeaning
utilization\text{utilization}Fraction of GPU memory the engine may use; vLLM calls the setting gpu_memory_utilization
weights\text{weights}Model weight bytes, summed over the GPUs
overhead\text{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.

Source5 Optimization and Tuning

Diagram

Worked: Llama 3 8B on one 80 GB GPU

Diagram: Usable memory is split into weights, assumed overhead and the cache pool.

72 GB usable (80 x 0.9)

Weights: 16 GB

Overhead: 5 GB assumed

KV pool: 51 GB

About 389,000 tokens

47 seqs of 8,192

189 seqs of 2,048

Diagram summary: Usable memory is split into weights, assumed overhead and the cache pool. Dividing the 51 GB pool by 128 KiB per token gives about 389,000 tokens of cache, which is 47 sequences at 8,192 tokens or 189 at 2,048.

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))   # 189

A 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,07264 \times 8{,}192 \times 131{,}072 bytes, about 68.7 GB. One GPU leaves 72−16−5=5172 - 16 - 5 = 51 GB, which is too little. Two leave 144−16−5=123144 - 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.

BatchCache read per stepStep at leastAggregate tokens/s at most
12.1 GB5.4 msabout 185
48.4 GB7.3 msabout 549
1633.5 GB14.8 msabout 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.

Source6 NVIDIA H100 Tensor Core GPU

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.516 + 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/1851{,}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.

Source7 Efficient Memory Management for Large Language Model Serving with PagedAttention

Diagram

Blocks and a block table

Diagram: A sequence sees its cache as logical blocks in order, and a block table maps each one to whichever physical block in the pool is free, in...

Logical blocks 0, 1, 2

Block table

Physical block 7

Physical block 2

Physical block 9

Diagram summary: A sequence sees its cache as logical blocks in order, and a block table maps each one to whichever physical block in the pool is free, in any order. Unused blocks stay available to any sequence.

The idea borrows virtual memory from operating systems. The original paper’s default block size was 16 tokens.

Source7 Efficient Memory Management for Large Language Model Serving with PagedAttention

Worked example

Worked: waste for a 700-token sequence

Storage schemeSlots reservedSlots wasted
Contiguous slab for an 8,192-token maximum8,1927,492 (91%)
16-token blocks704 (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

ChangesDoes not change
Memory utilization, so the reachable batch sizeThe 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 laterThe 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.

Source7 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

  1. Split the prompt into blocks. Only full blocks are cached.
  2. 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).
  3. Look each hash up. A hit reuses the stored block and skips its prefill.
  4. 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.

Source8 Automatic Prefix Caching

Diagram

Many requests, one copy

Diagram: Requests that begin with the same tokens point at one stored copy of the prefix blocks.

Request 1

Shared prefix blocks

Request 2

Request 3

Prefill skipped for shared part

Diagram summary: Requests that begin with the same tokens point at one stored copy of the prefix blocks. Prefill is skipped for the shared part, and each request computes and stores only its own tail.

Source8 Automatic Prefix Caching

Worked example

Worked: a 3,000-token shared prefix on the 8B model

QuantityCalculationResult
Full blocks in the prefix3,000/163{,}000 / 16, rounded down187
Tokens cached187×16187 \times 162,992
Tokens still recomputed3,000−2,9923{,}000 - 2{,}9928
One shared copy2,992×128 KiB2{,}992 \times 128\ \text{KiB}about 0.39 GB
Twenty private copies20×0.39 GB20 \times 0.39\ \text{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 cacheResponse cache
StoresAttention keys and values of a shared prompt startWhole finished answers
Hit needsIdentical tokens from the first token, same adapter and modelThe same request again
After a hitThe model still processes the unmatched tokens, then generatesThe stored answer is returned without running the model
HelpsPrefill time (TTFT) and memoryWhole-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.

Source8 Automatic Prefix Caching

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=49631 \times 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.

Source9 SGLang: Efficient Execution of Structured Language Model Programs

Compare

Shrinking the cache by design

TechniqueIdeaEffectCost
Multi-query attentionAll query heads share one KV headSmallest cacheCan lead to quality degradation (GQA paper)
Grouped-query attentionGroups of query heads share a KV headCache shrinks by query heads over KV headsBuilt into the model; multi-head checkpoints can be uptrained using 5 percent of the original pre-training compute
Multi-head latent attentionCache a compressed latent vectorDeepSeek-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 quantizationStore keys and values in fewer bitsCapacity roughly doubles at 8 bitsvLLM 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.

Sources3 GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints10 DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model11 Quantized KV Cache1 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.

Source11 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=5172 - 21 = 51 GB to 76−21=5576 - 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

Diagram: When no block is free an engine can queue new requests, preempt a running sequence and either recompute or swap out its cache later, or...

No free block

Queue new requests

Preempt a sequence

Shed load

Recompute later or swap to CPU

Diagram summary: When no block is free an engine can queue new requests, preempt a running sequence and either recompute or swap out its cache later, or reject load. Queueing raises TTFT; preemption spends compute or transfer time. Shedding load is this course’s own advice; the cited sources describe queueing and preemption.

Sources5 Optimization and Tuning7 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, lower max_num_seqs or max_num_batched_tokens, or add tensor or pipeline parallelism, each with a cost in latency or synchronization.

Sources5 Optimization and Tuning7 Efficient Memory Management for Large Language Model Serving with PagedAttention

Summary

Summary

  • KV bytes per token=2×layers×KV heads×head dim×bytes\text{KV bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes}. Use KV heads.
  • KV budget=memory×utilization−weights−overhead\text{KV budget} = \text{memory} \times \text{utilization} - \text{weights} - \text{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)

  1. Mastering LLM Techniques: Inference Optimization (opens in a new tab)

    Shashank Verma, Neal Vaidya2023Article

    Used for The KV-cache size per token formula and the role of the cache in decoding.

  2. Transformer Inference Arithmetic (opens in a new tab)

    kipply2022Article

    Used for The 4 x layers x model-dimension byte count of the cache at 16 bits for a multi-head model.

  3. GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (opens in a new tab)

    Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, et al.2023EMNLP 2023Paper

    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.

  4. The Llama 3 Herd of Models (opens in a new tab)

    Aaron Grattafiori, Abhimanyu Dubey, Abhinav Jauhri, et al.2024Preprint

    Used for Layer, attention-head and KV-head counts for the 8B, 70B and 405B models.

  5. Optimization and Tuning (opens in a new tab)

    vLLM project2026Documentation

    Used for The gpu_memory_utilization setting, preemption by recompute, the V1 default, and the remedies for preemption.

References

References & Sources (2 of 3)

  1. NVIDIA H100 Tensor Core GPU (opens in a new tab)

    NVIDIA2026Documentation

    Used for The 3.35 TB/s H100 SXM bandwidth used in the speed table.

  2. Efficient Memory Management for Large Language Model Serving with PagedAttention (opens in a new tab)

    Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, et al.2023Preprint

    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.

  3. Automatic Prefix Caching (opens in a new tab)

    vLLM project2026Documentation

    Used for Block hashing from the parent hash, tokens and extras, full-block-only caching, reference counts, LRU eviction and cache salt.

  4. SGLang: Efficient Execution of Structured Language Model Programs (opens in a new tab)

    Lianmin Zheng, Liangsheng Yin, Zhiqiang Xie, Chuyue Sun, et al.2023Preprint

    Used for RadixAttention as a radix tree over token sequences with LRU eviction of leaves.

  5. DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (opens in a new tab)

    DeepSeek-AI2024Preprint

    Used for The reported 93.3 percent KV-cache reduction against DeepSeek 67B using multi-head latent attention.

References

References & Sources (3 of 3)

  1. Quantized KV Cache (opens in a new tab)

    vLLM project2026Documentation

    Used for FP8 cache data types, calibration advice, default scales without calibration, and the absence of accuracy figures.