Skip to content

Latest commit

 

History

History
543 lines (452 loc) · 40.1 KB

pool.md

File metadata and controls

543 lines (452 loc) · 40.1 KB

kern-pool:tokens → store

状态的记账层重设计。起因是一个 review 找到的 bug(半页 checkpoint 之后 host 层按 node id 复用旧副本),追下去发现它不是一处笔误,而是几个接口没把不变量放进类型里。 这份文档定下 kern-pool 的模型和接口(2026-09-14 一个 PR 落地,第 7 节是门禁结果)。 设计对照了三个开源实现: NVIDIA Dynamo 的 KVBM(lib/llm/src/block_manager)与 kv_router 的 radix indexer (lib/kv-router/src/indexer),以及 SGLang 的 RadixCache / HiRadixCache / MambaRadixCache 和它的 Rust 内核(rust/sglang-radix-tree)。

1. 结论

  • 索引是 tokens → store。 调用方拿一串 token 来,得到一个持有前缀字节的 store; page 不出现在索引的契约里,也不出现在 kern-pool 的公开词汇里。
  • 共享单位仍然是 page,节点自创建起冻结。 这是三个参考实现的共同选择,也是 kernel 按 page table 寻址(一页一个写者)决定的。索引按 token 键,字节按页共享, 两者不冲突:索引条目持有一个 store,store 持有一条页链。
  • 所有权,不是 id。 每个句柄(Lease、Checkpoint、Hit)持有它依用的东西,drop 即归还;裸 i32 不穿过任何模块边界。"已经有一份"由节点自己的 Arc 表达,不再有 按 id 查的镜像表。
  • 一个 tier(2026-10-27 起)。 只有 device 一层:Checkpoint 是具体类型(store.rs), Storage trait、Store<T>、Host / Parked、节点的 host twin、Tier / Found 随 host 层一起删除——跨机的第二层是 Mooncake 池(第 9 节),按 key 存对象,本 crate 只出 纯决策(pooled.rs)。2026-09-14 到 10-27 之间的两层设计留在下文标了"历史"的段落里。
  • 单线程。 索引与池由 scheduler 线程独占,&mut 修改,没有并发;Arc 和一把从不 争用的 Mutex 只为 Send(句柄可能在别的线程 drop)。

2. 名词

Storage(历史,2026-10-27 删除)

pub trait Storage: sealed::Sealed + Send + Sync + 'static {
    type Page: Copy + Ord;                 // Pool: 页号 i32;Host: host 页号 u64
    type Slot: Copy + Ord;                 // Pool: slot 号 i32;Host: host slot 号 u64
    type Twin: Default + Send + Sync;      // 节点对另一 tier 副本的了解
    fn give_page(&self, page: Self::Page);
    fn give_slot(&self, slot: Self::Slot);
}

trait 只管归还:分配留在各自的类型里,因为 Pool::take 的两态拒绝(Busy / ExceedsPool,2026-10-27 起没有 Remapping:页数与 slot 数装载时定死)和 Host 的 "取最小空闲号"没有共同的签名可抽。Pool(页、slot、manifest 的表)和 Host(host 页、 host slot 两段定长预算)实现它, trait 是 sealed 的,别处不能。页号是裸 i32 / u64,但只出现在两处:交给 runtime 执行的 Copies,和只读的观测(Lease::page_ids()、Checkpoint::page_ids()、 Parked::page_ids(),harness 与测试读字节用)——没有任何接口按它们找东西。

Host:按单元记账,不知道字节(2026-10-09;历史,2026-10-27 删除)

Host::new(pages, slots) 是两段定长预算:host 页 0..pages、host slot 0..slots, 各取最小的空闲号(没发出过的号是一个水位,还回来的在水位下面的一个有序集合里)。 Parked 的页、Host::park / Host::restore 的 Copies<i32, u64> / Copies<u64, i32> 的 host 一侧、runs 折叠的连续页,都是单元号。一个单元多少字节是 shell 的事:runtime (park.rs)的 pinned 块前段是 host 页(每页是所有分页 state 的该页首尾相接),后段是 host slot(每个是所有 per-seq state 的 slot 首尾相接),偏移 = 单元号 × 单元字节 + state 在单元里的偏移;Runtime::reserve_host(pages, slots) 收的也是单元。

为什么不按字节:流水线头(kern-serve/src/pp/head.rs)用一份记账代表 S 个 stage 进程,每个 stage 持有模型的不同层,同一页、同一 slot 在各 stage 上字节数不同(没有 per-seq state 的 stage,slot 是 0 字节),页号却全流水共用。host 层同理:头上一份 Host 发 host 页号和 host slot 号,每个 stage 用自己的单元字节去乘。按字节的 first-fit 只对一个进程成立。

代价是两段在 reserve 时定死:之前页从低端、slot 从高端共用同一块字节,谁用谁占。 切分是 kern_runtime::host_split(bytes, page_bytes, slot_bytes, turn):每 turn 页配一个 slot, 即一个 parked 条目的样子——自己一个 slot,加上它在同一 session 前几轮共享的前缀之后新增的那一轮的页; manifest 只有一种单元时全给它。turn 来自 --host-turn(token,默认 8192,按 page unit 向上取整成页), --host-gib(每张卡 Runtime::host_units,流水线 head 按段)和 agentx_replay --host-turn 都走它。 这样 slot 的字节占比由单元字节数推出来:qwen3.8(784 token/页、49 MiB 页、147 MiB slot)是 11 页一个 slot, slot 占 21%;full K3 PP8 段(64 token/页、216 KiB 页、55.9 MiB slot)是 128 页一个 slot,占 67%。

