ExecuTorch端侧推理教程 · 08-批处理调度与服务化

08 - 批处理调度与服务化:batching、ServingRuntime 与 llm_server

所属系列:ExecuTorch 端侧推理教程 | 前置:07-LLM端侧推理链路 | 下一篇:09-构建体系与进阶专题
证据基线:commit 8c3f75df(version.txt = 1.6.0)。本章所有 文件:行号 均在本 checkout 实测。

本篇知识图谱

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
29
30
31
32
33
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((批处理调度与服务化))
调度层
DecodeFirstScheduler
decode 优先预算
prefill 轮转取块
每 session 一占
工厂防异常构造
引擎线程
RunnerImpl
control_mutex 预留
get_work 到 execute
20ms 条件等待
drain 与退役
执行层
ModuleExecutor
pack 成 PackedStep
max_step_tokens 切片
单条 module execute
逐行 sample
批量 KV
Cache BatchControl face
CellCache 单元池
seq_new seq_clone rewind
declare_step 申报
cache_key BackendOptions
服务层
ServingRuntime 异步 API
control 与 delivery 线程
事件回调合同
llm_server OpenAI 端点
JSONL 驱动 C++ worker

本篇目标

  1. 理解 DecodeFirstScheduler 的策略:decode 优先占预算、prefill 轮转取块、每 session 每批只占一格。
  2. 看清引擎线程闭环:RunnerImpl 持 control_mutex_ 预留工作(get_work),交 ModuleExecutor 组批执行。
  3. 拆解 ModuleExecutor 四步:pack → 按 max_step_tokens 切片 → 单条 module_->execute → 逐行采样。
  4. 理解批量 KV 的 Cache/BatchControl face 设计与 cache_key 会合机制;上层 ServingRuntime 与 OpenAI 兼容 llm_server。

1. 分层地图:从单流到服务

第 07 章是单会话单流。服务化栈自下而上四层(目录 ls 实测 extension/llm/batching/:scheduler.h、decode_first_scheduler.h、executor.h、module_executor.、runner.、prefix_cache.h):

1
2
3
4
5
ServingRuntime(serving/,会话生命周期+事件回调)
└ RunnerImpl 引擎线程(batching/runner.cpp,control_mutex_ 编排)
└ DecodeFirstScheduler(调度决策:本批装什么)
└ ModuleExecutor(执行:pack→切片→execute→采样)
└ CellCache(批量 KV:seq_new/seq_clone/rewind)

llm_server 示例再把 ServingRuntime 包成 HTTP 服务。每层只依赖下一层的窄接口。

2. DecodeFirstScheduler:decode 优先 + prefill 轮转

extension/llm/batching/decode_first_scheduler.h:43(Observed in source):

  • 预算三参数(create 工厂 :56-73):max_batch_tokens=544、max_decode_sequences=32、max_prefill_chunk_size=256。校验注释(:45-50)写明底线逻辑:“budget must cover a saturated decode batch plus one full chunk”——预算装不下「满 decode 批 + 一个 prefill 块」就直接拒绝创建,否则任务会被收录后永远排不进批,stranding(搁浅)而非延迟。工厂而非 throwing 构造,因为 size 优化构建 -fno-exceptions(:52-55);
  • get_work 的顺序即策略(:105-121):先 take_decodes_(:116)——所有已就绪 decode 先花预算(注释 :103-104 “Spending accumulates instead of counting a budget down”);再 while (spent < max_batch_tokens_ && take_prefill_pass_(...))(:117-119)——prefill 按轮转逐块填余量;
  • 每 session 每批一占(:109-114):局部 decoding set 保证「a session’s second decode, or a prefill chunk beside its decode, waits for the next batch」——一个 session 在一个批里要么一个 decode 要么一个 prefill 块,_executor 得到连续区间与确定的 produce_output 语义;
  • submit(:77-96)在锁内做 admissible 检查 + 同一 submit 向量内 tid 去重(:86-90)。

3. 引擎线程:control_mutex 下的预留与执行

引擎线程本体在 extension/llm/batching/runner.cpp 的 RunnerImpl(control_mutex_ 成员 :552)。主循环 run_()(:766-804,Observed in source):

