KV Cache Optimization: PagedAttention and FlashAttention

Autoregressive Large Language Models generate text one token at a time, recomputing self-attention across all preceding tokens at every decoding step. Without caching intermediate Key ($K$) and Value ($V$) projections, generation time scales quadratically ($\mathcal{O}(N^2)$) with sequence length.

While KV caching eliminates redundant computation, it shifts the bottleneck from compute to GPU High-Bandwidth Memory (HBM) capacity and memory bandwidth. Scaling modern LLMs to 128K+ context windows and high concurrent batch sizes requires two foundational systems breakthroughs: FlashAttention (eliminating intermediate attention matrix reads/writes) and PagedAttention (eliminating KV cache memory fragmentation).

Calculating KV Cache Memory Footprint

For a Transformer model with $L$ layers, $H_{kv}$ key-value attention heads (using Grouped-Query Attention, GQA), head dimension $d_h$, precision bytes $B$ (e.g., 2 bytes for FP16/BF16, 1 byte for FP8), batch size $B_{\text{batch}}$, and sequence length $S$, the exact KV cache size is:

$$\text{KV Cache Bytes} = 2 \times L \times H_{kv} \times d_h \times S \times B_{\text{batch}} \times B$$

Even with GQA, long contexts and concurrent requests consume tens of gigabytes of VRAM:

Model ArchitectureKV Heads ($H_{kv}$)Layers ($L$)PrecisionKV Size per 32K ContextMax Concurrent 32K Requests on 80GB A100
Llama-3 8B (GQA-8)832BF16 (2B)4.0 GB~14 requests
Llama-3 70B (GQA-8)880BF16 (2B)10.0 GB~2 requests (across 2x A100)
Llama-3 70B (GQA-8)880FP8 (1B)5.0 GB~5 requests (2x throughput)
Standard MHA 70B (No GQA)6480BF16 (2B)80.0 GB0 requests (OOM)

FlashAttention: IO-Aware Tiled Self-Attention

Standard self-attention computes $S = QK^T \in \mathbb{R}^{N \times N}$, writes $S$ to slow GPU HBM, reads $S$ back to compute $P = \text{Softmax}(S)$, writes $P$ to HBM, and finally multiplies $PV$. For a 32K sequence, materializing the $32768 \times 32768$ attention matrix consumes 2 GB per head and stalls Tensor Cores on HBM memory transfers.

FlashAttention (and FlashAttention-2 / FlashAttention-3) fuses the entire attention operation into a single CUDA kernel using two core techniques:

  1. SRAM Tiling: Blocks of $Q$, $K$, and $V$ are loaded from slow HBM into ultra-fast on-chip SRAM (~20 MB per GPU). Attention scores are computed, softmaxed, and multiplied by $V$ entirely inside SRAM without ever materializing the $N \times N$ matrix in HBM.
  2. Online Softmax Rescaling: Because softmax requires a global row sum $\sum_j e^{x_j}$, FlashAttention tracks running row-wise maximums $m^{(i)}$ and normalization denominators $\ell^{(i)}$ across tiles, rescaling partial outputs on the fly so the fused result is mathematically identical to standard attention.

PagedAttention: Eliminating KV Cache Fragmentation

Traditional inference engines pre-allocate a single contiguous tensor of size max_seq_len for each incoming request's KV cache. Because actual output lengths are unknown ahead of time, this causes 60% to 80% memory waste from:

  • Internal Fragmentation: Reserved slots for max_seq_len=32768 when a request finishes after 400 tokens.
  • External Fragmentation: Free memory scattered in non-contiguous chunks that cannot fit a new contiguous sequence allocation.

PagedAttention (introduced in vLLM) applies operating-system virtual memory paging to KV caches:

  • Fixed-Size KV Blocks: The KV cache is partitioned into small, non-contiguous physical blocks (typically block_size = 16 or 32 tokens).
  • Block Table Mapping: Each sequence maintains a lightweight logical-to-physical Block Table mapping logical token positions to physical GPU memory blocks, allocating new blocks dynamically only as tokens are generated.
  • Copy-on-Write Prefix Sharing: System prompts, few-shot examples, and shared RAG documents map multiple requests to the exact same physical KV blocks with reference counting (ref_count > 1), cutting prefill compute and VRAM usage dramatically.