依据是 AgentX 回放(2026-10-09,~/bench_results/2026-10-09-pd-agentx/x3-agentx/results/replay/)按 --host-turn 扫, 命中率(%):

--host-turn qwen3.8 每 slot 页数 / slot 占比 / c32 K3 slot 占比 K3 c24 K3 c32 K3 c64
2048 — 89% 97.3 97.0 96.3
4096 6 / 33% / 95.7 81% 97.5 97.4 97.0
8192 11 / 21% / 96.0 67% 97.6 97.4 97.2
9408 12 / 20%(旧的五分之一)/ 96.0 — — — —
12544 / 12288 16 / 16% / 95.8 58% 97.5 97.4 97.1
16384 — 51% 97.5 97.4 97.0
18816 / 32768 24 / 11% / 95.4 34% 97.4 97.2 96.8
65536 — 21%(≈ 旧的五分之一) 97.2 97.0 96.5

qwen3.8:device 250 GiB、host 512 GiB;K3:PP8 head 的段形状,131 slot、13.86M token、host 128 GiB/段, 不带 host 时 c24 95.0%。同一个 8192 在两个模型上都在最好值上;之前固定五分之一给 slot(在 qwen3.8 上量的) 到了 K3 是 slot 先用光,128 GiB 只用到 52 GiB。c128 的 K3 反过来要更多页(8192 是 89.9%,五分之一 90.7%, slot 35–50% 91.6–91.8%):并发高了,每个 parked 条目被续上之前要撑更久,旧轮更多被丢,新增页的比例跟着变。 8192 是这份轨迹的量,不是推出来的:一轮新增 token 明显不同的负载要重扫。

Node:一页,冻结

pub struct Node<T: Storage> {              // 字段 crate 私有;pub 只因为它是 Twin 里的类型
    page: T::Page,
    parent: Option<Arc<Node<T>>>,          // 持有一个节点就持有它到根的每一页
    tier: Arc<T>,                          // drop 时把 page 还给它
    twin: T::Twin,                         // Pool: Mutex<Weak<Node<Host>>>;Host: ()
}

不变量:一个 Node 存在的那一刻它的页就不再被写。 节点只从三处产生:lease 写满 的整页(checkpoint / retire / fork 把它移进链)、为一个新持有者拷出来的半页、 retire 时 lease 消失后原地封存的半页。运行中的 lease 永远不写任何 Node 的页。 这一条之前在 Pool::checkpoint 上被打破(半页 checkpoint 后 lease 接着写同一页), host 层按 node 去重就读到过期字节;这是 review 的 P1。

(历史,twin 随 host 层删除)twin 是 device 节点对它 host 副本的弱引用。park 时逐节点看 twin:活着就复用,否则 分配、拷贝、记下。用节点自己的字段而不是按 id 的表,两个原因:id 表的 key 可以在内容 变了之后仍然相等(这次的 bug),用指针当 key 又有 ABA;节点持有自己的链接,两者都没有。 wake(Host::restore)进 lease 的整页节点在创建时就带上 twin,所以同一 session 醒来再睡 不再拷第二份(lessons.md 2026-09-03 记的那条缺口)。

Checkpoint:一个前缀的字节

pub struct Checkpoint {
    len: usize,                            // 持有的 token 数,≥ 1
    pages: usize,                          // ceil(len / unit);slot-only 时 0
    chain: Option<Arc<Node>>,              // 页链;slot-only 时 None
    slot: Option<Arc<SlotOwn>>,            // 恰在 len 之后的 recurrent state;Drop 归还
}

(2026-10-27 前是 Store<T: Storage>,Checkpoint = Store<Pool>、Parked = Store<Host>。) Checkpoint: Clone:clone 是同一份字节的又一个持有者(Arc 链、Arc slot),最后一个 持有者 drop 时归还。索引条目和 Hit 拿的是同一份,不需要 id 也不需要类型擦除。带 slot 的 store 只在精确 len 上可用(state 是"恰好这些 token 之后"的状态);不带 slot 的可在它任何整页上可用。

Lease:唯一能写的东西

pub struct Lease {
    chain: Option<Arc<Node<Pool>>>,        // 共享的整页
    shared: usize,
    pages: Vec<i32>,                       // 全部页号;shared 之后的是自己的,Drop 归还
    slot: Option<Arc<SlotOwn<Pool>>>,
    prefix: usize,                         // 已填的位置,不再命名
}

Lease 不泛化:它是唯一被 kernel 寻址的对象(page table 行、slot mapping、line index),host 单元从不进表。行由 extend_row 铺,位置由 slot(pos) 给:pos 必须 过了 prefix,也必须过了 shared 页——一个 Node 存在的那一刻它的页就不再被写, 封页的租约自己也不例外(slot 断言,tests/pool.rs 的 a_lease_refuses_the_pages_it_sealed);page_ids() 留给 harness 读字节,不是句柄。

