SGLang推理服务教程 · 05-KVCache内存池与RadixCache

05 - KVCache 内存池与 RadixCache

所属系列:SGLang 推理服务教程 | 前置:04-Scheduler调度与前向执行 | 下一篇:06-平台抽象与Attention后端注册表
证据基线:commit 69028290,全部为静态源码走读。本章主战场:srt/mem_cache/memory_pool.py、srt/mem_cache/allocation.py、srt/mem_cache/allocator/(paged.py、swa.py)、srt/mem_cache/radix_cache.py、srt/hardware_backend/npu/。

本篇知识图谱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((KVCache 内存池与 RadixCache))
三层存储
ReqToTokenPool 行映射
加1 padding 行
MHA MLA DSA 池层级
FP8 uint8 存储
页式分配器族
PagedAllocator 页对齐
Triton alloc kernel
SWA 双池映射
延迟释放 reuse guard
分配路径
alloc_for_extend
fail loud 请求槽
页路径与 token 路径
RadixCache
页对齐匹配
extra_key 命名空间
chunk 级 checkpoint
LRU 堆驱逐
平台适配
NPU 子类覆盖
is_npu 条件分支
与调度回环
memory_budget 账本
retract 释放回池

本篇目标

  1. 建立 KV 三层存储模型:请求→token 行映射、页式分配器、物理池,外加 RadixCache 这个「元数据第四层」。
  2. 看懂页式分配器族的三个关键机制:Triton alloc kernel、SWA 双池映射、延迟释放 + reuse guard。
  3. 掌握 RadixCache 前缀复用的四件事:页对齐匹配、extra_key 命名空间、chunk 级 checkpoint、LRU 驱逐。
  4. 知道 FP8 KV 与 NPU 在这一层如何收口。

1. 三层存储鸟瞰(memory_pool.py)

1
2
3
4
5
6
7
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
flowchart TD
A["ReqToTokenPool 行映射<br/>memory_pool.py:382<br/>加1 padding 行 :416-418"] -->|"out_cache_loc 写回"| B["页式分配器<br/>allocator/paged.py:132<br/>Triton kernel :259-267"]
B -->|"分配物理页"| C["物理池 KVCache 家族<br/>:1949 → MHA :2282 MLA :4875 DSA :5467"]
D["RadixCache 元数据层<br/>radix_cache.py"] -->|"命中即复用 命中前缀免算"| B
D -->|"驱逐时 free_segment"| B
B -->|"延迟释放 staged"| E["在途写保护 reuse guard<br/>:177-193"]

第一层 ReqToTokenPool(mem_cache/memory_pool.py:382,docstring “maps a request to its token locations” :383):一张 (size+1) × max_context_len 的 int32 表(:422-424),第 i 行存第 i 个请求每个 token 的 KV 物理位置。它有一个关键的 +1 设计——注释原文(:416-418):“+1 padding row at index 0: cuda-graph padded batches default req_pool_indices to 0, so dummy reads/writes land here harmlessly”——cuda-graph 补齐产生的哑请求都指向第 0 行,越界读写落在无害的 padding 上。这正是 04 章 decode graph 路径能安全回放的地基之一。

第二层 物理池(抽象基类 KVCache :1949):按模型注意力族分层(class 层级 grep 实测):

池 位置 说明
MHATokenToKVPool(KVCache, MHAKVView) memory_pool.py:2282 标准 MHA 双缓冲 k_buffer/v_buffer(:2306-2307)
MLATokenToKVPool(KVCache, MLAKVView) :4875 DeepSeek MLA 压缩 latent
DSATokenToKVPool(MLATokenToKVPool) :5467 DSA 稀疏注意力,继承 MLA
HybridLinearKVPool / MiniMaxSparseKVPool 等 :4255 / :6183 hybrid/线性注意力与稀疏变体

请求映射层也有对应家族:hybrid(含线性注意力/Mamba)模型用 HybridReqToTokenPool(:1419)——它额外持有状态槽(基类预留的 mamba_pool/state 字段 :397-402);循环状态的物理侧是独立的 MambaPool(:521)。