Simulating a Block-Table KV Cache Allocator (paged_kv_cache.py)

The Python implementation below demonstrates how a PagedAttention block manager allocates physical KV pages on demand and shares prefix blocks via Copy-on-Write:

Python
from dataclasses import dataclass, field
import torch


@dataclass
class PhysicalKVBlock:
    block_id: int
    ref_count: int = 0
    token_ids: list[int] = field(default_factory=list)


class PagedKVCacheManager:
    """Manages non-contiguous physical KV blocks and per-sequence block tables."""

    def __init__(
        self,
        num_blocks: int,
        block_size: int,
        num_layers: int,
        num_kv_heads: int,
        head_dim: int,
        dtype: torch.dtype = torch.bfloat16,
        device: str = "cpu",
    ) -> None:
        self.num_blocks = num_blocks
        self.block_size = block_size
        self.free_blocks: list[int] = list(range(num_blocks - 1, -1, -1))
        self.blocks: dict[int, PhysicalKVBlock] = {
            i: PhysicalKVBlock(block_id=i) for i in range(num_blocks)
        }
        # Physical KV pool: [num_layers, 2 (K/V), num_blocks, block_size, num_kv_heads, head_dim]
        self.kv_pool = torch.zeros(
            (num_layers, 2, num_blocks, block_size, num_kv_heads, head_dim),
            dtype=dtype,
            device=device,
        )
        self.block_tables: dict[str, list[int]] = {}
        self.prefix_cache: dict[tuple[int, ...], int] = {}

    def _allocate_block(self) -> int:
        if not self.free_blocks:
            raise RuntimeError("Out of KV cache blocks: trigger preemption or eviction.")
        block_id = self.free_blocks.pop()
        self.blocks[block_id].ref_count = 1
        self.blocks[block_id].token_ids.clear()
        return block_id

    def allocate_sequence(self, seq_id: str, prompt_tokens: list[int]) -> list[int]:
        """Allocate physical blocks for a prompt, reusing cached prefix blocks."""
        table: list[int] = []
        for start in range(0, len(prompt_tokens), self.block_size):
            chunk = tuple(prompt_tokens[start : start + self.block_size])
            if len(chunk) == self.block_size and chunk in self.prefix_cache:
                shared_id = self.prefix_cache[chunk]
                self.blocks[shared_id].ref_count += 1
                table.append(shared_id)
            else:
                new_id = self._allocate_block()
                self.blocks[new_id].token_ids = list(chunk)
                if len(chunk) == self.block_size:
                    self.prefix_cache[chunk] = new_id
                table.append(new_id)

        self.block_tables[seq_id] = table
        return table

    def append_token(self, seq_id: str, token_id: int) -> int:
        """Append a newly generated token, allocating a new block only when full."""
        table = self.block_tables[seq_id]
        last_block = self.blocks[table[-1]]

        if len(last_block.token_ids) < self.block_size:
            # Copy-on-Write if block is shared across multiple sequences
            if last_block.ref_count > 1:
                last_block.ref_count -= 1
                cloned_id = self._allocate_block()
                self.blocks[cloned_id].token_ids = list(last_block.token_ids)
                self.kv_pool[:, :, cloned_id] = self.kv_pool[:, :, last_block.block_id]
                table[-1] = cloned_id
                last_block = self.blocks[cloned_id]

            last_block.token_ids.append(token_id)
            return last_block.block_id

        new_block_id = self._allocate_block()
        self.blocks[new_block_id].token_ids.append(token_id)
        table.append(new_block_id)
        return new_block_id

    def free_sequence(self, seq_id: str) -> None:
        """Release block references when a request finishes."""
        for block_id in self.block_tables.pop(seq_id, []):
            block = self.blocks[block_id]
            block.ref_count -= 1
            if block.ref_count == 0:
                self.free_blocks.append(block_id)


if __name__ == "__main__":
    manager = PagedKVCacheManager(
        num_blocks=64, block_size=4, num_layers=2, num_kv_heads=4, head_dim=64
    )
    shared_system_prompt = [101, 204, 309, 412, 518, 620]

    t1 = manager.allocate_sequence("req_1", shared_system_prompt)
    t2 = manager.allocate_sequence("req_2", shared_system_prompt)
    print(f"req_1 block table: {t1}")
    print(f"req_2 block table (reuses full prefix block 0): {t2}")

    manager.append_token("req_1", 999)
    print(f"req_1 after Copy-on-Write append: {manager.block_tables['req_1']}")
    print(f"req_2 remains isolated: {manager.block_tables['req_2']}")