Pool::new(manifest, pages, slots)(2026-10-27 起)就是页数和 slot 数本身:runtime 把 --capacity 的 token 数除以页单位得到页数,--max-seqs 经 slots_for 得到 slot 数, 再各自一块 alloc_vmm;没有块、没有按块取整,小池子想多小就多小。

Copies:借用来源的拷贝计划

pub struct Copies<S = i32, D = i32> {
    pub pages: Vec<(S, D)>,
    pub slot: Option<(S, D)>,
}

之前的 Copies(device→device)、Park(device→host)和 wake 里手拼的 Vec<(i32, u64)> 合成一个类型(2026-10-27 起只剩 device→device,Copies 不再泛型)。plan 由要它的 shell 当场执行、不存,所以没有绑生命周期。

Prefix:token 索引

pub struct Prefix<R: Kept = Checkpoint> { unit, root: Node, lru, clock, .. }

pub struct Hit<R> {
    pub len: usize,                        // 可用的前缀长度
    pub found: R,                          // 条目的一个 clone
}

条目持有 R,Hit 持有它的 clone(Kept: Clone,Checkpoint 和 tray 的 Group<X> 都是)。make_room 把条目删掉不影响手里的 Hit(lessons.md 2026-09-04"make_room 之后旧的命中不能再用"这类错误从类型上消失)。条目按 token 键 操作:insert(&key, r)、lookup(&tokens),腾地方只有一个动作 evict():丢掉最不值钱 的条目(次序见下文"带 state 的条目分档"),返回它的 key 说明动了谁——scheduler 与 agentx_replay 之前各写一份同样的循环,现在是表的。哪个条目最冷是表自己的事,外面看不到 LRU。TP 下 R 是 tray 的 Group<Checkpoint>,索引仍然是 tray 一棵,不变。(2026-10-27 前 是 Prefix<R, P>、Found::{Resident, Parked}、evict(park),随 host 层删除。)

Interleave / Deal:按位置分发给一个组(2026-10-09)

pub struct Interleave { w }                    // new(w) 拒 0;owner(p) = p % w,local(p) = p / w,
                                               // len(n, m) = 前 n 个位置里成员 m 持有几个
pub struct Pages<'a> { pub ids: &'a [i32], pub unit: u64 }
pub struct RowRun { pub src_row, pub src_stride, pub dst_row, pub rows }
pub fn deal(src: Pages, dst: Pages, il: Interleave, m: u64, len: u64) -> Result<Deal>

manifest 里 paged state 写 shard: {by: position} 时(decode 的 DCP),组里每个成员 一个 Pool,各自按本地位置记账:一条 n 个位置的序列在成员 m 上租 len(n, m), 对称地租 len(n, 0) = ⌈n/w⌉,最多浪费一个位置。Pool 本身不变。

deal 是 P→D 交接的纯计划:P 的整序列页表(每页 unit 行,一行 = 一个 token 槽) 里属于成员 m 的行,折成按本地位置排序的最长 run——目标连续、源每隔 w 行一行。 run 只在两侧的页物理相邻时跨页:64 行一页、8 个成员时,P 的第 k 页给成员 m 的是 第 m, m+8, …, m+56 行,落在本地第 ⌊k/8⌋ 页的第 8(k mod 8) 到 8(k mod 8)+7 行;两侧 都连续的页合成一个 run。所有 paged state 共用页号,一个 Deal 管全部层,runtime 按 各 state 的行字节放大。Deal 只能由 deal 造出:它命名的行都在给它的页里(成员号、 页数、负页号都在构造时拒掉)。门禁(tests/deal.rs):3000 个随机 (w, 两侧页大小, 长度, 页表) 对逐行参考模型——每个源位置 p 恰好落在成员 p % w 的本地位置 p / w, 各成员行数之和 = 长度,run 不可再合并。

3. 操作

操作 签名 页 slot
Pool::lease(tokens) -> Lease 全新 全新,runtime 清零
Pool::checkpoint(&mut Lease, len) -> (Checkpoint, Copies) 整页入链共享;len 在页中间时那半页拷给 checkpoint,lease 继续写自己的 拷进新 slot
Pool::retire(Lease, len) -> Checkpoint 整页入链,半页原地封存,多余的还 易主,不拷
Pool::restore(&Checkpoint, len, tokens) -> (Lease, Copies) 整页共享,半页拷给 lease 拷进新 slot
Pool::fork(&mut Lease, len, tokens) -> (Lease, Copies) 整页共享,半页拷给孩子 拷进新 slot

三条规则贯穿全部操作:整页共享、半页拷给新持有者、写者只有 lease。 restore 和 fork 本来就这样,checkpoint 是唯一的例外,改成一致。半页拷贝只在页中间 checkpoint 时发生;scheduler 在页边界(纯 KV,零拷贝)和带 state 模型的 history 末尾之前的最后一个 页边界(Request::history_tokens,前端量出的 prompt 与 generation prompt 的分界,向下取整到页)留 快照,没有 history 末尾的请求才在结束时留(retire,零拷贝)——history 那次只付一份 state 拷贝, 换来回放别人回复的下一轮(AgentX)也能命中上一轮的 prompt,每轮只留这一份;落在页边界,池化层 才叫得出它的名字(第 9 节),下一轮多算不到一页。K1c 的显式断点(system prompt 末尾)是同一种页中间 checkpoint。

