[TokenSpeed 源码解读] 调度与缓存 FSM

解读 TokenSpeed 的 C++ 调度器:类型化请求状态、统一 prefill/decode 路径、多组 KV Cache、admission 与 retraction。

src/pages/articles/_md/AI/Infra/Inference/TokenSpeed/CodeWiki/main-2026-11/02-scheduler-cache-fsm.md

← 返回概览


模块定位

tokenspeed-scheduler/csrc/ 是 TokenSpeed 的正确性核心。它回答“一轮该执行谁”之前,先回答更难的问题:请求此刻拥有哪些 page、request-pool slot、storage lease 和尚未落地的 forward;发生 prefix hit、PD transfer、容量不足或取消时,这些资源应该移动到哪个状态。

TokenSpeed 没把状态表示成一个 enum 加若干全局 map,而是让 fsm::State 的每个 variant 直接持有它合法拥有的资源。事件处理通过 move 构造下一个状态,RAII handle 的析构负责释放。这使“忘记在异常分支归还 block”从运行期隐患变成结构上更难发生的错误。

模块架构

C++ Scheduler、FSM 与 CacheCoordinator 的静态关系
C++ Scheduler、FSM 与 CacheCoordinator 的静态关系

Scheduler 持有 Request 集合、CacheCoordinator、request slot allocator 和配置;每个 Request 持有一个 std::variant 状态。CacheCoordinator 再把统一 prefix boundary 投影到 Full、SlidingWindow、State 多个 cache group,共享底层 BlockPool,并同时管理 Device、Host L2、snapshot pool 与可选 L3 ticket。

这套结构把“调度策略”和“资源事实”分开:operations/forward.cpp 决定 prefill/decode/retraction 的候选顺序,coordinator 负责探测、分配、pin、copy-on-write 与 eviction;最终二者汇总成值语义 ExecutionPlan。

调用链路

Scheduler 从反馈到 ExecutionPlan 的调用链
Scheduler 从反馈到 ExecutionPlan 的调用链

每轮开始先通过 Advance() / advance_head() 把 forward、cache 和 storage 结果应用到 FSM。NextExecutionPlan() 再收集候选,按 engine role 构建 prefill、decode 或 fused operations;admission 通过 cache matcher 查可恢复 boundary,申请 block table 与 slot;容量不足时选择 victim 做 retraction 或 capacity abort;最后 plan 同时携带 forward、cache copies/zero、remote streams、storage ops 和 aborts。

方法速查表
方法 一行职责 关键设计决策
Scheduler::SubmitRequests() 批量验证并创建请求 全批先验证,避免半提交
Scheduler::NextExecutionPlan() 生成一轮完整 plan forward/cache/PD/storage 都是一等操作
Scheduler::Advance() 应用 forward/PD 事件 统一状态变更入口
Scheduler::admit() 申请 cache 与 slot 先匹配真实 prefix,再分配资源
Scheduler::schedulePrefill() 生成 prefill chunk chunk、replay、State checkpoint 统一处理
Scheduler::scheduleDecode() 生成 decode/verify speculation 只是同一路径的参数
Scheduler::retractVictim() 保存并释放受压请求 tail image + slot state 由 RAII 绑定
CacheCoordinator::Probe() 多组 cache 联合匹配 boundary 必须同时满足各组语义

核心实现

State variant 把非法资源组合排除在外

状态集合在 states.h 中显式列出:

using State = std::variant<
    Bootstrapping, Submitted, Prefetching, Prefilling,
    RemotePrefilling, PrefillAwaitingResult, PrefillDone,
    Decoding, PdTransferring, Retracted, Restoring,
    Finishing, Finished>;

Submitted 只持有 AdmissionResources,没有 Device page;能执行 forward 的状态持有 ForwardResources。后者把 ReqPoolIndex、多组 BlockTable、CacheProgress 与 results_in_flight 绑在一起。retraction 必须整体 move 这组资源,不能只释放 page 却留下仍会写入旧 page 的 in-flight forward。

多组 cache 共享 boundary,不共享语义

CacheGroupConfig::AttnKind 只有三类:

enum class AttnKind { kFull, kSlidingWindow, kState };
  • kFull 保存 prefix-closed token history。
  • kSlidingWindow 只要求 boundary 前的尾窗仍存在。
  • kState 保存完整 recurrent state,没有 token row span,block table 是 input/live 两个 slot。

调度器用 prefix granularity 表示可复用身份边界,但每组再用自己的 block_granularity、window 或 checkpoint granularity 解释该边界。这样 GQA KV、SWA、Mamba/KDA 状态可以参与同一次 admission,而不需要把 State 伪装成 token page。

统一路径不是“所有情况完全相同”

buildPrefillWorkerPlan()、buildDecodeWorkerPlan() 和 buildFusedPlan() 最终都填充同一个 ExecutionPlan;PD remote stream、L2 write-back、L3 query 和 ordinary forward 也都在 plan 中并列。统一路径的含义是共享 admission、资源 fence 和反馈协议,而不是拒绝不同 operation。由此 speculation、CUDA Graph、PD 与非 PD 都不会复制一套请求生命周期。

retraction 保存的是可恢复状态,不只是 token

容量压力下,scheduler 先判断 victim 是否仍有 in-flight result、是否已持有足够 generation reserve,并计算 snapshot/Host shortfall。可恢复 victim 的 hash-complete pages 可写回 L2,tail pages 和 slot-sized tensors 进入 snapshot pool;Retracted 状态不持有 Device block,之后 Restoring 重新获得 slot 和 page。若 snapshot pool 关闭或无法容纳,调度器走明确的 capacity abort,而不是悄悄丢状态后重算。

Prefix 命中必须重新验证

L3 query 或 Ready hold 只能提供候选,ordinary admission 仍重新调用 matcher。QUERY 与 GET 之间的 eviction 可能缩短命中,但绝不能凭一个远端“存在”结果制造本地 hit。这个反直觉的重复工作换来一个重要性质:唯一可信事实始终是 coordinator 此刻持有并 pin 成功的 block refs。

设计模式

模式 位置 为什么用
Type State fsm::State 让每个阶段只拥有合法资源
RAII CacheBlockRef、ReqPoolIndex、StorageLease 状态销毁即释放,异常路径无需手工配对
Event Sourcing forward_events.h、outside_event_handler.cpp 状态只由已发生的外部事实推进
Command ExecutionPlan planner 与 executor 解耦
Strategy Full/SWA/State group matcher 不同 cache 语义共享 coordinator 流程

模块间交互

Rust control plane 调用 scheduler bridge 的 next_execution_plan()、advance() 与统计接口;Python data plane 消费 plan,却不能直接拿 Request 或改变 state。Attention cache recipe 在启动时发布 CacheGroupConfig 与物理 page counts;scheduler 只看到逻辑 group contract,不读取 tensor shape、stride 或 backend 名称。

扩展方式

新增 cache family 时,优先把它归入 Full、SlidingWindow 或 State,并在 Python recipe 发布真实 block_granularity/retention/transfer policy;只有现有三种语义无法表达时才扩大 C++ contract。新增调度事件要同时补状态可达性、资源移动和失败测试,重点检查 early return 后 RAII owner 是否仍唯一。