1. The Two Phases of LLM Generation
When an autoregressive Large Language Model (such as LLaMA-3, DeepSeek, or GPT-4) serves a request, inference proceeds in two fundamentally distinct operational regimes:
- The Prefill Phase (Prompt Processing):
- All input prompt tokens are ingested simultaneously.
- Matrix multiplications are large and highly parallel: operations.
- Compute-bound: Utilizes high Tensor Core compute throughput (TFLOPs).
- The Decode Phase (Token Generation):
- Generates tokens sequentially, one token at a time: .
- Matrix-vector products: batch size is small, arithmetic intensity is near zero.
- Memory-bandwidth bound: The GPU spends of its time waiting for weights and previous keys/values to stream across the HBM memory bus.
To avoid recomputing keys and values for all past tokens at every step, we store them in GPU VRAM as the Key-Value (KV) Cache.
2. Deriving the Exact KV-Cache Memory Equation
Let us calculate the exact number of bytes required to cache a single token across an entire Transformer stack.
For each Transformer layer :
- Key vector dimension:
- Value vector dimension:
- Precision byte size: bytes per parameter ( for FP16/BF16, for FP8, for INT4).
The total memory required per token across both Keys and Values is:
To find total KV-cache size for a batch of concurrent sequences of sequence length :
3. Real-World Case Study: LLaMA-3 70B
Let us evaluate the architectural parameters of LLaMA-3 70B:
- Layers ():
- Query Heads ():
- KV Heads (): (Grouped-Query Attention)
- Head Dimension ():
- Precision (): bytes (FP16)
Plugging these numbers into our first-principles equation:
Now compute the KV-cache requirement for a standard serving setup:
- Batch Size concurrent users.
- Context Length tokens.
[!WARNING] The weights of LLaMA-3 70B quantized to 4-bit take . The KV-cache for just 16 concurrent users at 8k context () exceeds the weight size of the model itself!
4. Architectural Solutions: MHA vs. MQA vs. GQA
How have AI architects solved this exponential memory bottleneck?
- Multi-Head Attention (MHA) ():
- Cache size is huge: .
- Multi-Query Attention (MQA) ():
- Compresses cache by , but loses representation quality and expressive nuance.
- Grouped-Query Attention (GQA) ():
- The golden mean adopted by modern foundation models. Yields an cache compression with negligible degradation in benchmark scores.
5. PagedAttention & Eliminating Virtual Fragmentation
In early serving frameworks (TensorRT-LLM v1, HuggingFace), memory was pre-allocated contiguously for the maximum sequence length (e.g. 8k).
Because actual response lengths vary widely, of GPU VRAM was completely wasted due to internal and external fragmentation!
In 2023, Kwon et al. introduced PagedAttention (the core algorithm behind vLLM):
- Inspired by virtual memory paging in operating systems (OS).
- Divides the KV-cache of each request into fixed-size physical memory blocks (typically 16 or 32 tokens).
- Dynamic logical-to-physical block mapping tables allow non-contiguous physical storage.
This single algorithmic breakthrough nearly tripled serving throughput without altering a single weight of the model.