wake 直接醒进请求的租约(历史:host 层于 2026-10-27 删除;"一个请求的房间只问一次" 这条对池化层的取回同样成立)。 2026-09-14 的版本让 wake 得到一个 Checkpoint,scheduler 把它插回索引、请求回到队首再按 resident 命中 restore:两次分配、两次"够不够"的判断, 没有谁把它们合起来看。DSv4.1 EP4(--chunk 128 --max-seqs 16)第二轮命中 parked 条目就 活锁——醒来的快照加半页拷贝加续写比池子多一页,Busy → make_room 能 park 的只有 刚醒的那条 → 再醒 → 再 park(一次 host session 打出 236 万行 parked tokens=86;toy-stateful 上 e2e 的 wake_room 场景 608 万行)。现在 Host::restore(&Parked, &Pool, len, tokens) 与 Pool::restore 同形:按 tokens 一次取够页,前 ceil(len/unit) 页从 host 拷进这些页里, 整页封成带 twin 的节点(再睡零拷贝),半页是 lease 自己的;runtime 的 Waking / awake 交出的是 Lease,tray 的 Rising 落地即 Row,scheduler 落地即 admit。parked 条目原样 留在索引里,请求结束时更长的上下文照常成 resident 条目。没了的东西:Host::wake、醒来 的快照进索引、scheduler 的 woken 名单、Got::Rising 里带的 key。

4. 索引:token radix tree

树的边是 token 段,节点上挂条目;树只索引,不管字节。字节的共享关系全在 store 的链上,两个条目共享哪些页由它们从哪条 lease 派生决定,树不知道也不需要知道。

这一点和 SGLang 不同(它的树节点直接持有 KV 索引,所以 split 必须在页边界,state 只能挂在页边界的节点上,页中间的 state 靠 tombstone 处理),原因是 kern 的带 state 快照落在请求结束的任意长度上,半页是快照私有的:同一 session 的下一轮从 L₁ restore (拷半页)再 retire 到 L₂,两个快照在 token 上是前缀关系、在页上不是。条目持有 store 让树可以在任意 token 位置分叉而不碰任何一页。

命中规则:沿 prompt(不含最后一个 token)走树,

  • 路径上的条目(prompt 完整覆盖它)在自己的 len 上可用,带不带 slot 都是;
  • 路径之外不带 slot 的条目在它与 prompt 共有的整页上可用:从深度 d 的节点分出去的 兄弟子树共有 d 个 token,prompt 走进一条边的中间时那棵子树共有到分叉处;每个节点 的 paged_below / resident_below 子树计数说这样的条目有没有,不用扫;
  • 取最长,同长 resident 优先。

命中触碰路径上的每个条目,根最新、叶最旧,同一条链一起老化、叶先走;evict 取的 最冷条目来自各 tier 一张按 tick 的 BTreeMap。

带 state 的条目分档(2026-10-09):带 state 的条目只服务精确续上它的 prompt,所以它们 自成一棵对话 trie。按它下面最近的带 state 条目数分三种:0 个是某个会话的最新一轮,1 个是 会话已经走过去的一轮(superseded),≥2 个是几段对话共用的前缀。腾地方先拿 superseded, 内部按 LRU——有空间时它们留着,客户端把对话改回第 k 轮还能命中;拿走它只还 slot 和 它结尾那半页,别的页是后继的前缀,留着。superseded 拿光了才轮到会话:闲得最久的会话交出 它的最新一轮。共享前缀不属于任何一个会话,下面只剩一段对话时才按那一段的身份参与。 叶先走的老规则对带 state 的链正好反了:K3 PP8 上一轮的 K/R 条目不断占 slot,链里最新 的一条反而最冷(serve.md「流水线」)。分档每次 evict 扫一遍树(只在有带 state 条目时), 树的大小是 slot 数量级。不带 slot 的 resident 条目比同路径上一个 不带 slot、只在 device 的条目深一页时替换它:纯 KV 序列每页 checkpoint 一次, 索引里只留一条会长的。

这个索引不提高命中长度。 纯 KV 模型命中仍对齐到页,带 state 模型仍只命中精确 长度(serve.md 记过:state 快照之后的 token 必须整段重跑,KV 部分命中没有算力意义)。 换掉 hash chain 换来的是:键是 token 本身,没有碰撞;Chain 不再由每条序列携带、 每 token 折叠;(depth, hash) 桶、tail 重哈希、"条目按页生长"的特殊路径都没了; 两个 session 打出同样的 token 在树上就是同一条路径。付出的是树里存 token (每 token 8 字节,相对 KV 每 token 几十 KB 可忽略;AgentX 393 个 session、ctx p50 219k 全存也不到 1 GB)和 split 逻辑。插入从根走一遍 memcmp,每页一次,摊到每步 微秒级。

树的实现:children: BTreeMap<i64, Node> 按边的第一个 token 键,确定性;条目删空 且只剩一个孩子的节点合并回去(dynamo 的 router 因为并发读不能合并,我们可以);LRU 是单调计数器(SGLang 的 tick,不是时钟)。

5. 从参考实现借了什么

