Memory and the KV-cache

  • Production
  • 45 min
  • Lesson 2 of 7 in Inference engineering
  • Last verified

Open slides(34 slides)

Before you start

You will be able to

  • Compute KV-cache bytes per token and per request from layers, KV heads, head dimension and precision, using KV heads rather than query heads.
  • Turn a GPU memory budget (usable memory minus weights and overhead) into a number of concurrent sequences, explain why a model that fits does not necessarily serve, and say how cache reads limit decode speed at large batch.
  • Explain how PagedAttention blocks and block tables remove waste, and say what it does not change.
  • Explain how prefix caching reuses KV blocks, what makes a prefix reusable, and how it differs from a response cache.
  • Compare grouped-query attention, latent attention and KV quantization by effect and cost, and describe what a server does when the cache pool is full.

Every customer being answered keeps a set of notes in the server’s memory, and each set grows with every word of the conversation.

Ananya looks at the memory gauge, then at the queue, then at Latency the cat, who has chosen the warm server rack for a nap.

“How many fit?” she asks nobody in particular. Latency does not move.

Concept

The notes in the story are the KV-cacheKV cacheStored key and value vectors of earlier tokens, reused at each decode step so they are not recomputed. It saves compute but its memory grows with context length and concurrent requests. It is not a response cache.Open the glossary entry: for every token already in a conversation, the model keeps the keys and values its attention layers computed, so each new token only has to compute its own and read the rest. How LLMs work introduced the idea, and LLM inference and serving gave a first capacity estimate. This lesson makes the estimate precise and then covers the tools engines use to stretch it: paging, prefix caching, and architectures that need fewer bookmarks.

The cache trades compute for memory. It saves redoing the projections for the whole history at every step, and it costs memory that grows with context length, batch size, layers and KV heads. On a serving GPU that memory, not arithmetic, usually decides how many requests fit.

Why It Matters

“How many users does one GPU serve?” is a memory question, and getting it wrong in either direction costs money: overestimate and the server thrashes, underestimate and you buy GPUs you do not need. The cache also adds bytes to every decode step, so it limits speed as well as count. Interviewers like this topic because it needs a formula, an assumption list and a judgment about trade-offs, all in a few minutes.

Mental Model

The shelf is the GPU’s free memory after the model has taken its share. Each customer’s notes take shelf space in proportion to how long their conversation is. Paging means the shelf is divided into small fixed bays that notes can occupy in any order, instead of every conversation reserving a plank long enough for the longest conversation. Prefix cachingPrefix cachingReusing the KV cache of a prompt prefix shared by requests, so the shared part is not recomputed. The serving-engine counterpart of a provider's prompt caching.Open the glossary entry means that if forty customers begin with the same page, you keep one copy of it and let them all point at it. Fewer notes per word, through a better-designed model, matters more than any shelving trick.

Sizing the cache

Per token, the cache stores one key vector and one value vector for each KV head in each layer:

KV bytes per token=2×layers×KV heads×head dimension×bytes per value\text{KV bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dimension} \times \text{bytes per value} KV total=bytes per token×tokens per sequence×concurrent sequences\text{KV total} = \text{bytes per token} \times \text{tokens per sequence} \times \text{concurrent sequences}

The 22 is key plus value. Use KV heads, not attention heads. A model with grouped-query attention has fewer KV heads than query heads, and sizing with the query-head count overstates the cache several times over.

Real configurations (accessed 2026-10-21): the Llama 3 paper’s architecture table lists 32 layers, 32 attention heads and 8 KV heads for the 8B model; 80 layers, 64 attention heads and 8 KV heads for the 70B model; and 126 layers, 128 attention heads and 8 KV heads for the 405B model. Head dimension is model dimension divided by attention heads, which is 128 for all three. In 16-bit values:

ModelLayersKV headsHead dimKV per tokenOne 8,192-token sequence
Llama 3 8B328128128 KiB1.0 GiB
Llama 3 70B808128320 KiB2.5 GiB
Llama 3 405B1268128504 KiB3.9 GiB
A 7B-class model with full multi-head attention (32 KV heads, hypothetical)3232128512 KiB4.0 GiB

The last row is a contrast case, not a specific model: with the same layers and head size, full multi-head attention costs four times the 8-KV-head design.

