SGLang推理服务教程 · 04-Scheduler调度与前向执行
04 - Scheduler 调度与前向执行:一个 batch 的完整旅程
所属系列:SGLang 推理服务教程 | 前置:03-双入口与三进程流水线 | 下一篇:05-KVCache内存池与RadixCache
证据基线:commit69028290,全部为静态源码走读。本章主战场:srt/managers/scheduler.py、srt/managers/schedule_policy.py、srt/managers/tp_worker.py、srt/model_executor/model_runner.py、srt/layers/sampler.py。本系列灵魂章。
本篇知识图谱
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇目标
- 把一个 batch 的七站旅程走完:事件循环 → 准入 → 预算 → 保活 → 折叠执行 → 采样同步 → 结果流回。
- 记住调度铁律「先 prefill 后 decode」的代码位置与理由。
- 理解 retract_decode 的取舍:牺牲 prefill 进度,保 decode 批活着。
- 分清前向的三条执行路径与采样器的 TP 同步点。
1. 旅程总览
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
2. 第一站:事件循环与四种变体(scheduler.py:2221-2326、:7107-7120)
normal 循环(event_loop_normal,scheduler.py:2221-2253)每轮五步:ingest_requests()(:2229)→ get_next_batch_to_run 返回 plan(:2235-2239,running_batch 与 batch_to_run 二元组)→ 有批则 run_batch + process_batch_result(:2243-2245)→ 空转则 on_idle()(:2247-2249)→ last_batch = batch + 不变量检查(:2252-2253)。
overlap 循环(event_loop_overlap,:2256-2326)是默认主力:维护 result_queue 双端队列(:2259-2261),本步 run_batch 的结果只入队(:2305,注释:用 WAR barrier 隔离本前向的共享读 :2304),上一步的结果才被 pop_and_process(:2263-2266)——CPU 后处理与 GPU 前向错开一代;某些条件下提前处理(:2279-2290,还顺带做统一内存的机会性 flush :2289-2290);本步的采样可以推迟到上一步结果处理完再发(launch_batch_sample_if_needed :2321,注释说明它依赖上一步结果如 grammar :2319)。
变体分派在 _dispatch_event_loop_once(:7107-7120):非分离模式下按序选择 pp_size>1 → event_loop_pp(:7114)、enable_overlap_mlx → overlap_mlx(:7116)、enable_overlap → overlap(:7118)、否则 normal(:7120);PD 分离模式下 prefill/decode 角色各有专属循环(:7121 起)。注释还提示 PD 角色切换可在同一 scheduler 上换循环(:7108)。
3. 第二站:ingest 与「先 prefill 后 decode」(scheduler.py:2359、:4374-4501)
ingest_requests(:2359)把 ZMQ 收到的请求搬进 waiting queue。真正的调度决策在 get_next_batch_to_run(:4374-4501):
- 收尾上一步的 extend 批:chunked 请求先 stash(:4390-4398);上一个 prefill 批过滤掉已完成请求后 merge 进 running_batch(:4413-4446)——prefill 完的请求就地转为 decode 成员。
- 每步都 filter_batch(:4448-4453,注释:overlap 下 prefill 的合并在其结果前发生,
update_running_batch可能轮空)。 - 先 prefill:
get_new_batch_prefill(:4461-4463)尝试组新 prefill 批;有新批就直接跑——「Run prefill first if possible」(:4478-4480)。 - 否则 decode:running 批非空时
update_running_batch(running_batch)(:4482-4489)。
这个顺序的含义:只要有新 prefill 可组,decode 就让一步——GPU 上的 decode 每步只有 1 token 的工作量,让给大算量的 prefill 是吞吐最优解,代价是 decode 稍有停顿(PD 分离就是把这个取舍拆到两台机器上)。
4. 第三站:策略族与 PrefillAdder 预算准入(schedule_policy.py:188-204、:1077、:1139-1143)
准入策略分两族(schedule_policy.py:188-204):CacheAwarePolicy(LPM 最长前缀匹配、DFS_WEIGHT、HRRN、SHORTEST_PREFILL_FIRST、UNIBOOST,:191-195)与 CacheAgnosticPolicy(FCFS、LOF、RANDOM、ROUTING_KEY,:201-204)——前者看 RadixCache 里能复用多少前缀(05 章的主角),后者不看。
PrefillAdder(:1077 起)是准入的执行者,构造时领三本预算账:rem_input_tokens(减去混合 decode 的占用,:1118)、rem_chunk_tokens(chunked prefill 的每步 token 上限,:1119、:1137-1138)、memory_budget = create_prefill_budget(allocator, tree_cache, ...)(:1139-1143)——KV 可用页数是硬约束。准入结果进 can_run_list(:1146)。它还有一批精细开关(Mamba chunk 网格 :1104-1106、页对齐 chunk 结尾 :1122-1132),本章只记账,05 章讲页时再回收。
5. 第四站:KV 不足时抽回保活——update_running_batch/retract_decode(scheduler.py:5249-5337)
decode 批每步先过 update_running_batch(:5249-5338):
- 剔除在飞行中结束的请求(:5253-5254);
check_decode_mem()不通过即kv_full_retract_flag(:5262)——decode 步要为每个请求再写 1 token 的 KV,写不下就必须腾;- 抽回:
batch.retract_decode(self.request_retirer)(:5284-5286,本体在schedule_batch.py:3018),拿回可用 token 数与 new_token_ratio(:5287-5288),更新比率追踪器(:5306),被抽回的请求带 is_retracted=True 回 waiting queue 重排队(:5325-5326)——它们已算出的 prefill KV 部分作废,下次从头来;日志直接打 “KV cache pool is full. Retract requests”(:5311-5323); - KV 够用时只做比率衰减(:5328);最后
prepare_for_decode(:5337)备好张量。
语义:retract 是 decode 的保命机制——与其让整个 decode 批 OOM 崩溃,不如退几个请求出去。new_token_ratio 随之变化(抽回后调高、平稳期衰减),间接控制后续 prefill 准入的激进程度(§4 的 new_token_ratio 参数即由此而来)。
6. 第五站:run_batch 折叠与三条执行路径(tp_worker.py:624-773、model_runner.py:2141-2193)
run_batch(scheduler.py:5442)把批交给 model_worker.forward_batch_generation(:5527 调用点)。forward_batch_generation(tp_worker.py:624-773)内部分两步:
- 折叠:
ForwardBatch.init_new(batch, self.model_runner, ...)(:657-664)——把带策略语义的ScheduleBatch(请求对象、树缓存引用、预算账)折叠成纯张量视图的ForwardBatch,这是「调度层 → 执行层」的接口面。 - 执行与采样:末 rank 调
model_runner.forward(:689-692),结果装进GenerationBatchResult(logits_output、can_run_cuda_graph 等,:709-727);两种采样时机——overlap 且有 grammar(或SGLANG_ENABLE_DELAY_SAMPLE)时挂delay_sample_func延后采样(:745-767),否则当场model_runner.sample(:769-773)。
model_runner.forward 在三条路径中择一(model_runner.py:2141-2193):
| 路径 | 条件 | 位置 |
|---|---|---|
| decode CUDA graph 回放 | can_run_graph(decode 形状命中已捕获图) |
:2141-2146 |
| prefill piecewise graph | extend 批且 prefill_cuda_graph_runner.can_run_graph 通过(:2164-2173 的一系列守卫),:2174 注释即 “Prefill cuda graph (piecewise)” |
:2164-2188 |
| eager 兜底 | 其余(decode/extend/idle 在 runner 内分发,:2190) | :2189-2193 |
细节:decode graph 命中时提前返回(:2146),跳过 :2154 的 eager 前置准备(注释解释它做 DP padding 与 attn-tp 归一化,:2148-2153)。
7. 第六站:Sampler 融合采样与 TP 同步(layers/sampler.py:120、:300、:364-409)
Sampler(layers/sampler.py:120)初始化时就定下同步组:tp_sync_group = tp_group.device_group(:123),开 DP attention 时换 attn_tp_group(:125-126)——TP 切分下每个 rank 只算部分 logits,采样结果必须全 rank 一致。前向(:280 起标准路径)里两处融合:
- 融合 softmax:
sampler_softmax(logits, sampling_info.temperatures, out=logits)(:297-300,注释 “Temperature fused; the probs overwrite the logits in place”——温度缩放与 softmax 融成一次 kernel,原地覆盖)。 - top-k/top-p renorm:torch 后端依次
top_p_renorm_prob(probs, sampling_info.top_ps)、top_k_renorm_prob(probs, sampling_info.top_ks)(:413-414);flashinfer 后端把二者传给融合算子(:442-443)。
_sample_from_probs(:364-409)分简单/复杂两案:简单贪心或纯多项式直采(:385-390),复杂案带 top-k/top-p/min-p(docstring :374);带种子的采样强制走 pytorch 后端,因为 FlashInfer 的种子绑定 batch 槽位、会破坏确定性(:405-408)。最后跨 TP 同步:self._sync_token_ids_across_tp(batch_next_token_ids, sampling_info)(:334-336,前后都有 e2e trace 打点)。
8. 第七站:process_batch_result 与流回(scheduler.py:5932-5986)
process_batch_result(:5932-5986)按 forward_mode 分派:decode → process_batch_result_decode(:5957),extend → prefill 处理(PD prefill 有专属分支 :5961-5962),idle → idle 处理(:5973-5974);顺带发布负载快照给路由层(:5947-5954)。逐请求的输出经 OutputStreamer(srt/managers/scheduler_components/output_streamer.py,持有 send_to_detokenizer: zmq.Socket :92)的 stream_output(:233)推给 DetokenizerManager(:353/:436)——03 章 §4-§6 的解码回填与 SSE 产出正是这条边的续篇。overlap 模式下这一切发生在 GPU 跑下一批的同时(§2 的 result_queue),这就是流水线的意义。
本篇小结
- 七站旅程:事件循环(normal :2221 / overlap :2256,四种变体 :7107-7120)→ ingest(:2359)→ 调度决策(先 prefill 后 decode,:4461-4489)→ 预算准入(PrefillAdder :1077,三本账 :1118-1143)→ KV 不足抽回(:5249-5337,schedule_batch.py:3018)→ 折叠执行(tp_worker.py:624,ForwardBatch.init_new :657;三路径 model_runner.py:2141-2193)→ 采样同步(sampler.py:120/:300/:413-414/:334-336)→ 结果流回(:5932,OutputStreamer → DetokenizerManager)。
- 调度铁律:prefill 优先(:4478-4480),decode 让步但由 retract 机制保命。
- 折叠即接口:ScheduleBatch 带策略语义,ForwardBatch 是纯张量视图。
- 三条前向路径:decode 整图回放、prefill 分段图、eager 兜底。
- 采样三件事:融合 softmax、top-k/top-p renorm、token 跨 TP 一致性。
- 下一章解剖旅程里反复出现的 KV 池与它上面的复用层:05-KVCache内存池与RadixCache。
前置:03-双入口与三进程流水线 | 下一篇:05-KVCache内存池与RadixCache | 回目录:README