来源 借 不借
Dynamo KVBM 冻结 = Arc::new(mutable),只读性从 Arc 加只有 Deref 的包装里长出来(kern 的 Node 就是这个);Drop 里迭代解链防栈溢出;registry 的值是 Weak,删除由 Drop 驱动 三个泛型参数传遍全部类型再用 dyn Any 擦回去;BlockState 是运行时枚举、每个操作都是可失败的 match;无界 channel;跨 tier 用相等的 hash 链接(我们用节点上的 twin)
Dynamo kv_router 单线程 actor;删除时合并节点;LRU 侵入节点 Rc<RefCell> 加旁路 lookup 表当真索引、split 要重写 O(后缀) 条 lookup;arena + u32 id(所有权丢了)
SGLang 页对齐是键类型的性质不是散落的算术;单调 tick;淘汰只看可淘汰的叶子,策略只打分不能 pin;lock 回执(我们用 RAII,回执就是 Arc);state 只在节点精确末端有效这一条做成类型 节点是 (component × tier) 值矩阵按下标算;panic 当错误处理;split 深拷值;cache_protected_len 把半页挂在请求上;mamba tombstone + 每次匹配重扫;为 FFI 加的 Mutex

三家都没有页中间共享。KVBM 半块直接丢;SGLang 匹配向下对齐到页、split 断言页边界; dynamo router 按 block hash。kern 的 restore 会拷半页,所以在带 state 的精确长度命中 上比它们多拿到那不足一页的部分,这是保留 exact-length 快照的理由。

6. 与之前的差异

删掉的公开项:Checkpoint::nodes()、Parked::pages(n) / slot()、 Host::park(&[(u64, i32)], page_bytes, slot, len) 的四元组签名、Park 类型、 Pool::wake / wake_slot、Prefix::resident(id) / parked(id) 的 id 查询、Chain。 留下的:Kept(tray 的 Group<X> 要靠它回答 tokens() / has_slot())、 Lease::page_ids() / Checkpoint::page_ids() / Parked::offsets()(只读观测;2026-10-09 起是 Parked::page_ids(),host 页号)。

修掉的已知问题:review 的 P1(半页 checkpoint 后 host 副本过期)由不变量消失; "醒来再睡拷第二份"由 wake 带 twin 消失;"make_room 后旧 hit 失效"由 Hit 持有 clone 消失;Host 层 page_bytes / slot_bytes 改在 Host::new 给一次,不再每次 park 传(2026-10-09 起 Host 不再知道字节,见第 2 节); 分叉在条目中间时同长的 resident 条目优先于 parked 的(之前按 id 取第一个)。

不动的部分:Pool 内部的 Denied(当时三态,2026-10-27 起 remap 删除后两态)、Lease 的表接口、runtime 的 两条流与 Waking / Room 模式、tray 级"全成或全不成"、scheduler 的快照策略。 review 的 P2(rebalance 对共享 chunk 重复计费导致误报 ExceedsPool)在 Pool 内部, 与本设计正交,单独修。

7. 门禁

一个 PR 落地(2026-09-14)。测试都在 crates/kern-pool/tests/,不用 GPU:

  • 字节级 property test(pool.rs):随机的 lease / 填写 / checkpoint / restore / fork / retire / drop 序列,每个位置由它的 lease 写上唯一戳,对着"位置 → 戳"的 参考模型比对每个句柄能看到的每个位置和 slot,池的占用等于句柄命名的页与 slot。 纯 KV 与带 state 各跑一遍。旧的 checkpoint 在这个测试上直接复现 P1。
  • park / wake property test(host.rs,随 host 层于 2026-10-27 删除)。
  • 索引 property test(prefix.rs):随机 token 序列的插入 / 查询 / 淘汰 对着"所有条目线性扫描取最长"的参考模型;同一操作序列跑两遍 trace 相同。

AgentX 回放(agentx_replay,qwen3.8-27b 形状:页 784、64 KiB/token、147 MiB slot、 130 slot 起、单卡 250 GiB、并发 32;~/bench_results/2026-09-14-pool-radix-replay/): 不带 host 命中 93.1%(与 K1b 相同);带 host 512 GiB 见 roadmap K3b 行。回放现在 按 tier 分开报命中(resident / host 各多少请求、多少 token),kern-serve 的 stats 行也加了 resident_hits / resident_hit_tokens / host_hits / host_hit_tokens, host 层有没有被打到一眼可见。

fleet 回放(agentx_fleet_replay,2026-10-27,~/bench_results/2026-10-27-mooncake-gdr/): N 个实例各自一份 Pool + Prefix、没有 host 层,请求按 --route random(不看任何 cache) 或 session(会话粘到一个实例)分发,--pool-gib 开一个全局内容寻址的 LRU 池:页 seal 时 write-through(--put-ms 后可见),admission 时本地命中之后逐 block 探池,命中的 block 取回并 在本地建索引;带 state 的模型只在会话上一轮结束处找 state 对象。问的是:路由完全不做 cache-aware、全靠池化命中,行不行。页与 slot 固定(e9a2d87 之后),4 实例、并发 128、 每实例 250 GiB、池 3 TB:

