---
title: "【AI 核心深度 M4-050】解释 PagedAttention 如何解决 KV Cache 碎片（PagedAttention: Eliminating KV-Cache Memory Fragmentation via Virtual Memory Paging）深度数理推导与工程落地解析"
canonical_url: "https://airsota.com/2026/10/01/science-depth-m4-050-efficient-attention-flashattention/"
date_published: "2026-10-01T12:25:02-07:00"
date_modified: "2026-10-01T12:25:02-07:00"
language: "zh-CN"
categories: ["AI 核心深度 856 题 (Science Depth)", "TalentMe (AI 学习与算法架构)", "大厂算法与面试备考 (Interview Guides &amp; Math)"]
tags: ["applied-scientist", "efficient-attention-flashattention", "machine-learning", "module-m4", "science-depth"]
summary: "把 KV cache 分成固定大小的块（page），用块表间接映射，实现非连续存储、按需分配与共享，消除碎片。"
publisher: "AirSOTA (https://airsota.com)"
---

# 【AI 核心深度 M4-050】解释 PagedAttention 如何解决 KV Cache 碎片（PagedAttention: Eliminating KV-Cache Memory Fragmentation via Virtual Memory Paging）深度数理推导与工程落地解析

> **Executive Summary**: 把 KV cache 分成固定大小的块（page），用块表间接映射，实现非连续存储、按需分配与共享，消除碎片。

> 
**所属模块**：`M4 · 序列与 Transformer (Sequences & Transformers)` | **专题分类**：`高效注意力与 FlashAttention (Efficient Attention & FlashAttention)` | **难度等级**：`Medium`

### 一、核心一句话结论 (One-Sentence Summary)

**把 KV cache 分成固定大小的块（page），用块表间接映射，实现非连续存储、按需分配与共享，消除碎片。**

*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 Insights)

- 📌 传统预分配最大长度 → 内部碎片（最多浪费 ~60-80%）

- 📌 分页后按需分配，浪费 ≤ 一个块

- 📌 支持前缀共享（相同前缀复用同一物理块）

**English Insights:**

- *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 Principles & Derivation)

$$text{logical block}totext{physical block table};qquad text{waste}le text{one block per seq}$$

数学机理：**问题**——传统推理引擎为每个请求**预分配**一段连续的 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 倍（同等延迟下），主要来自显存利用率与批大小的提升。

  📖 查看英文严格数学推导 (English Mathematical Derivation)

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 $60%-80%$ 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 $0, dots, T-1$ 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 $N$ 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.

  

### 四、工业级落地权衡与工程考量 (Industrial Trade-offs)

深度剖析与工程权衡：① **与操作系统的类比**——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 虚拟内存是深度理解的标志。

  ⚙️ 查看英文落地权衡分析 (English Systems & Trade-offs)

Throughput impact: By eliminating memory fragmentation and enabling prompt KV-cache sharing, PagedAttention (vLLM) increases serving batch sizes by $2-4times$, delivering an immediate $2-4times$ boost in overall serving throughput.

  

### 五、常见面试避坑陷阱 (Common Pitfalls & Traps)

- ⚠️ 以为 PagedAttention 加速了注意力计算（它优化的是 KV 内存管理）

- ⚠️ 忽略前缀共享对多请求场景的收益

**English 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*

### 六、高频深度面试追问与预测 (Follow-Up Questions)

- **为什么分页能提升吞吐？**

- *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?*

### 七、知识图谱对齐 (Knowledge Graph Anchor)

- 🔗 **关联底层卡片**：`FlashAttention 核心机理：SRAM 分块平铺与 Online Softmax 消除 HBM 瓶颈` (`FlashAttention: Tiling, Online Softmax & IO Awareness`)

- 🗺️ **知识图谱模块**：`AI 基础设施工程导图`

  

#### 🔬 算法科学家与机器学习深度考察全量题库 (Science Depth)

  本题收录于 **TalentMe 算法科学家深度考察真题库 (Science Depth)**。全库共 856 道硬核考点，深度覆盖数学统计、经典ML、深度学习、Transformer、大语言模型、多模态、推荐系统与 MLOps。支持 Jev 面经智能匹配、一键离线单文件 HTML 手册导出并直连 Obsidian 本地记忆。

  [👉 前往 TalentMe 交互式研读本题 (M4-050) →](https://talentme.airsota.com/tools/science-depth/M4-050)

---
*Source: [AirSOTA Knowledge Matrix](https://airsota.com/2026/10/01/science-depth-m4-050-efficient-attention-flashattention/) · Complete Index: [llms.txt](https://airsota.com/llms.txt)*
