M4-050M4: Sequences & TransformersEfficient Attention & FlashAttentionMedium
⚡Flashcard Drill➔Mastery:
PagedAttention: Eliminating KV-Cache Memory Fragmentation via Virtual Memory Paging
🎯 Active Recall Self-Check (Draft First, Verify After)
Login-free practice tracker: recall core answer, audit pitfalls, and log review status.
Step 1 · Draft your concise answer & assumptions
Step 2 · Check Pitfalls & Follow-up Inquiries
📐 Mathematical Definition
⚡ One-Sentence Core Answer
PagedAttention adapts OS virtual memory paging to LLM serving, storing non-contiguous KV-cache blocks in virtual pages to eliminate internal/external fragmentation and enable memory sharing.
📌 Key Takeaways
- •Core problem: traditional serving pre-allocates contiguous memory for maximum context (e.g., 2048 tokens), wasting 60–80% of VRAM on memory fragmentation
- •Virtual memory paging: partitions KV cache into fixed-size physical blocks (e.g., 16 tokens), mapped via dynamic page tables
- •Copy-on-write sharing: enables zero-memory duplication in parallel sampling, beam search, and shared system prompts
📐 Mathematical Derivations
Architecture and Mechanics (Kwon et al., SOSP 2023; vLLM):
In standard LLM serving systems, GPU memory for the KV cache of a request must be allocated contiguously. Because request generation lengths are unpredictable, systems must over-allocate memory for the maximum possible length (e.g., 2048 tokens).
- Memory Waste Taxonomy:
1. Internal Fragmentation: Allocated memory reserved for future tokens that are never generated.
2. External Fragmentation: Unusable memory holes scattered between terminated requests of variable lengths.
3. Reservation Waste: Total wasted memory typically reaches of total GPU VRAM.
PagedAttention Architecture:
- Partition physical GPU memory into a pool of fixed-size Physical Blocks (e.g., each block holds keys and values for 16 tokens).
- Each request maintains a Logical Page Table mapping logical token indices to arbitrary non-contiguous physical blocks in GPU VRAM.
- When a new token is generated, if the current block has space, it is appended locally; if full, the block manager allocates 1 new physical block from the global free pool.
- Zero-Copy Forking (Copy-on-Write):
In parallel sampling (generating responses for 1 prompt) or shared system prompts, multiple requests point to the exact same physical prompt blocks. Memory is duplicated only when a request writes a unique generated token.
In standard LLM serving systems, GPU memory for the KV cache of a request must be allocated contiguously. Because request generation lengths are unpredictable, systems must over-allocate memory for the maximum possible length (e.g., 2048 tokens).
- Memory Waste Taxonomy:
1. Internal Fragmentation: Allocated memory reserved for future tokens that are never generated.
2. External Fragmentation: Unusable memory holes scattered between terminated requests of variable lengths.
3. Reservation Waste: Total wasted memory typically reaches of total GPU VRAM.
PagedAttention Architecture:
- Partition physical GPU memory into a pool of fixed-size Physical Blocks (e.g., each block holds keys and values for 16 tokens).
- Each request maintains a Logical Page Table mapping logical token indices to arbitrary non-contiguous physical blocks in GPU VRAM.
- When a new token is generated, if the current block has space, it is appended locally; if full, the block manager allocates 1 new physical block from the global free pool.
- Zero-Copy Forking (Copy-on-Write):
In parallel sampling (generating responses for 1 prompt) or shared system prompts, multiple requests point to the exact same physical prompt blocks. Memory is duplicated only when a request writes a unique generated token.
🏭 Production Trade-offs
Throughput impact: By eliminating memory fragmentation and enabling prompt KV-cache sharing, PagedAttention (vLLM) increases serving batch sizes by , delivering an immediate boost in overall serving throughput.
⚠️ Common Interview Pitfalls
- ✕Setting block size too small (e.g., 1 or 2 tokens), causing page table lookup overhead to bottleneck GPU memory controllers
- ✕Setting block size too large (e.g., 256 tokens), which reintroduces internal memory fragmentation
🎯 Interviewer Follow-up Inquiries
- ?How does PagedAttention implement Copy-on-Write (CoW) during parallel sampling in vLLM?
- ?What is the optimal physical block size (e.g., 16 vs 32 tokens) in PagedAttention to balance memory efficiency and kernel throughput?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
中文速览与面试要点
解释 PagedAttention 如何解决 KV Cache 碎片
把 KV cache 分成固定大小的块(page),用块表间接映射,实现非连续存储、按需分配与共享,消除碎片。
核心要点
- 数学机理: 问题 ——传统推理引擎为每个请求 预分配 一段连续的 KV cache 空间(大小 = max_seq_len × 层数 × KV 头 × d_h)。但实际输出长度 不可预知 (可能远小于最大长度),故 (a) 内部碎片 ——分配了但没用到的空间浪费(实测可达 60%~80%);(b) 外部碎片 ——不同请求的连续空间大小不一,导致显存难以利用;(c) 无法共享 ——相同前缀(如系统提示、few-shot 示例)在每个请求中重复存储。 PagedAttention(Kwon 等 2023,vLLM 的核心) 借用操作系统 虚拟内存分页 的思想:把 KV cache 切成固定大小的 块(block/page,如 16 个 token) ;每个序列维护一个 逻辑块 → 物理块 的映射表(block table);物理块 无需连续 ,按需分配。 收益 :(a) 消除碎片 ——浪费最多一个块(≤16 token 的空间),显存利用率接近 100%;(b) 按需增长 ——序列变长时动态分配新块;(c) 共享前缀 ——相同前缀的请求可 指向同一物理块 (引用计数),显存与计算都省(配合 prefix caching);(d) 灵活调度 ——块级管理使连续批处理(continuous batching)与抢占(preemption)更易实现。 效果 ——vLLM 报告吞吐提升 2~4 倍(同等延迟下),主要来自显存利用率与批大小的提升。
- 深度剖析与工程权衡:① 与操作系统的类比 ——PagedAttention 完全对应 OS 的'分页 + 页表 + 写时复制(CoW)':前缀共享对应 CoW(多个序列共享只读块,写入时复制);这使'LLM 推理的内存管理'成为一个成熟的系统工程问题。② 块大小的权衡 ——块太小则映射表开销大、kernel 效率低;块太大则碎片增加、共享粒度粗。实践中常用 16(vLLM 默认)。③ 与连续批处理的协同 ——PagedAttention 使'新请求可随时插入正在运行的批'(因为块可动态分配),这是连续批处理能实现的前提;两者共同构成现代推理引擎的基础。④ 与 prefix caching 的关系 ——PagedAttention 的块级共享是 prefix caching 的实现基础(用哈希索引相同前缀的块);对'多请求共享同一长系统提示'的场景收益巨大。⑤ 与 Flash Attention 的分工 ——Flash 优化'计算'(不物化 L×L),PagedAttention 优化'存储'(KV cache 的内存管理);推理引擎通常两者都用(Flash 做 prefill 计算、Paged 做 KV 管理)。⑥ 面试要点 ——被问'PagedAttention 解决什么',应给出' 预分配导致碎片(最多浪费 60-80%)→ 分页按需分配 + 块表间接映射 + 前缀共享 ',并量化收益(显存利用率近 100%、吞吐 2~4 倍);能类比 OS 虚拟内存是深度理解的标志。
- 传统预分配最大长度 → 内部碎片(最多浪费 ~60-80%)
- 分页后按需分配,浪费 ≤ 一个块
- 支持前缀共享(相同前缀复用同一物理块)
常见陷阱
- 以为 PagedAttention 加速了注意力计算(它优化的是 KV 内存管理)
- 忽略前缀共享对多请求场景的收益