Configuring FlashAttention & Paged KV Cache in Production (serve_vllm.py)

Modern serving engines combine FlashAttention kernels for fast prefill with PagedAttention and FP8 KV cache quantization for high-concurrency decoding:

Python
from vllm import LLM, SamplingParams


def create_optimized_engine(model_id: str) -> LLM:
    """Initialize vLLM with PagedAttention, prefix caching, and FP8 KV cache."""
    return LLM(
        model=model_id,
        dtype="bfloat16",
        kv_cache_dtype="fp8",          # Halves KV cache HBM usage vs BF16
        block_size=16,                 # 16 tokens per physical PagedAttention block
        gpu_memory_utilization=0.90,   # Reserves 90% VRAM for weights + KV block pool
        enable_prefix_caching=True,    # Automatic Copy-on-Write prefix sharing
        enable_chunked_prefill=True,   # Interleaves long prefills with decode batches
        max_model_len=32768,
    )


if __name__ == "__main__":
    llm = create_optimized_engine("Qwen/Qwen2.5-7B-Instruct")
    params = SamplingParams(temperature=0.0, max_tokens=256)
    outputs = llm.generate(
        ["Explain how online softmax enables SRAM tiling in FlashAttention."],
        params,
    )
    print(outputs[0].outputs[0].text)

Advanced KV Cache Compression Techniques

When even PagedAttention and GQA hit VRAM limits at 128K–1M tokens, combine these complementary optimizations:

  • FP8 (E4M3) KV Quantization: Compresses cached Key and Value tensors from 16-bit to 8-bit with per-tensor or per-channel scaling factors, doubling maximum batch concurrency with $< 0.1\%$ accuracy impact on Hopper/Ada GPUs.
  • Chunked Prefill: Splits a 64K prompt into 2,048-token chunks scheduled alongside active decode steps, preventing long prompt prefills from spiking tail Time-Between-Tokens (TBT) latency.
  • Multi-Head Latent Attention (MLA): Used in DeepSeek-V2/V3, MLA projects $K$ and $V$ into a low-rank compressed latent vector $c_t^{KV}$ before caching, reducing KV cache size by up to 93% compared to standard Multi-Head Attention.

Best Practices for High-Throughput LLM Serving

  • Enable Automatic Prefix Caching (APC) for agentic and RAG workloads: Multi-turn chat histories, system instructions, and tool schemas share identical token prefixes across turns; APC eliminates redundant prefill FLOPs and duplicate KV blocks.
  • Tune block_size to 16 or 32: Smaller blocks (16) minimize internal tail fragmentation and maximize prefix-cache hit granularity without inflating block-table lookup overhead.
  • Pair FlashAttention-2/3 with bfloat16 or fp8: Always verify at startup that your serving engine selects the FlashAttention backend rather than falling back to PyTorch's unfused math attention kernel.
  • Monitor KV cache utilization metrics: Track gpu_cache_usage_perc and preemption counts in Prometheus; sustained cache usage above 95% signals that incoming requests are being swapped or recomputed.

Common Mistakes

  • Setting max_model_len unnecessarily high without PagedAttention: Pre-allocating static buffers for 131072 tokens when average requests are 2048 tokens caps concurrency to a handful of users.
  • Leaving enable_prefix_caching=False in multi-turn chatbots: Recomputing KV states for a 10,000-token conversation history on every user message wastes both compute and HBM bandwidth.
  • Using INT4 KV quantization without calibration on needle-in-a-haystack benchmarks: Aggressive 4-bit quantization of Key vectors can degrade long-context retrieval accuracy; prefer FP8 (E4M3) unless memory is strictly constrained.

Summary

KV cache optimization sits at the heart of production LLM inference performance. By combining FlashAttention to keep quadratic attention intermediate states inside fast on-chip SRAM with PagedAttention to manage KV memory in non-contiguous, shareable virtual blocks, inference engines eliminate memory fragmentation and unlock massive concurrent throughput across long-context workloads.