Skip to content
E
Educatum

How does PagedAttention resolve KV Cache memory fragmentation, and what are its serving trade-offs?

Curated by Educatum AI teamLast updated:
HardwareInference
Direct Answer

PagedAttention resolves KV cache fragmentation in autoregressive LLM serving by partitioning each sequence's keys and values into fixed-size physical memory blocks (e.g., 16 tokens) managed via a logical-to-physical Block Table, analogous to OS virtual memory paging. Because blocks are allocated on demand rather than contiguously for the maximum sequence length, external fragmentation is eliminated and internal fragmentation is bounded to less than one block per sequence, while identical prompt prefixes can be shared via copy-on-write. This reclaimed VRAM unlocks much higher serving concurrency and throughput, at the cost of custom block-indexed attention kernels and slight non-contiguous memory access overhead.

PagedAttention addresses a critical inefficiency in auto-regressive LLM serving: the dynamic and unpredictable memory footprint of the Key-Value (KV) cache. In many naive inference systems, memory for the KV cache is either pre-allocated contiguously based on the maximum possible sequence length or managed via inefficient dynamic allocation. Because most requests finish generating long before reaching this maximum, a significant portion of VRAM can be wasted due to internal fragmentation (reserved but unused memory) and external fragmentation (small, unusable gaps between allocations).

Drawing inspiration from operating system virtual memory, PagedAttention (Kwon et al., 2023, arXiv:2309.06180) divides the KV cache into fixed-size physical blocks (e.g., chunks of 16 or 32 tokens). It uses a Block Table to map the continuous logical sequence of tokens to these non-contiguous physical blocks in GPU memory. Conceptually, this virtualizes KV cache memory, decoupling logical sequence layout from physical memory allocation.

  • On-Demand Allocation: Memory is allocated dynamically block-by-block as the generated sequence grows, limiting maximum memory waste to at most a fraction of a single block per sequence.
  • Memory Sharing: PagedAttention enables prompt sharing and beam search optimization. Multiple sequences with identical prefixes (e.g., shared system prompts) can reference the same physical blocks, using copy-on-write–like semantics when sequences diverge.
  • High Concurrency: By reclaiming fragmented VRAM, systems like vLLM can significantly increase effective batch size and throughput, often achieving multiple-fold improvements under high-concurrency workloads.

⚠️ Limitations & Caveats

  • PagedAttention requires specialized CUDA kernels, as standard optimized attention implementations typically assume contiguous memory layouts.
  • Fetching data from non-contiguous memory blocks reduces cache locality and can introduce slight per-token latency overhead, which is more noticeable at small batch sizes. In practice, PagedAttention primarily improves throughput under high concurrency, with minor latency trade-offs for individual requests.

🧪 Core Insights & Mathematical Foundations