变体族(NoOp :3537、FP4 :3648、PageMajor :3802、MXFP8 :3874)说明这一层是量化与布局改造的落脚点(07 章回收)。

FP8 KV 的 uint8 存储(memory_pool.py:1988-1992,位于 KVCache.__init__):dtype 为三种 float8 时 store_dtype = torch.uint8,注释写明原因——“Tensor.index_put is not implemented for torch.float8_e5m2”。存储与计算 dtype 分离:写池用 uint8,attention 读出时再按 fp8 解释。

2. 页式分配器族(allocator/)

ls mem_cache/allocator/ 实测七个模块:base、token(page_size=1)、paged、swa、mamba、hisparse、page_interleave。主力 PagedTokenToKVPoolAllocator(allocator/paged.py:132)的契约写在 docstring:“the indices handed to one request are always page-aligned”(:133-134);类属性 supports_reuse_guard = True(:139)。

三个关键机制:

  • Triton alloc kernel:use_triton_kernels 按平台能力开(:153),extend 分配直接发射 alloc_extend_kernel[(bs,)](:259-267),否则走 naive 逐条(:268-277);分配前的可用页数守卫还会先精确计数,防 kernel 越界读 free_pages(:240-253)。还有个工程细节:ROCm 上预暖 torch.unique,免得首次 free 撞上 ~200ms 的 JIT(:160-168)。
  • 延迟释放 + reuse guard:释放的页先进 staged_pages 暂存——set_reuse_guard_event 的 docstring(:178-182):“Cover KV writes still in flight when the scheduler releases pages. PD transfers are not stream-ordered with those writes. Freed pages stay staged until allocation pressure requires a merge”。合并回 free_pages 时先同步守护事件再 sort(merge_and_sort_free :185-193)。即「延迟释放加 reuse guard 防在途写复用」:在途 PD 传输读走的页,绝不立即二次分配。available_size 也把 staged 计入(:171-172)。
  • SWA 融合映射:SWATokenToKVPoolAllocator(allocator/swa.py:37,“Allocator for SWA hybrid KV cache”)持 full 与 swa 双分配器(:58-70 起),按 free/free_swa/free_swa_segment 分窗释放(:498-681);两层池的位置换算由 BaseSWAKVPool.translate_loc_from_full_to_swa(kv_indices)(mem_cache/base_swa_memory_pool.py:55)完成——一个请求的 token 在 full 窗与滑窗里各有一份视图,靠这个翻译函数对齐。

分配入口是 alloc_for_extend(mem_cache/allocation.py:363-484,docstring “Allocate KV cache for extend batch and write to req_to_token_pool” :366-367):先 maybe_evict_swa(:374)清窗外 token,再 alloc_req_slots——池满直接 RuntimeError,fail-loud(docstring :370-371 明说);随后按页大小分岔:page_size=1 走 alloc_token_slots(:424-432),页式走 alloc_paged_token_slots_extend(:474-484),返回的 out_cache_loc 最终写回 req_to_token(:486 起)。

3. RadixCache 前缀复用(radix_cache.py)

RadixCache 是架在分配器之上的「元数据第四层」:树节点记录 token 序列 → 池位置的映射,让相同前缀免算。

  • 页对齐匹配(match_prefix,radix_cache.py:369-422):key 先 page_aligned(self.page_size)(:411,docstring :386-388 说明页内零头被截掉),命中路径中途分裂节点以暴露精确边界(:395-403),同时刷新访问时间戳供驱逐策略使用(:399-400)。
  • extra_key 命名空间(docstring :372-381):“Entries that share identical leading token ids but have different extra_key values are intentionally kept disjoint”——用途两条:隔离不同 LoRA/adapter 的 KV(:378)、隔离不应共享状态的请求(“different sampling salt, cache version, or retrieval augmentation context” :379-381)。RadixKey 的字段表证实这是键的一部分:__slots__ = ("token_ids", "extra_key", "cache_salt", ...)(:63-76)。
  • chunk 级 checkpoint(checkpoint,:515-550):chunked prefill 每算完一段就把已算前缀插进树(_insert_cache :526-528,Pure-SWA 树还要对 window_evict_floor 取整对齐 :519-525),回写 req_to_token 行(:538-541),并把树外残留的部分页标记为受保护(:543-546 注释),最后换锁与 last_node(:548-550)。没有它,长 prompt 分块 prefill 的中间成果每次都白算。
  • LRU 驱逐(evict,:559-587):可驱逐叶子进小顶堆(eviction_strategy.get_priority :566-569),逐个 free 后父节点若无其他子且 lock_ref==0 也入堆(:572-582)——被运行中请求引用的前缀不会被驱逐;默认策略名 “lru”(:317)。free 走 free_segment(x.value, start_pos=0)(:576),树里的值是页对齐拷贝(:575 注释)。
  • 锁引用是复用与驱逐的开关:inc_lock_ref(:589-594)沿命中路径逐节点加 lock_ref——04 章 PrefillAdder 准入时锁住要复用的前缀,evictable_size(:628)随之收窄;请求结束解锁,前缀重新进入可驱逐池。复用的生命周期 = 从准入锁到完成解锁。