For scale, the PagedAttention paper (Kwon et al., 2023) works out 800 KB per token for OPT-13B (2×5,120 hidden size×40 layers×2 bytes2 \times 5{,}120\ \text{hidden size} \times 40\ \text{layers} \times 2\ \text{bytes}).

From memory to concurrency

A GPU’s memory holds four things: the weights, the KV pool, activation workspace, and engine overhead. Engines let you set the fraction of memory they may use (vLLM calls it gpu_memory_utilization). The KV budget is what is left:

KV budget=GPU memory×utilization−weights−overhead\text{KV budget} = \text{GPU memory} \times \text{utilization} - \text{weights} - \text{overhead}

Worked example, with stated assumptions: Llama 3 70B in BF16 (140 GB of weights) on four 80 GB GPUs, utilization 0.9, and an assumed 4 GB of overhead per GPU (illustrative; real overhead depends on the engine and settings).

Diagram: Usable GPU memory is split between the weights, engine overhead and the KV pool.

4 GPUs × 80 GB × 0.9 utilization = 288 GB usable

Weights: 140 GB

Overhead: 4 GB × 4 = 16 GB (assumed)

KV pool: 288 − 140 − 16 = 132 GB

At 320 KiB per token: about 403,000 tokens

about 49 sequences of 8,192 tokens

about 196 sequences of 2,048 tokens

Diagram summary: Usable GPU memory is split between the weights, engine overhead and the KV pool. The pool, divided by the cache bytes per token, gives the total tokens of cache, and dividing that by the sequence length gives how many requests fit. Longer contexts mean fewer concurrent requests.
  • Usable: 4×80×0.9=288 GB4 \times 80 \times 0.9 = 288\ \text{GB}. Minus weights 140 GB, minus overhead 16 GB: 132 GB for the cache.
  • At 320 KiB (327,680 bytes) per token: 132×109÷327,680≈403,000132 \times 10^{9} \div 327{,}680 \approx 403{,}000 tokens of cache.
  • At 8,192 tokens per sequence: about 49 sequences. At 2,048 tokens: about 196.
  • Storing the cache in FP8 halves the bytes per token and doubles those counts.

The same arithmetic on two such GPUs: usable 144 GB, minus 140 GB of weights, minus 8 GB of overhead is negative. The model’s weights fit in memory, and the server cannot hold a single long sequence. Fits is not serves. The fixes are fewer weight bytes (quantize to FP8, 70 GB, which leaves 66 GB and roughly 24 sequences of 8,192 tokens), more GPUs, or shorter contexts.

This is also why long-context traffic is expensive. One 128,000-token sequence on the 70B model needs 128,000×320 KiB128{,}000 \times 320\ \text{KiB}, about 39 GiB of cache for a single user.

The cache also costs speed

Every decode step reads the weights once for the whole batch, and it also reads each sequence’s own cache. Lesson 1’s bound ignored the second term. Take the 8B model on an H100 (3.35 TB/s), 16 GB of weights and 8,192-token sequences, where each sequence’s cache is 1.0 GiB (about 1.07 GB):

BatchCache bytes read per stepStep time at leastAggregate tokens per second at most
11.07 GB5.1 msabout 196
88.6 GB7.3 msabout 1,090
3234.4 GB15.0 msabout 2,130

At batch 32 the cache is more than twice the weights, and the weights-only ceiling of about 6,700 tokens per second from lesson 1 drops to about 2,100. This is the second limit on batching promised there: the weights are shared across the batch, but each cache is not. It also explains why per-token latency degrades as context grows.

The fragmentation problem and PagedAttention

The simple way to store a sequence’s cache is 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 go unusable. The PagedAttention paper reports that in existing systems only 20.4 to 38.2 percent of KV-cache memory held actual token states.

PagedAttentionPagedAttentionStoring the KV cache in on-demand blocks to avoid fragmentation, which allows larger batches and prefix sharing.Open the glossary entry borrows virtual memory from operating systems. The pool is divided into fixed-size blocks (vLLM’s default is 16 tokens). Each sequence has a block table that maps its logical blocks to whichever physical blocks are free. Blocks are allocated as the sequence grows, so the waste per sequence is at most part of one block.

Diagram: A sequence’s three logical blocks are mapped by a block table to physical blocks 7, 2 and 9 in the pool, in no particular order.

GPU KV pool, physical blocks

Sequence A, logical order

block 0

block 1

block 2