[KV Block Footprint (per layer)]: Stoken=2×nkv_heads×dhead×p,Sblock=B×Stoken(p=bytes per element)[Logical to Physical Slot]: PhysSlot(i)=BT ⁣[⌊i/B⌋]⋅B+(i mod B)[Memory Waste Naive]: Wnaive=∑j=1N(MaxLen−Lj)×Stoken[Memory Waste Paged]: Wpaged=∑j=1N(⌈Lj/B⌉⋅B−Lj)×Stoken<N×Sblock[Paged Attention]: PagedAttn(qt,K,V)=softmax⁡ ⁣(qtKTdhead)V=∑b=0⌊t/B⌋exp⁡(sb−mglobal)lglobalVBT[b],sb=qtKBT[b]Tdhead[Online Softmax Rescaling]: mnew=max⁡(mold,max⁡(sb)),lnew=emold−mnewlold+∑exp⁡(sb−mnew),Onew=emold−mnewloldOold+exp⁡(sb−mnew)VBT[b]lnew\begin{aligned} & \text{[KV Block Footprint (per layer)]: } S_{\text{token}} = 2 \times n_{\text{kv\_heads}} \times d_{\text{head}} \times p, \quad S_{\text{block}} = B \times S_{\text{token}} \quad (p = \text{bytes per element}) \\ & \text{[Logical to Physical Slot]: } \text{PhysSlot}(i) = \text{BT}\!\left[\lfloor i / B \rfloor\right] \cdot B + (i \bmod B) \\ & \text{[Memory Waste Naive]: } \mathcal{W}_{\text{naive}} = \sum_{j=1}^{N} (\text{MaxLen} - L_j) \times S_{\text{token}} \\ & \text{[Memory Waste Paged]: } \mathcal{W}_{\text{paged}} = \sum_{j=1}^{N} \left(\lceil L_j / B \rceil \cdot B - L_j\right) \times S_{\text{token}} < N \times S_{\text{block}} \\ & \text{[Paged Attention]: } \text{PagedAttn}(q_t, K, V) = \operatorname{softmax}\!\left(\frac{q_t K^T}{\sqrt{d_{\text{head}}}}\right) V = \sum_{b=0}^{\lfloor t/B \rfloor} \frac{\exp(s_b - m_{\text{global}})}{l_{\text{global}}} V_{\text{BT}[b]}, \quad s_b = \frac{q_t K_{\text{BT}[b]}^T}{\sqrt{d_{\text{head}}}} \\ & \text{[Online Softmax Rescaling]: } m_{\text{new}} = \max(m_{\text{old}}, \max(s_b)), \quad l_{\text{new}} = e^{m_{\text{old}} - m_{\text{new}}} l_{\text{old}} + \sum \exp(s_b - m_{\text{new}}), \quad O_{\text{new}} = \frac{e^{m_{\text{old}} - m_{\text{new}}} l_{\text{old}} O_{\text{old}} + \exp(s_b - m_{\text{new}}) V_{\text{BT}[b]}}{l_{\text{new}}} \end{aligned}

Follow-up 1: Explain the implementation mechanics of the Block Table during the attention computation.

During decoding, the model generates a new Query vector for the current token and must compute attention scores against all historical Keys. In PagedAttention, the CUDA kernel does not iterate over a single contiguous memory region. Instead, it consults the Block Table to determine the physical locations of the blocks corresponding to the sequence.

The kernel then iterates over these blocks, loading Key and Value chunks into on-chip SRAM. It computes partial attention contributions for each block and aggregates them using numerically stable softmax accumulation. This ensures that the final attention output is mathematically identical to standard attention, while the underlying memory layout remains non-contiguous.

⚠️ Limitations & Caveats

  • The block size (e.g., 16 vs. 64 tokens) is a critical hyperparameter. Larger blocks increase internal fragmentation, while smaller blocks increase lookup overhead and reduce memory efficiency.
  • The Block Table is maintained by the runtime and accessed efficiently within GPU kernels, requiring careful coordination between host-side scheduling and device execution to avoid overhead.

Follow-up 2: How do prefix-aware architectures like RadixAttention (SGLang) advance beyond standard PagedAttention?

While PagedAttention enables memory sharing for sequences generated simultaneously (e.g., Beam Search), it does not natively reuse KV cache across independent requests. RadixAttention, introduced in SGLang (Zheng et al., 2023, arXiv:2312.07104), extends this idea by organizing KV cache blocks into a global Radix Tree.

Completed requests are not immediately evicted. Instead, their KV cache blocks are retained in GPU memory and indexed by their token prefixes. When a new request arrives, the system traverses the Radix Tree to identify shared prefixes and reuses existing KV cache blocks, computing only the new suffix tokens. An eviction policy (e.g., Least Recently Used) is applied when memory pressure increases.

Dimension vLLM (Standard PagedAttention) SGLang (RadixAttention)
Computational Cost Moderate (Block table lookups) Higher (Radix tree traversal & maintenance)
Data Requirements Agnostic (Processes sequences independently) Thrives on high-overlap prompt distributions
KV Cache Sharing Intra-request (e.g., Beam Search) Inter-request (Global prefix reuse)
Known Failure Modes Redundant computation on repeated prompts Tree maintenance overhead under low reuse

⚠️ Limitations & Caveats

  • RadixAttention relies on workload characteristics. In highly diverse workloads with minimal prefix overlap, the overhead of maintaining the Radix Tree may outweigh its benefits.
  • In multi-tenant environments, sharing cached KV blocks introduces isolation challenges, requiring careful system design to ensure prompt-level separation.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.