形状 路由 无池 3 TB 池(本地 / 池) 池 get 总量 get 忙秒 p99 / 峰值 GB/s
qwen3.8-27b(单实例 89.5%) random 58.9% 88.3%(21.0 / 67.4) 964 TB 59.2 / 149
qwen3.8-27b session 87.2% 91.1%(85.6 / 5.5) 78 TB 31.9 / 335
K3(页 64、27 KiB/token、447 MiB slot、131 slot;单实例 91.6%) random 70.1% 97.2%(17.4 / 79.7) 511 TB 26.5 / 64.5
K3 session 91.8% 97.1%(87.3 / 9.9) 62 TB 17.2 / 38.8

读法:池能把 random 路由拉回粘连路由 3 个点以内,put 在途竞态可以不管(put 0 ms 与 2 ms 逐字节同,在途 miss 0.00%);代价是 random 路由的 get 流量是粘连的 12 倍,qwen3.8 形状下 合 4 实例忙秒 p99 59 GB/s、每 tray 约 15 GB/s,超过实测的跨 tray RDMA(mlx5_bond_0 约 11 GB/s);K3 形状每 tray 约 6 GB/s,够。路由至少做 session 粘连,池只补跨实例的那 5–6%。 回放把每个没命中的 token 归因:K3 + 3 TB 池剩下的是 diverged 1.21%(prompt 从任何 mark 之后分叉, state 模型拿不回,这就是与纯 KV 98.6% 的差)、命中之后的尾巴 1.06%、池淘汰 0.42%、会话第一轮 与上一轮未结束 0.12%,上限约 97.6%。探池必须从新到旧试会话的每个 mark:只探最新一个时 random + 池是 90.2%,差的 7 个点全是回退 / 分叉到更老一轮的 prompt。

8. 未决

  • 带 state 的模型要不要在页边界也留 state 快照(SGLang 的 mamba_checkpoint_grid), 换取页对齐的部分命中。代价是每页一个 slot 拷贝和 slot 占用,收益要用 AgentX trace 回放算,不先做。
  • Device 的 Drop 归还走 Mutex 还是 KVBM 那样的 channel。单线程下 Mutex 永不争用, 先不改。
  • 树是否需要按 KeyNamespace(SGLang 的 extra_key / cache_salt)分片:LoRA 或多模型 共用一个池时才需要,现在没有。

9. 池化层:Mooncake Store(2026-10-27)

Mooncake Store 是 device 池之外唯一的一层:跨 tray 共享,RDMA 直接读写 GPU 内存,一个 session 的下一轮落到任意 tray 都能接上前一轮的前缀,路由不需要 cache 感知。fleet 回放 (第 7 节)说收益在哪:random 路由下 K3 形状 70.1% → 97.2%,qwen3.8 形状 58.9% → 88.3%, 池补的是跨实例的那一段。100 Gb/s 网卡上取回和重算同一量级(~/bench_results/2026-10-27-mooncake-gdr/: 跨 tray 11 GB/s,K3 约 420k token/s),所以省的是 prefill 算力,TTFT 只要求不退化。

正确性靠三条规则,其余都是展开:

  1. 池里的对象只能证实,不能信任。 探测结果只是提示;get 对每个 key 核对存储字节数等于 本地要写的字节数,任何一个不符整体算没命中。
  2. 网卡和 compute stream 不同时碰同一块内存。 Put / Get 前面排着的清零和拷贝是 stream 上的 异步操作,网卡等 Runtime::mark 的 pinned 字翻过再读写;网卡还在写的页不进任何 item; worker 线程不调 CUDA(lessons.md 2026-10-08 的死锁)。
  3. 失败只有一种结果:按 device 前缀重算。 不重试、不删对象、不给 Mooncake 提示。失败的 get 可能已经写了 slot,所以重算前把 device 快照的拷贝(或 Zero)重新排一次。

固定的决定:只有两层;池视为无限,kern 不删、不 pin、不设 TTL;快照策略同 device;每次快照 把 [0, m) 全部重 put,靠 Mooncake 去重(scheduler 不知道上一轮的页还在不在,只写新页会让 mark 盖住有洞的前缀);TP 各成员各写各的,一次决策发给全组,mark 等全组;PP head 决策, mark 等全部 stage;get 异步,没有同步版本;replicated(dealt)组不留 checkpoint,池对它关闭。

决策在 kern-pool,client 在 kern-serve

crates/kern-pool/src/pooled.rs 是纯函数:同样的 token 给同样的 key,同样的答案给同样的选择。 Mooncake client(crates/kern-serve/src/pool/mooncake.rs)只搬字节、报落地;scheduler 和 PP head 从不调 Mooncake。kern-runtime 多暴露 pooled_spans()(每个 pooled state 的地址段,注册给 RDMA)和已有的 mark()。

类型 / 函数 做什么
Chain 逐页的前缀摘要:第 k 页 = sha256(第 k−1 页 ‖ 该页 token),at(k) 是前 k 页
Keys namespace(manifest 规范 JSON、权重 header 摘要、PP 的 cut id 的 sha256)下的 page(stage, chain)、state(stage, member, chain)、mark(chain)
Probe::plan / keys / chosen 一次 batch 探什么、读回来选哪个长度
grid / snapshots 带 state 的 prompt 给池留快照的间距(state 字节的两倍折成整页)和位置(网格点加最后一个页边界)
objects 一个成员为前缀 [0, len) 要搬的对象:owner 搬页,持 slot 的搬 state
landed 成员的一组落地标志读成 token 数:带 state 全有或全无,paged-only 按页
Landing 一次传输等全组成员回报,全到齐取最小

