LLM Inference Memory and Phase Splitting: KV Cache and PD Disaggregation
Machine LearningModel answerLast updated
Explain why transformer decoders cache keys and values, size that cache for a given model, and reason about running prefill and decode on separate GPU pools.
You are discussing how to serve a large decoder-only language model efficiently. Answer the two parts below the way you would in a technical conversation: explain the mechanism, put numbers on it, and discuss trade-offs. State your assumptions first, since the answers depend on them.
Assumptions to settle up front
- Model shape: number of layers, query heads versus key/value heads (full multi-head attention or grouped-query attention), head dimension, numeric precision.
- Workload: typical prompt length, output length, and number of concurrent requests.
- Latency goals: time to first token, time per output token, or total throughput.
- Hardware: GPU type and the interconnect between GPUs that would serve each phase.
Part 1: The KV cache
Describe what is stored during autoregressive generation, why this speeds up decoding, and how much memory it uses. Derive the cache size per token and per request for a model you specify. Explain what that size implies for batch size, maximum context length and GPU memory management as requests grow.
Cover:
- What is cached per layer and per head, and what is not cached
- The compute saved per step versus the memory spent
- A per-token formula with a worked example
- Consequences for batching and memory management
Part 2: Prefill-decode disaggregation
Describe the two phases of inference and how their resource profiles differ. Then explain disaggregation, where prefill and decode run on separate groups of GPUs: why do it, what does it cost, and when is it not worth it?
Cover:
- Compute-bound prefill versus bandwidth-bound decode, and which latency metric each drives
- Interference when both phases share GPUs
- The cost of moving state between pools and how to reduce or hide it
- When colocating both phases is the better choice
Hints
Hint 1
Think about which tensors in attention depend only on earlier tokens and therefore never change once computed. Queries are only needed for the current token.
Hint 2
For the size formula, count two tensors (K and V) per layer, each with (number of KV heads x head dimension) values per token, multiplied by bytes per value. Then check how grouped-query attention changes the KV head count.
Hint 3
For disaggregation, compare arithmetic intensity: prefill processes many tokens per weight read, decode processes one token per sequence per weight read. Then ask what has to travel from the prefill pool to the decode pool, and how large it is relative to the network bandwidth.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I will use a Llama-2-70B-like shape: 80 layers, 64 query heads, 8 KV heads (grouped-query attention), head dimension 128, FP16 (2 bytes). Typical workload: 2,000-token prompts, a few hundred output tokens, tens to hundreds of concurrent requests. Two latency metrics matter: time to first token (TTFT) and time per output token (TPOT).
Part 1: The KV cache
What is cached. In each attention layer, every token produces a query, a key and a value vector. The output for the newest token needs its own query, plus the keys and values of all earlier tokens. Earlier keys and values never change (causal masking, fixed weights), so we store them. Queries are used once and are not cached. Activations from other layers are not needed either, since each layer keeps its own K and V.
Why it speeds up decoding. Without a cache, generating token t means recomputing K and V projections for all t previous tokens in every layer, so total work to generate n tokens grows roughly as O(n²) in projection cost. With the cache, each step computes projections for one new token and appends to the cache. Per-step projection and MLP cost becomes constant in sequence length. Attention itself still reads the whole cache, so that part stays O(t) per step, but the expensive matmuls are no longer repeated.
Size per token.
bytes/token = 2 (K and V) x layers x kv_heads x head_dim x bytes_per_value
For the model above: 2 x 80 x 8 x 128 x 2 = 327,680 bytes, about 320 KB per token. A 4,096-token request needs about 1.3 GB. With full multi-head attention (64 KV heads) it would be 8x larger, about 2.6 MB per token, which is why GQA matters for serving.
Consequences.
- Weights for this model take about 140 GB in FP16, so on 2 x 80 GB GPUs only about 20 GB or less remains for cache. That fits only around 15 requests at 4k tokens. The cache, not compute, often caps batch size.
- Memory grows with every generated token, and output length is unknown in advance. Preallocating the maximum length per request wastes memory through fragmentation. Paged allocation (as in vLLM's PagedAttention) splits the cache into fixed-size blocks allocated on demand, which reduces waste to under a block per request and enables prefix sharing between requests with a common prompt.
- Other levers: quantize the cache to FP8 or INT8 (2x smaller), use GQA/MQA models, sliding-window attention, evicting or offloading cold cache to CPU, and preemption or recomputation under memory pressure.
Part 2: Prefill-decode disaggregation
Two phases.
- Prefill processes the whole prompt in parallel and builds the cache. Thousands of tokens share each weight read, so arithmetic intensity is high and the phase is compute-bound. It determines TTFT.
- Decode generates one token per sequence per step. Every step must read all weights plus the sequence's cache, doing little math per byte, so it is memory-bandwidth-bound. It determines TPOT and benefits from large batches to amortize weight reads.
The interference problem. On shared GPUs, a long prefill occupies the device for hundreds of milliseconds, stalling decode steps for other users and producing latency spikes in TPOT. Conversely, queuing prefill behind decode batches inflates TTFT. Tuning one metric hurts the other. Chunked prefill (splitting prompts into pieces mixed into decode batches) softens this but does not remove it.
Disaggregation. Dedicate one pool to prefill and another to decode. A request is prefilled, its KV cache is sent to a decode GPU, and decoding continues there.
Benefits:
- No interference, so TTFT and TPOT SLOs can be met independently.
- Each pool can use its own parallelism and batch policy: smaller batches and tensor parallelism for low-latency prefill, large batches for decode throughput.
- Pools scale independently, and can even use different hardware.
Costs.
- KV transfer. In our example a 2,000-token prompt produces about 650 MB of cache. Over 400 Gb/s (50 GB/s) networking that is about 13 ms, tolerable. Over 100 Gb/s it is about 52 ms, a visible hit on TTFT. Mitigations: NVLink or RDMA, layer-by-layer streaming so transfer overlaps with prefill computation, GQA and cache quantization to shrink the payload.
- Capacity planning. The prefill-to-decode ratio must match the workload mix (prompt versus output lengths). A mismatch leaves one pool idle while the other queues. Mix shifts need dynamic rebalancing.
- Complexity. A cache-aware router, failure handling for in-flight transfers, and two deployments to operate. Prefix caching becomes harder because cache lives in two places.
- Weights are duplicated across both pools, which costs memory.
When not to disaggregate.
- Small models or short prompts, where prefill is brief and interference is minor.
- Low traffic, where separate pools would sit underutilized.
- Slow interconnect, so transfer time wipes out the gain.
- Loose latency SLOs, where chunked prefill on colocated GPUs is good enough.
- Workloads with heavy prefix reuse, where most prefill is skipped anyway.
Common mistakes
- Saying the cache stores queries or activations.
- Forgetting the factor of 2 for K and V, or using query heads instead of KV heads.
- Claiming decode is compute-bound, or ignoring that attention still scans the full cache each step.
- Presenting disaggregation as free: ignoring transfer cost and pool-ratio tuning.
- Quoting numbers without stating the model shape and precision.
Summary
The KV cache trades memory for compute and makes decode cheap per step, but its size (about 320 KB per token here) governs batch size and drives paged memory management. Prefill is compute-heavy and sets TTFT, decode is bandwidth-heavy and sets TPOT. Disaggregation removes their interference at the price of KV transfer and operational complexity, and it pays off mainly at scale with strict latency SLOs and fast interconnects.