1
2
3
4
5
6
7
8
while (is_running_()) {
process_pending_commands_(); // :794
reap_cancelled_(); // :795
if (execute_one_batch_()) continue; // :796
std::unique_lock lock(control_mutex_); // :799
engine_cv_.wait_for(lock, 20ms, []{ // :800-803
return 生命周期变化 || !inbox_.empty() || scheduler_->has_work(); });
}

execute_one_batch_(:1028 起)开头就是持 control_mutex_ 预留工作(:1032-1037):锁内校验 lifecycle 后 tasks = scheduler_->get_work()——预留与 stop 转换有全序(注释 “Work reservation and the stop transition have a total order” :1031)。随后组批统计(注释解释 DecodeFirstScheduler 的轮转会让两个 prefill 交错成 A,B,A,B,:1041-1053),交给 executor 执行。关闭路径 shutdown()(:708-754)同样全程持 control_mutex_ 并处理「engine 线程不能 join 自己」(:730-734)等边角。

4. ModuleExecutor:pack → 切片 → 单条 execute → 逐行采样

ModuleExecutor::execute(batch, out)(extension/llm/batching/module_executor.cpp:310-409,Observed in source)四步:

  1. pack:sessions_.pack(batch)(:314)把多会话输入压成一个 PackedStep(tokens/positions/seq_ids/logit_indices);
  2. 切片:按 max_step_tokens_ 循环 for (off = 0; off < total; off += max_step_tokens_)(:322-324)——注释(:319-321)给出正确性论证:“They go in order, so a slice attends the cells its predecessors wrote, and each input’s logits row falls in exactly one of them”(顺序执行,前片写的 KV 后片可见,每行 logits 恰属一片)。每片先向 cache 申报 ctl_->declare_step(seq_ids 切片)(:327-331,拒绝即 “the cache refused a slice of %d”);
  3. 单条 execute:组 [1, n] tokens + [n] positions 张量(:332-339),LogitsToKeepMode::Selected 时附加 selector(:341-353),然后一条 module_->execute(method_, {...})(:352/:354)跑整个切片——模型内 KV 操作天然并行处理多序列;
  4. 逐行采样:logits 形状校验(:369-380)后按行 sessions_.sample(session, logits, row)(:387/:401)——Selected 模式按 selector 映射回 input 索引(:382-392),普通模式按 step->logit_indices[i] 跳过「另一片的行或被丢弃块的预测」(:395-398)。

采样本身复用第 07 章 host CPU Sampler——服务化没有把采样搬进图。

5. 批量 KV:Cache/BatchControl face 与缓存键会合

5.1 CellCache:一 cache 三 face

extension/llm/cache/cell_cache.h:61-63(Observed in source):class CellCache : public Cache, public BatchControl, public CellStepper——一个实现暴露三个能力面,face() 用 expose<BatchControl, CellStepper>(this, id) 按需揭示(:110-112),face 名如 "et.cache.CellStepper"(:54)。接口分组:

  • CacheControl:capacity() / clear()(:74-75);
  • BatchControl:declare_step(seq_ids)(:79)、max_seqs()(:81,上限 kMaxSeqs = 64,owner bitset 一 seq 一位 :66)、seq_new()(:82)/ seq_clone(src, upto)(:83-84)/ seq_rm(:85)/ rewind(seq_id, position)(:88) / pos()(:89)——单元池的会话操作原语;rewind 注释保证窗口层收窄 mask 不丢位置(:86-87);
  • CellStepper:place_step(layer, positions, length)(:96-97)——把一步的位置集合交给字节层;
  • 前向结果钩子:end_step()(:103,成功后关闭 placed step,下次 forward 需重新 declare)/ abandon_step()(:107,失败时「each of its sequences drops back to its first position in the step, giving back the cells the step claimed」)。

ModuleExecutor 的 declare_step(:327)与切片循环正是这个 face 的消费者。

5.2 缓存键会合:cache_key 经 BackendOptions 绑定

AOT 侧与运行时侧怎么找到同一个 cache 实例?extension/llm/cache/cache_registry.h 三处注释(Observed in source):两侧 “rendezvous on a cache_key passed as a runtime backend-load option”(:14);“Process-global map<cache_key, shared_ptr>”(:44);set_option(BackendOptions<N>& options) 负责 “Adds the complete cache rendezvous option. BackendOptions copies the key…”(:130-133)。

