If latency budgets leave no room for synchronous retries, partition KV caches into fixed-size 16-token physical blocks mapped via a block table, and handle memory pressure with prefix-aware LRU eviction, swap-to-CPU, or recomputation.
TL;DR30-second simplified summary▾
Core Mechanics: Serving Llama-3-70B (GQA, 80 layers, 8 KV heads, head_dim=128, FP16) on 8× H100-80GB (TP=8) leaves 57.5 GB/GPU (460 GB total) for KV cache after weights (17.5 GB/GPU) and activations (5 GB/GPU).
Visual & Structural Flow: Depicts Logical Token Blocks Mapped to Non-Contiguous 16-Token Physical KV Pages (Logical Seq (CoW) -> Block Table -> Physical KV Pool -> CPU Swap / Evict); GPU HBM Blocks, Prefix Cache & CPU Host Swap (GPU HBM (460 GB) -> Radix Prefix Cache -> CPU RAM Swap -> Recompute Queue).
Trade-Offs & Production: Pre-allocating max_seq_len (32,768 tokens) per active sequence wastes gigabytes on short 512-token chats. Manage GPU HBM like OS virtual memory: Fixed 16-Token Physical Blocks: Divide the 460 GB KV pool into ~90,000 fixed 16-token blocks; allocate blocks on demand via a.
Failure Modes & Application: Paged KV memory management powers modern LLM inference clusters: vLLM / SGLang / TensorRT-LLM: Enables high-concurrency multi-tenant serving on H100 clusters.
Why LLM KV-Cache PagedAttention Matters.
Why this matters: The mechanism: understand how Why LLM KV-Cache PagedAttention Matters works from first principles.
Serving Llama-3-70B (GQA, 80 layers, 8 KV heads, head_dim=128, FP16) on 8× H100-80GB (TP=8) leaves 57.5 GB/GPU (460 GB total) for KV cache after weights (17.5 GB/GPU) and activations (5 GB/GPU).
Each token consumes $2 \times 80 \times 8 \times 128 \times 2\text{ B} = 320\text{ KB}$ globally (40 KB/GPU).
Real-World Impact of Contiguous KV Allocation.
Why this matters: The problem: see what breaks without Real-World Impact of Contiguous KV Allocation under real concurrency or scale.
Naive contiguous KV-cache allocation cripples LLM serving throughput:
- 60–80% Internal Fragmentation: A 512-token chat request reserves a 32K-token slab (
10.5 GB), leaving 98% unused. - Duplicate System Prefixes: Identical 4K-token RAG/system prompts are recomputed and stored separately per user.
- Preemption Thrashing: Under memory pressure, dropping a request forces full O(N²) prefill recomputation unless blocks are swapped over PCIe Gen5 (64 GB/s).
Logical Token Blocks Mapped to Non-Contiguous 16-Token Physical KV Pages
1.Block Size (16 tok): 320 KB/tok × 16 = 5.12 MB global block (640 KB/GPU).
2.Prefix Sharing: Radix/hash-indexed shared blocks use refcount + Copy-on-Write.
3.Swap vs Recompute: PCIe Gen5 (64 GB/s) swaps 640 KB/GPU block in ~10 µs.
4.3-5x Batch Size: Eliminates reserved waste, saturating H100 Tensor Cores.
Virtual-to-physical block tables eliminate contiguous reservation waste and enable zero-copy prefix sharing.
- Problem
- How to implement LLM KV-Cache Eviction & PagedAttention without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- If latency budgets leave no room for synchronous retries, partition KV caches into fixed-size 16-token physical blocks mapped via a block table, and handle memory pressure with prefix-aware LRU eviction, swap-to-CPU, or recomputation.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When LLM KV-Cache Eviction & PagedAttention experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive Solution (and Why It Breaks).
Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.
Think of Naive Solution (and Why It Breaks) as the intuition layer for LLM KV-Cache Eviction & PagedAttention: The problem: see what breaks without Naive Solution under real concurrency or scale.
Pre-allocating max_seq_len (32,768 tokens) per active sequence wastes gigabytes on short 512-token chats. Dynamically realloc()-ing contiguous tensors on every generated token forces expensive GPU-to-GPU memory copies and stalls CUDA kernels.
Naive Solution (and Why It Breaks)
Enterprise Solution: PagedAttention + Prefix Caching + Preemption Policy.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Manage GPU HBM like OS virtual memory:
- Fixed 16-Token Physical Blocks: Divide the 460 GB KV pool into ~90,000 fixed 16-token blocks; allocate blocks on demand via a per-sequence
BlockTableso internal waste is at most 15 tokens per sequence. - Automatic Prefix Caching (CoW): Hash completed 16-token prefix blocks; concurrent RAG requests share the same physical blocks with
ref_count > 1and only allocate new blocks on divergence. - Prefix-Aware Eviction & Swap: Under memory pressure, evict unreferenced prefix-cache blocks via LRU first, then preempt lowest-priority sequences via PCIe Gen5 swap-to-CPU (for long prefills) or recompute (for short prompts).
GPU HBM Blocks, Prefix Cache & CPU Host Swap
1.HBM Capacity: 460 GB / 320 KB/tok ≈ 1.43M active tokens across cluster.
2.No Contiguous Copy: PagedAttention CUDA kernel gathers non-contiguous blocks directly.
3.Eviction Order: 1) Free unreferenced prefix blocks, 2) Swap/recompute lowest priority.
4.Continuous Batching: Iteration-level scheduling packs new tokens into freed slots.
PagedAttention + Radix prefix caching maximizes HBM utilization and continuous-batching throughput.
from collections import OrderedDict
from dataclasses import dataclass
@dataclass
class PhysicalBlock:
block_id: int
block_hash: int | None = None
ref_count: int = 0
class PrefixBlockAllocator:
def __init__(self, num_blocks: int):
self.blocks = [PhysicalBlock(i) for i in range(num_blocks)]
self.free_ids = list(range(num_blocks))
self.hash_to_id: dict[int, int] = {}
self.evict_lru: OrderedDict[int, int] = OrderedDict()
def allocate(self, block_hash: int | None = None) -> PhysicalBlock | None:
if block_hash is not None and block_hash in self.hash_to_id:
bid = self.hash_to_id[block_hash]
blk = self.blocks[bid]
if blk.ref_count == 0:
self.evict_lru.pop(bid, None)
blk.ref_count += 1
return blk
if self.free_ids:
bid = self.free_ids.pop()
elif self.evict_lru:
bid, _ = self.evict_lru.popitem(last=False)
old_hash = self.blocks[bid].block_hash
if old_hash is not None:
self.hash_to_id.pop(old_hash, None)
else:
return None # Trigger LIFO preemption
blk = self.blocks[bid]
blk.block_hash = block_hash
blk.ref_count = 1
if block_hash is not None:
self.hash_to_id[block_hash] = bid
return blk
def free(self, bid: int) -> None:
blk = self.blocks[bid]
blk.ref_count -= 1
if blk.ref_count == 0:
if blk.block_hash is not None:
self.evict_lru[bid] = blk.block_hash
else:
self.free_ids.append(bid)
Where PagedAttention Applies in System Design.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Paged KV memory management powers modern LLM inference clusters:
- vLLM / SGLang / TensorRT-LLM: Enables high-concurrency multi-tenant serving on H100 clusters.
- RAG & Agentic Workflows: Prefix caching cuts TTFT (Time To First Token) by 5–10x on shared system/document prompts.
- Disaggregated Prefill-Decode: Transfers paged KV blocks over NVLink/RDMA between prefill and decode pools.
Practice: Make the trade-off yourself.
How does PagedAttention eliminate the 60–80% memory waste of contiguous KV-cache allocation?