Block table for A:
0 to physical 7, 1 to 2, 2 to 9

#2

#7

#9

free list

Diagram summary: A sequence’s three logical blocks are mapped by a block table to physical blocks 7, 2 and 9 in the pool, in no particular order. Unused blocks stay on a free list for any sequence to claim.

Worked example: a 1,000-token sequence needs 63 blocks of 16 tokens, which is 1,008 slots, so 8 are wasted (0.8 percent). Reserving a contiguous 8,192-token slab for it would leave 88 percent of the slab empty.

Storage schemeSlots reserved for a 1,000-token sequenceSlots wasted
Contiguous slab for an 8,192-token maximum8,1927,192 (88%)
PagedAttention, 16-token blocks1,0088 (0.8%)

What PagedAttention changes: memory utilization, and therefore the batch size you can reach. Because blocks are addressable, it also enables sharing between sequences (parallel sampling and shared prefixes) and lets an engine preempt a sequence and bring it back later. What it does not change: the real bytes of a token’s keys and values, and it does not make the attention arithmetic faster. The paper reports 2 to 4 times higher throughput than FasterTransformer and Orca at the same latency; those gains come from the larger batches that the freed memory allows.

Prefix caching

Many requests start with the same tokens: a system prompt, tool definitions, few-shot examples, a shared document. If the KV blocks for that prefix are already computed, a new request skips prefill for the shared part.

vLLM’s design documentation (accessed 2026-10-21) describes the mechanism. Each full block gets a hash built from the parent block’s hash, the block’s own tokens, and extra values that make it unique, such as a LoRA adapter ID. Only full blocks are cached. A new request’s blocks are hashed and looked up. Blocks are reference-counted, so a block in use by any request stays; when memory is needed, the least recently used free blocks are evicted. SGLang’s RadixAttention (Zheng et al., 2023) pursues the same goal of KV-cache reuse across requests, organising cached prefixes in a radix tree, which suits branching conversations and agent runs.

Worked example: an 8B model serves a support bot whose every request begins with the same 6,000-token policy prompt followed by about 500 unique tokens.

Diagram: Requests that start with the same tokens point at one shared copy of the prefix’s cache blocks, which are reference counted, instead of...

Request 1: shared prefix + unique tail

Shared prefix blocks
6,000 tokens, one copy, reference counted

Request 2: shared prefix + unique tail

Request 50: shared prefix + unique tail

Prefill skipped for the shared part

Own tail blocks

Own tail blocks

Own tail blocks

Diagram summary: Requests that start with the same tokens point at one shared copy of the prefix’s cache blocks, which are reference counted, instead of each holding its own. Prefill is skipped for the shared part, and each request only computes and stores its own unique tail.
  • Prefill: 6,000 of 6,500 tokens (92 percent) need no recomputation once the prefix is cached.
  • Memory: one copy of the prefix is 6,000×128 KiB6{,}000 \times 128\ \text{KiB}, about 0.79 GB. Fifty concurrent requests with private copies would hold 39 GB for it. Shared, they hold 0.79 GB.

Rules that decide whether it works:

  • The prefix must be identical and at the start. Put static content first and per-request content last. A timestamp or user name at the top of the prompt makes every request different from byte one.
  • Anything that changes the KV values changes the cache key: another LoRA adapter. A different model version runs on its own engine, so its cache is separate. vLLM can also mix a cache salt into the first block’s hash, so only requests with the same salt share blocks, which is a way to keep tenants apart.
  • Requests have to reach the same engine. A cache on replica A does nothing for a request routed to replica B, so a load balancer that spreads related requests randomly wastes it. Lesson 6 returns to routing.

Prefix caching saves prefill work and memory, so it improves TTFT and capacity. It does not speed up decode. And it is not a response cache, which stores whole answers and returns them without running the model. Provider “prompt caching” discounts, covered in Cost and latency optimization, apply the same idea at the API.

Shrinking the cache by design

The cache per token is set when the model is designed. For a model you plan to self-host, read its KV bytes per token before you read its benchmark scores.