即:宿主在 load_method 时把 cache_key 塞进 BackendOptions(第 06 章 interface.h:121-141 的 set_option 通道),图内 kvcache::update_and_attend(第 07 章 update_and_attend.py:61 的进程级 REGISTRY)按 key 会合到同一 cache——多会话共享一个图、各自挂自己的 KV。

6. ServingRuntime 与 llm_server

6.1 ServingRuntime:异步会话 + 事件回调

extension/llm/serving/serving_runtime.h:123(Observed in source)。构造即契约:Owns one Runner 与 scheduler,“Initialization happens on the engine thread”(:127),配置非法则 inert——无线程、ready=false(:128-130)。配置面(ServingRuntimeConfig :43-108):max_sessions、max_requests=8、max_pending_operations=64、max_events_per_request=16、max_tokens_per_request=256、前缀缓存(prefix_cache_capacity/checkpoint,:65-94)。

API 全异步(:173-195):open_session_async / close_session_async / reset_session_async,两种完成形态——回调 LifecycleCallback(:113)或 std::future。回调合同(:154-166):“callbacks run once on control”——生命周期回调跑在 control 线程、无 runtime 锁、可与提交返回竞争;token 交付走 “shared delivery thread”(:166 “A blocked sink still stalls the shared delivery thread”——sink 卡住会拖住共享交付线程,这是背压的显式代价)。加上执行侧 engine 线程(:127),服务化栈至少三条线程各司其职:engine 执行、control 编排回调、delivery 交付 sink。会话语义细节也写死在注释里:close 是 RAII(:178)、reset 幂等且销旧建新(:187-195)、生成可复用全 prompt 匹配的共享快照(:172)。

6.2 llm_server:OpenAI 兼容端点 + JSONL worker

examples/llm_server/python/server.py 的定位写在文件头(:14-19,Observed in source):“Model execution lives in a separate C++ worker process driven over JSONL via WorkerClient”、“One worker process: explicit multiplexing permits bounded concurrent requests… Extra worker processes would duplicate weights, so --num-runners accepts 1”——Python 只做协议与编排,模型跑在独立 C++ worker 进程,权重只驻一份;本地 _spawn(server.py:53-67,:60 用 args.worker_bin 组命令,经 worker_client.spawn_worker 拉起)启动 --worker-bin 指定的 worker 二进制。

OpenAI 兼容面(:343-401):/health(:343)、/v1/models(:349,ModelCard 带 context_length)、/v1/chat/completions(:360-378)——标准 OpenAI 请求体 + ExecuTorch 会话扩展 header(x_executorch_session_id/session_id/x_session_affinity,:366-370);再加 vendor extension 会话管理 /v1/sessions/{id} DELETE(:380-399)与 /reset(:401+)。JSONL 协议细节在 protocol.py 与 worker_client.py/multiplexed_worker_client.py(目录 ls 实测),多路复用客户端支撑 :17 说的有界并发。

本篇小结

  • 调度策略(decode_first_scheduler.h:43-121):decode 先花预算、prefill 轮转填余量、每 session 每批一占;预算底线校验在 create 工厂里,防「收录即搁浅」。
  • 引擎线程(batching/runner.cpp):control_mutex_ 下 get_work 预留(:1032-1039)与 stop 全序化;主循环 20ms 条件等待(:799-803)。
  • ModuleExecutor(module_executor.cpp:310-409):pack → max_step_tokens 切片(顺序片间 KV 可见 :319-321)→ 单条 module_->execute(:352)→ 逐行 sessions_.sample(:387/:401)。
  • 批量 KV:CellCache 三 face(cell_cache.h:61-63)暴露 seq_new/seq_clone/rewind/declare_step;AOT 与运行时靠 cache_key 在 BackendOptions(load_method 时)会合(cache_registry.h:14/:44/:130-133)。
  • 服务层:ServingRuntime 全异步会话 API + control/delivery/engine 线程分工(serving_runtime.h:123-195);llm_server 用 JSONL 驱动单份权重的 C++ worker(server.py:14-19),对外提供 OpenAI 兼容 /v1/chat/completions 与 vendor 会话扩展(:343-401)。

前置:07-LLM端侧推理链路 | 下一篇:09-构建体系与进阶专题 | 回目录