4. FP8 KV 与 NPU 适配(线2 收口)

  • FP8:§1 的 store_dtype 分离(:1988-1992)就是 FP8 KV 的全部存储层改动;量化方法本体在 srt/layers/quantization/(07 章)。
  • NPU 子类覆盖:NPU 侧不抄改共享代码,而是子类化后覆盖——NPUMHATokenToKVPool(MHATokenToKVPool)(srt/hardware_backend/npu/memory_pool_npu.py:92)、NPUMHATokenToKOnlyPool(:579)、NPUPagedTokenToKVPoolAllocator(PagedTokenToKVPoolAllocator)(hardware_backend/npu/allocator_npu.py:16),DSV4 还有专属 ReqToToken 池(dsv4_req_to_token_pool.py:151/:181)。共享池内只留少量 _is_npu 条件分支(如 memory_pool.py:2308-2312 的 NPU 条件初始化),平台差异收口在 hardware_backend 的子类里——这是 06 章平台抽象的又一实例。

5. 与调度层的回环

把 04 章的账本接上(全部锚点已在该章验证,此处只标注衔接点):

  • PrefillAdder 的 memory_budget(schedule_policy.py:1139-1143)= 分配器 available_size(paged.py:171-172)减去 running 占用——RadixCache 的可驱逐量是预算的弹性部分;
  • KV 满时 retract_decode(schedule_batch.py:3018)释放被抽回请求的页,页先进 staged(§2 延迟释放);
  • chunked prefill 的段间成果由 checkpoint(§3)沉淀进树,下一次匹配直接命中;
  • decode graph 回放(model_runner.py:2141-2146)依赖 §1 的 +1 padding 行兜住哑请求。

本篇小结

  • 三层存储:ReqToTokenPool 行映射(+1 padding 防图越界,:416-418)→ 页式分配器 → 物理池(MHA :2282 / MLA :4875 / DSA :5467 层级);FP8 KV 以 uint8 落盘(:1988-1992)。
  • 分配器族三机制:Triton alloc kernel(:259-267)、延迟释放 + reuse guard(:177-193,防 PD 在途写复用)、SWA 双池融合映射(swa.py:37 + base_swa_memory_pool.py:55)。
  • alloc_for_extend(allocation.py:363-484)是唯一入口:SWA 清扫 → fail-loud 请求槽 → 按页分岔。
  • RadixCache 四件事加一把锁:页对齐匹配(:369-422)、extra_key 命名空间隔离 LoRA/cache_salt(:372-381、:63-76)、chunk 级 checkpoint(:515-550)、LRU 堆驱逐(:559-587);inc_lock_ref(:589-594)把「复用中」变成驱逐免疫。
  • NPU 以子类覆盖收口(memory_pool_npu.py:92、allocator_npu.py:16),共享层只留条件分支。
  • 下一章看这些池与策略如何按平台与注意力后端被选中:06-平台抽象与Attention后端注册表。

前置:04-Scheduler调度与前向执行 | 下一篇:06-平台抽象与Attention后端注册表 | 回目录:README