TechniqueIdeaEffectCost
Multi-query attention (MQA)all query heads share one KV headsmallest cachethe GQA paper notes it can degrade quality
Grouped-query attention (GQAGQAShort for grouped-query attention: query heads share key and value heads, which shrinks the KV cache.Open the glossary entry)groups of query heads share a KV headcache shrinks by the ratio of query heads to KV heads (4 times for 32 versus 8)built into the model; the paper shows multi-head checkpoints can be converted with about 5 percent of the original pre-training compute
Multi-head latent attention (MLA)cache a compressed latent vector and expand it when neededDeepSeek-V2 reports a 93.3 percent smaller KV cache than DeepSeek 67B (a model-to-model comparison that also changes other things)more complex attention kernels
KV-cache quantizationstore keys and values in 8 bits or fewercapacity roughly doubles at 8 bitsaccuracy risk that depends on the model and the context length, so test your own long inputs; vLLM’s documentation says dataset calibration of scales is recommended and gives no accuracy figures, so validate on your own evaluation set

Other families exist (sliding-window attention, state-space layers, evicting low-importance tokens). They trade away exact long-range recall, which is why they are model-design decisions rather than serving switches.

An interview line that holds up: choices made at pretraining time, such as GQA or MLA, matter more for serving cost than most runtime tricks.

When the pool is full

Eventually every sequence wants another block and none is free. An engine can do one of three things.

  1. Queue new requests until space frees up. TTFT rises.
  2. Preempt a running sequence. Its cache is either recomputed when it resumes (spends compute) or swapped to CPU memory (spends transfer time). The vLLM documentation says preempted requests are recomputed and that this can hurt end-to-end latency; in its current engine the default mode is recompute.
  3. Shed load: reject requests rather than serve everyone badly.
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...

KV pool is full: a sequence needs a block, none is free

1 Queue new requests: TTFT rises

2 Preempt a running sequence

Recompute its cache later (compute)

Or swap it to CPU memory (transfer)

3 Shed load: reject rather than serve everyone badly

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 shed load. Each option trades time for memory, and constant preemption is the failure to watch for.

A preemption storm is the failure to watch for. The engine keeps evicting and recomputing, GPU utilization looks high, and goodput collapses. vLLM exposes a preemption count in its metrics. Fixes, from its optimization guide: lower the number of concurrent sequences or batched tokens, raise memory utilization, or add tensor parallelism to free memory per GPU (at the price of synchronization). Adding replicas is the usual operational answer outside that guide. Quantizing the KV-cache and capping context length per customer tier also reduce pressure.

Real-World Application

Before you deploy, compute the KV bytes per token from the model’s configuration, subtract weights and overhead from usable memory, and write down how many sequences of your real context length fit. Compare that with the concurrency your traffic needs. Then decide the levers in order of cost: shorter contexts, prefix caching with static content first, FP8 cache validated on your evaluation set, a model with fewer KV heads, more GPUs. Alert on preemption count, not only on GPU utilization.

Interview Perspective

Expect: “How big is the KV-cache for this model?”, “How many concurrent users fit on this GPU?”, “What is PagedAttention?”, “Why is my TTFT high when long and short users mix?”. A strong answer uses the formula with KV heads, subtracts weights and overhead, states the assumptions, and names two or three levers with their costs.

Common mistakes: sizing with attention heads instead of KV heads; saying PagedAttention makes attention faster or the cache smaller; confusing the KV-cache with a response cache; forgetting activation and overhead memory; expecting prefix caching to work when the prompt starts with dynamic content.

Provenance: Common industry pattern and Generated practice. These are standard serving topics for ML-infrastructure and GenAI roles; none is verified for a named company.

Practice Questions

  • Basic: What is the KV-cache, and what makes it grow?
  • Intermediate: Compute KV bytes per token for 40 layers, 8 KV heads and head dimension 128 in FP8. How many 4,096-token sequences fit in 40 GB?
  • Advanced: p95 TTFT triples whenever long-document users and chat users share a server. Diagnose it (prefill blocking, cache pressure, preemption) and propose fixes with their costs.
  • Product-Company: Design caching for a support bot where every request starts with a 6,000-token policy prompt followed by the user’s history.

Activity

Choose an open-weight model and read its config.json for layers, attention heads, KV heads and hidden size. Compute KV bytes per token and per sequence at the context length you would serve. Then compute the concurrency on one GPU of your choice, stating the utilization fraction, the overhead you assume and the precision. If the config is not available, say so rather than guessing.

Homework

Write a one-page cache plan for a service with a 4,000-token static system prompt and 1,000-token conversations: bytes per token, concurrency before and after prefix caching, what you would alert on, and the two levers you would pull first when the pool fills, each with its cost.

