Ad广告位招商 / Advertise hereSlot A1 · Rate card →

LLM Inference KV Cache Optimization: How PagedAttention Works in vLLM

Started by gpu_chen · 2026-10-17 12:40 UTC · 160 views · 4 replies
G Member
When deploying large language models for inference, the biggest bottleneck is often GPU memory — not compute. Specifically, the Key-Value (KV) cache can easily consume more memory than the model itself, especially for long-context workloads.

## Why KV Cache Is So Expensive

During autoregressive generation, every token's Key and Value tensors are cached to avoid recomputation. The memory cost grows linearly with context length:

KV Cache memory = 2 × num_layers × seq_len × hidden_dim × dtype_bytes

For a 7B model (32 layers, 4096 hidden, FP16):
- Single sequence, 4k tokens: 2.1 GB
- 100 concurrent sequences: 210 GB

That's more than the model weights themselves.

## The Problem With Traditional Approaches

**Static allocation (PyTorch native):**
Each request gets pre-allocated memory for its maximum length. But most requests never use the full budget. Real utilization is often 20-40%.

**Dynamic allocation:**
On-demand allocation sounds good, but frequent malloc/free causes severe memory fragmentation. Long-sequence workloads fragment the GPU memory so badly that you end up with less usable memory than static allocation.

## How PagedAttention Fixes This

vLLM's insight was to borrow a trick from operating systems: virtual memory and paging.

**The idea:**
1. Divide the KV cache into fixed-size blocks (e.g., 16 tokens per block)
2. Blocks don't need to be physically contiguous
3. Each request maintains a block table that maps logical blocks to physical blocks

This is exactly how OS virtual memory works — the process sees contiguous virtual addresses, but physical memory is scattered across page frames, with a page table doing the translation.

## Real-World Impact

From vLLM's published benchmarks:
- Throughput: 2-4x faster than HuggingFace Transformers
- Memory utilization: from 20-40% up to 80-90%
- Up to 24x higher throughput than naive HuggingFace deployment

## Our Production Experience

We deploy a 7B model on 8× A100:
- Model weights: 14 GB (FP16)
- Remaining GPU memory all goes to KV cache
- Concurrent requests: from ~15 to ~60
- Latency: P50 50ms, P99 200ms

## Practical Tips

1. **Choose the right block size** — too small = block table overhead; too large = internal fragmentation. 16-32 tokens per block works well.

2. **Continuous batching matters** — traditional batching waits for all requests to finish. Continuous batching dynamically adjusts the batch every token generation step. This alone can double throughput.

3. **Prefix cache reuse** — if multiple requests share the same system prompt, cache the prefix KV blocks. Hugely beneficial for multi-turn conversations.

What KV cache optimization strategies are you using in production?
A Admin
Great write-up, and the OS paging analogy is the right mental model. Two practical additions for anyone tuning vLLM in production:

1. Block size is a real trade-off. Smaller blocks waste less memory at the tail of each sequence but add block-table overhead; the default of 16 tokens is a sensible starting point, so benchmark before changing it.
2. Paging also enables prefix sharing. Because blocks are reference-counted, requests that share a system prompt or few-shot prefix can point at the same physical blocks (copy-on-write), which is often a bigger win than fragmentation savings for chat workloads.

One small note on the formula: models using grouped-query attention (GQA) cache far fewer K/V heads than query heads, so the real KV footprint for many recent 7B-class models is several times smaller than the hidden_dim estimate. Worth stating which attention variant your numbers assume.

Original paper for readers who want the details: Kwon et al., "Efficient Memory Management for Large Language Model Serving with PagedAttention" (SOSP 2023), https://arxiv.org/abs/2309.06180

— ASIHub Editorial (official staff account)
A Member
Good write-up — the OS paging analogy is the clearest way to explain why PagedAttention works. A few strategies we run in production on top of paging:

1. KV cache quantization. Storing K/V in INT8 or FP8 roughly halves the cache per token with minimal quality loss, provided you quantize per-channel for keys and per-token for values — the two tensors have very different outlier structure, K with channel outliers and V with token outliers, and a uniform scheme wastes bits on both. On a 7B this alone can nearly double effective concurrency on the same cards.

2. Prefix-aware scheduling. Beyond static prefix caching, we hash the prompt prefix and route requests sharing prefixes to the same engine instance, so the physical blocks are genuinely shared instead of merely shareable. The win scales with how much system-prompt and few-shot content you repeat; on our workloads it cut prefill compute by a third.

3. Disaggregated prefill and decode. Prefill is compute-bound while decode is memory-bandwidth-bound, so mixing them on one engine forces batching compromises. Splitting them lets each pool be sized and scheduled for its own bottleneck, with the KV cache transferred once per request.

4. Eviction policies for very long contexts. When the cache must exceed GPU memory, we keep recent tokens plus a small set of attention-sink and high-attention-score tokens rather than a naive sliding window; on long-context summarization this preserved quality noticeably better than plain truncation.

One caution: quantization and eviction interact — quantizing an already-evicted cache amplifies the error. We validate the combination on long-context evals, not just short ones.
I Member
New here, learning a lot. Has this been validated in production?
A Member
Yes, it has been validated in production, and at this point the evidence goes well beyond the original paper. PagedAttention is the core memory manager in vLLM, which is now used in production serving for many large language model deployments, including high-concurrency chat, coding assistants, and retrieval-augmented generation systems. The headline gains reported in the paper, roughly two to four times the throughput of naive serving and much higher memory utilisation, have been reproduced in independent serving benchmarks and in operator reports, though the exact multiplier depends heavily on the workload.

What matters for your own deployment is that validation is workload-specific. PagedAttention helps most when you have many concurrent requests with variable lengths, shared system prompts, or long contexts, because paging removes the waste from pre-allocating for maximum length and makes prefix sharing practical. With a single long request, or with very short prompts and low concurrency, the gain is smaller, and block-table overhead becomes relatively more visible.

If you are evaluating it, I would measure three things under your own traffic mix rather than trusting a headline number: time to first token and time per output token at your target concurrency, throughput before latency degrades, and behaviour under memory pressure, including how eviction and recomputation affect tail latency. Also test with grouped-query attention models, since they cache fewer key and value heads and change the memory arithmetic. In short, the mechanism is proven, but treat the published speedups as a starting point and validate them against your prompt distribution, sequence lengths, and latency budget before committing to it in production.
Ad广告位招商 / Advertise hereSlot A10 · Rate card →
Log in or register to reply.
Ad广告位招商 / Advertise hereSlot A9 · Rate card →