三种对象,key 里只有 token,没有 session、没有请求 id:

对象 key 值
页 namespace,stage(PP),第 k 页末的摘要 每个 paged state 在该页的字节
state namespace,stage,成员号,页边界处的摘要 每个 per-seq state 的 slot
mark namespace,页边界处的摘要 1 字节:这个快照的全部对象都写完了

页 key 没有成员维度:页只在 owner 上,owner 按负载选,同一 session 两轮可能落在不同成员。 state 每个成员内容不同,所以有。state 只落在页边界上,key 就是那个边界的摘要,和页同一套名字: 读者不用别人告诉它快照在哪,prompt 经过的每个页边界都可以问(读路径第 2 步)。manifest 或权重改一个 字节池就冷,没有兼容层;key 格式变了 namespace 前缀跟着升(kern-pool/2,2026-10-28)。

写路径

每个快照(带 state 的在 history_tokens 之前的最后一个页边界,paged-only 的每封一页,PP head 的 keep、不带 state 的 retire,以及下面的池专用快照)生成一个 Put:owner 带 [0, m) 的整页加 slot, peer 只带 slot。带 state 的 retire 停在 prompt 末尾、不在页边界上,只留 device。

PP head 给带 state 的 prompt 另留池专用快照(snapshots):网格点(间距 grid:state 字节的 两倍折成整页,K3 bf16 是八段合计 469 MB 的 state 对每 token 27.6 KB 的 KV,33,920 token)和 prompt 最后 一个页边界(有 history_tokens 时就是 keep 本身)。行在这些点停一下,Cache::snapshot 拷一份 slot、 不进前缀树,put 落地、mark 写完就放掉;没有空 slot 就像 keep 一样淘汰一个 device 条目腾地方(池比任何 device 条目留得久),无可淘汰才跳过。只用空 slot 时,device 条目两分钟内占满全部 slot,之后每个池专用 快照都被跳过、池里不再有新 state,device 条目一被淘汰下一轮就整段重算(2026-10-28 K3 回放:172k 的 prompt 命中 0,serve.md「K3 PP8 命中对账」)。冷 prefill 因此每隔 一个网格留一个可以续的点,一个 lane 首次进入后的下一轮即使在 keep 之前分叉,也只退到最近的网格点, 而不是从头算(2026-10-28 nvlink c64 预热里 677k 的 req-160 整段重算就是这个)。state 字节约是这段 KV 的一半,只在冷的那段付。executor 在 Put 前记 stream mark,worker 等它翻过再 batch put(已存在的 key 只有元数据来回)。 scheduler 持 Snapshot / Checkpoint 的 clone 到落地,传输中页不会被回收。全组落地后 owner 写 mark;任一成员失败就不写、放掉 clone、计数。paged-only 的页对象就是自己的 mark。

读路径

admit 之后请求经过两次异步往返才开始 prefill:先探,再取。两次都不堵 scheduler。

  1. lease 从 device_hit 起,持 device 快照的 clone(否则这几百毫秒里 make_room 可能把它淘汰, 失败后重拷的源页已经租给别人)。
  2. Probe::plan:device_hit 之后、最后一个 token 之前的每页的 key(PP 下每页每 stage 一个), 带 state 的再加每个页边界上的 mark(新到旧)。不靠前端:任何实例在 prompt 经过的任何页边界留的 快照都问得到(之前只探前端 history_marks 给的最近几轮,fleet 回放:只探最新一个少 7 个点)。 PP 8 段下每页 9 个 key,比只探页多 1/8。一个 batch exist,每个存在的 key 得 10 秒读租约,这是 老页唯一的续命途径。
  3. Probe::chosen:带 state 选最新的、其下每页都在的 mark;paged-only 取最长连续段。没有可用的 就按 device_hit 开跑。
  4. Get:owner 取页加 slot,peer 取 slot,同样等 stream mark。每个成员回报落地的 token 数(landed),Landing 取最小:带 state 要求全员完整,paged-only 取最小作命中长度。
  5. 落地:Row::filled(got) / Lease::filled(got),从 got 开跑,落地的前缀在 device 池里也建 checkpoint(不再 put,池里已有)。失败:重排 device 快照的拷贝或 Zero,从 device_hit 开跑。

Probing / Fetching 的请求持有 lease,计入行数上限;abort 只打标记,lease 到落地才释放,否则 网卡会写进已经租给别人的页。

TP、PP 与 DP

决策相同,差别只在 act 怎么到达、谁回报。TP:一次决策生成一组 act,随 Order 到各 rank, Answer.landed 回报。PP:head 自己的 client 当 stage 0;Probe 只由 head 发(key 已含每个 stage);Put / Get 作为 Job::Acts 跟在 cache 的拷贝 act 后面发给每个 stage,每个 stage 的 client 答 Report::Landed,head 按 stage 计 Landing;没有那种 state 的 stage 对象为空,立即 落地。head 在 stage 1 取走 item 之前听到的落地推迟到本 turn 之后(落地要 admit,admit 在 turn 之间)。DP(prefill tier, dp.rs,DSV4.1 Flash 的生产形状):每个 rank 自己的池和前缀树,act 走该 rank 的 Order, 没东西喂而有 act 在外时也发一个只带 act 的 order 收答案;带 state 的快照在 history_tokens 之前的 最后一个页边界随 prefill 取一次、put 完就放掉(一个 rank 只有 57 个 slot,device 仍只留 prompt 末尾的 条目),paged-only 的在 retire 时 put 整条链。