Quick Revision

  • KV per token=2×layers×KV heads×head dim×bytes\text{KV 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 reduces waste and raises batch size; it does not shrink the bytes or speed up attention.
  • Prefix caching needs an identical prefix at the start, the same adapter and the same engine. It saves prefill and memory, not decode.
  • GQA, MLA and KV quantization shrink the cache; each has a quality or complexity cost to validate.
  • A full pool means queueing, preemption or shedding. Watch the preemption count.

Check yourself

  • Walk-through: A 70B model with 8 KV heads and 80 layers serves 8,192-token chats on four 80 GB GPUs. State the formula, the budget, the concurrency, and the three cheapest ways to raise it.
  • Variation: Repeat for a 14B model with full multi-head attention on a single 80 GB GPU. What changes first?
  • Common misconception: “PagedAttention shrinks the KV-cache.” It shrinks waste, not the bytes a real token needs.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

More for this module: Inference engineering resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Inference engineering.

Check yourself14 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 14 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveCompute KV-cache bytes per token and per request from layers, KV heads, head dimension and precision, using KV heads rather than query heads.

  1. Question 1 of 14A model has 48 layers, 48 query heads, 6 KV heads and a head dimension of 128, and the cache is stored in 16-bit values. How large is its KV-cache per token?

    Choose one answer.

ObjectiveTurn a GPU memory budget (usable memory minus weights and overhead) into a number of concurrent sequences, explain why a model that fits does not necessarily serve, and say how cache reads limit decode speed at large batch.

  1. Question 2 of 14A 13B model in BF16 (26 GB of weights) runs on one 80 GB GPU at 0.85 memory utilization, with 6 GB of assumed overhead. Its cache is 160 KiB per token and requests are 4,096 tokens long. About how many fit at once?

    Choose one answer.

  2. Question 3 of 14A 34B model needs 68 GB for BF16 weights. The team plans to run it on one 80 GB GPU at 0.9 utilization with about 6 GB of overhead. What follows?

    Choose one answer.

  3. Question 4 of 14A 13B model (26 GB of weights, 160 KiB of cache per token) decodes a batch of 16 sequences, each with 4,096 tokens of context. Which statement describes the bytes read per step?

    Choose one answer.

ObjectiveExplain how PagedAttention blocks and block tables remove waste, and say what it does not change.

  1. Question 5 of 14Which statements about PagedAttention are correct? Select all that apply.

    Choose all that apply.

  2. Question 6 of 14An engine reserves a contiguous 4,096-token slab per request. A paged engine uses 16-token blocks. For one request of 2,050 tokens, how do the wasted token slots compare?

    Choose one answer.

ObjectiveExplain how prefix caching reuses KV blocks, what makes a prefix reusable, and how it differs from a response cache.

  1. Question 7 of 14A service puts "Current time: <timestamp>" as the first line of every prompt, followed by 5,000 static tokens of instructions. Prefix cache hits are near zero. What is the most likely cause?

    Choose one answer.

  2. Question 8 of 14Which of these stop two requests from sharing cached prefix blocks, even when their prompt text is identical? Select all that apply.

    Choose all that apply.

  3. Question 9 of 14A team says, "We already cache answers keyed by the user's question, so prefix caching adds nothing." What is accurate?

    Choose one answer.

  4. Question 10 of 14Four replicas serve a product whose prompts share a long prefix. A load balancer sends requests to replicas at random and the hit rate is about a quarter of what one replica achieves alone. What is the fix?

    Choose one answer.

ObjectiveCompare grouped-query attention, latent attention and KV quantization by effect and cost, and describe what a server does when the cache pool is full.

  1. Question 11 of 14Two models of similar quality share layers and head size. One has 8 KV heads and the other has 64. The cache is the limit on concurrency and everything else is equal. How do their maximum concurrencies compare?

    Choose one answer.

  2. Question 12 of 14A team stores the KV-cache in 8 bits to double capacity. What should they do before shipping?

    Choose one answer.

  3. Question 13 of 14GPU utilization shows 95 percent, but goodput is falling and the engine's preemption counter keeps climbing. What is the likely situation and a first response?

    Choose one answer.

  4. Question 14 of 14What does multi-head latent attention do to cut the KV-cache?

    Choose one answer.