失败模式

情形 结果
put 中途进程挂或断网 mark 没写,读者探不到;残页由池淘汰
mark 写后某页被淘汰 get 核对字节数失败,按 device 前缀重算
两个实例同时 put 同一 key,一个在 PutEnd 前崩溃 另一个收到"成功"但对象不完整;读者 get 失败
get 部分成员失败 整体失败;重排 device 拷贝后从 device_hit prefill
10 秒租约内没传完 返回错误,按失败处理
master 不可达 探测失败,--pool-cooldown 内全部直接 miss,decode 不受影响

The disk tier (--pool-ssd, 2026-11-09)

Some machines keep the pooled tier on their own NVMe instead of Mooncake: one rank, one GPU, one file. The decisions above do not change (the same keys, the same Act::{Probe, Put, Get, Mark}, the same three rules); only the store does. pool::Client is an enum over the two stores, and the scheduler cannot tell them apart.

  • Accounting is pure (kern-pool: Ring, Arena, Disk). Ring places objects in one file used as a ring: logical positions only grow, an object never straddles the end, the tail is one capacity behind the head, and eviction is first in, first out. A placement is two-phase (place, then commit once the write landed), and a placement that would lap a running write is refused, so two writes never share a byte. Arena hands out rooms of the pinned block (first fit); puts and gets each have half of it, so a write backlog never leaves a fetch without room. Disk turns one act into a Plan: a put takes its room before it places, so a full block never evicts a live object; a key written or being written moves nothing; a get stops at the first object the file does not hold at exactly its size, because a fetch lands a leading run or nothing.
  • The shell moves bytes (kern-serve/src/pool/ssd.rs). The disk reaches no device memory, so every byte passes through a pinned block, copied on the compute stream (Runtime::copy_bytes, one cuMemcpyBatchAsync per act). A put copies device → room behind everything issued so far and marks the stream; the write thread waits for the mark, then writes. The put is answered once the stream passed that mark, not once the disk wrote it: the scheduler holds a put's pages until it lands, so answering at the write would hold prefill to the disk's write speed (a 16k-token prompt behind 4.5 GiB of filler puts waited 2.6 s for its pages on a 1.7 GiB/s RAID5). Answered early, the backlog is bounded by the block's put half and a put it cannot stage is refused (pool_put_fails). Rule 1 covers the rest: an object is found only once written, a mark that precedes its pages makes the probe choose an older snapshot, and a state not yet written fails the get and recomputes. A get is read into rooms by the read thread; the next issue() on the device thread copies them into the lease and answers the get at once, since that copy is in stream order ahead of anything the scheduler issues after hearing it landed. Neither disk thread calls CUDA (rule 2).
  • Reads are checked after they land (rule 1): an extent is believed only if the tail has not passed it, since anything that overwrote it was placed (and moved the tail) first.
  • io_uring with O_DIRECT, one ring per thread, 2 MiB chunks, 64 in flight. Each thread drains everything queued as one batch, so a stream of one-page puts still keeps every member of a RAID busy, and the write thread waits only for the batch's last mark.
  • Nothing outlives the process: the file has no name (O_TMPFILE), is reserved whole at start (fallocate, so a short disk fails there), and a restart starts cold. The tier is a cache.
  • Refused with more than one rank or in a pipeline (Config::admits): the scheduler asks rank 0 alone whether the tier holds a prompt, which only holds when every rank shares the store.

门禁

  • crates/kern-pool/tests/pooled.rs:摘要链对前缀单调、key 随 kind / stage / member / namespace 各异;Probe 对随机 unit / hit / 存在集与穷举模型一致;snapshots 对随机 unit / grid / 区间与 穷举模型一致;objects / landed 对随机组与模型一致,不在页边界的 state 拒绝入池;Landing 对任意到达顺序结论相同、重复成员报错。全绿。
  • crates/kern-serve/tests/pool.rs:fake executor 上的两个实例共一个 fake 池,答案延后 0–2 步、 随机丢 act:一个实例留下的轮次被另一个实例取回(没有前端告诉它上一轮在哪)、第二次 prefill 从 history 之前的页边界起;40 种子下丢 act 的池对客户端看到的输出没有影响。全绿。 pp/cache.rs 的单测:池专用快照不进前缀树、放掉就还 slot、没有空 slot 时跳过而不淘汰。
  • e2e 2026-10-27 过(serve.md「池化 KV 层」,~/bench_results/2026-10-27-pooled-kv-e2e/):一个会话四轮 交替打两个实例,paged-only 单卡、带 state 跨 tray、PP 2 段三条路径,每轮回复与池外冷实例逐字相同,第二轮起 每轮命中池;B 命中的 token 数等于上一轮的 history_tokens。杀 master 的退化路径与生产形状未跑。