vLLM推理服务教程 · 04-EngineCore主循环与统一调度
04 - EngineCore 主循环与统一调度
所属系列:vLLM 推理服务教程 | 前置:03-双入口与请求生命周期 | 下一篇:05-KVCache与显存管理
证据基线:commit2e738227。主战场vllm/v1/engine/core.py与vllm/v1/core/sched/scheduler.py。
本系列灵魂章:01 章说过"所有机制都是 step 的放大镜"——本章就是把主循环本身拆开。
本篇知识图谱
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇目标
- 逐段拆解
step()五段主循环(core.py:714-744),每段知道输入输出与谁负责。 - 吃透统一 token 预算算法:为什么"无 prefill/decode 两阶段"的注释是整个调度器的世界观。
- 掌握准入与抢占:allocate_slots 失败后的抢占选择、预算回滚、watermark 门控。
- 建立异步视角:batch queue 的前向飞行流水化与 deferred sampling 的延迟提交。
1. step 五段主循环
run_busy_loop(vllm/v1/engine/core.py:1814-1825)每轮调 _process_engine_step(),最终落到 step()(vllm/v1/engine/core.py:714-744,Observed):
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
五段各自的职责(Observed):
| 段 | 位置 | 职责 |
|---|---|---|
| ① schedule | core.py:724 | 调度器分配本步 token 预算 → SchedulerOutput |
| ② execute_model | core.py:727 | non_block=True 提交前向,立刻拿 future |
| ③ get_grammar_bitmask | core.py:728 | 结构化输出掩码在 CPU 上算,与 GPU 前向重叠 |
| ④ sample_tokens | core.py:730-732 | 等前向产出并采样 |
| ⑤ update_from_output | core.py:738-740 | 回滚预算记账、产出 EngineCoreOutputs |
一个关键语义:前向与采样分离。GPU 侧 execute_model 只跑前向,把状态存进 execute_model_state 后返回 None(vllm/v1/worker/gpu/model_runner.py:2249-2275);core 侧拿到 None 后才调 sample_tokens(core.py:731-732,采样入口 model_runner.py:2279)——grammar bitmask 因此得以插在前向与采样之间(PP 非末级则前向直接回 IntermediateTensors,多卡折叠读)。池化模型不经采样,前向结果即输出(core.py:796 的 is_pooling_model 分支,Observed)。
2. 统一 token 预算:调度器的世界观
Scheduler.schedule 开头的注释是本章的题眼(vllm/v1/core/sched/scheduler.py:704-713,原文 Observed):
There’s no “decoding phase” nor “prefill phase” in the scheduler. Each request just has the
num_computed_tokensandnum_tokens_with_spec(=len(prompt_token_ids) + len(output_token_ids) + len(spec_token_ids)). At each step, the scheduler tries to assign tokens to the requests so that each request’snum_computed_tokenscan catch up itsnum_tokens_with_spec. This is general enough to cover chunked prefills, prefix caching, speculative decoding…
读懂这段就懂了 V1 调度器:
- 每个请求只有两个账面数字:已算完多少(
num_computed_tokens)与应该算多少(num_tokens_with_spec)。 - 每步的差值就是要补的 token 数——
num_new_tokens = num_tokens_with_spec + num_output_placeholders - num_computed_tokens(scheduler.py:824-828,Observed)。 - chunked prefill = 差值太大,一步只能补一部分;前缀缓存命中 = 差值凭空变小(命中部分直接计入 computed);投机解码 = spec token 让"应该算"先行膨胀,验证后再清算。三种特性不需要三套调度逻辑,只是同一个追赶目标的三个来源。
预算三件套(:728-731,Observed):token_budget = max_num_scheduled_tokens、input_budget = max_num_batched_tokens、draft_slots = spec.max_num_new_slots_for_drafting(投机时为 draft 留位);PAUSED_ALL 时 token_budget 直接归零(:732-734)。
3. running 队列截断:本步给谁补多少
running 循环(scheduler.py:780)逐请求补 token,四类跳过项(Observed):
- output placeholders(:785-799):异步调度下在途步必然产出的 token 先占位,若在途产出已能到达
max_tokens,本步不再调度——注释明说这避免破坏 uniform decode 优化; - PP 节拍(:801-805):PP+async 下同一请求每
pp_size步才 decode 一次(多卡折叠); - prefill 节流(:807-811):DP prefill 平衡时把进行中的 prefill chunk 推迟一个节拍;
- EC connector(:813-822):外部 KV connector 缓存不可用则跳过。
补多少:先按差值算 num_new_tokens(:824-828),长 prefill 阈值截断(:829-830),再被三个预算夹住——min(num_new_tokens, token_budget, input_budget - draft_slots)(:831-833)。running 先吃预算,waiting 才有剩余——这就是 running 队列优先的由来。
4. 准入与抢占
4.1 allocate_slots:KV 预算的准入门
每个被调度请求都要过 kv_cache_manager.allocate_slots(running 路径调用在 scheduler.py:899,waiting 路径在 :1489——后者多传 prefix-cache 命中与 connector 参数)。返回 None = KV 装不下。内部块布局与分配细节是 05 章主题,本章只看它的门控面:watermark_blocks。
4.2 watermark 门控
watermark_blocks = int(watermark * num_blocks)(vllm/v1/core/kv_cache_manager.py:200,watermark 来自 scheduler_config,scheduler.py:380)。应用规则(kv_cache_manager.py:529-536,注释原文 Observed):“The watermark is applied to waiting/preempted requests only, and only when there’s at least one request already scheduled”——即只有当本步已有 running 请求在跑、新请求又是 WAITING/PREEMPTED 状态时,才要求预留这段缓冲:required_blocks = num_blocks_to_allocate + watermark_blocks(:557)。这是防"新请求挤死在跑请求"的准入闸:KV 将满时,waiting 不再放行,running 继续吃剩余空间。
4.3 抢占:谁让位,怎么回滚
allocate_slots 反复失败时进入抢占循环(scheduler.py:896-968,Observed):
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
要点(Observed):
- FCFS 策略抢占
running[-1](:923,最晚到的先让位);PRIORITY 策略抢max(running, key=(priority, arrival_time))(:917-921)——优先级数字大者、同优先级先到者先被抢。 - 预算回滚(:935-957):victim 若已在本步调度名单里,要把它当初占走的账全部吐回来——
token_budget += restored(:939)、input_budget += restored + draft_slots(:940)、弹出 blocks/spec/encoder 记账(:941-957)。调度器的每一步都是"预算收支表",抢占是冲销分录。 _preempt_request(:961-965)把请求打回 WAITING 并释放 KV 块;若 victim 就是当前请求本身(没有别的可抢),当前请求也放弃本步(:967-968)。
4.4 waiting 队列:三条队伍有先后
waiting 不是一条队列(scheduler.py:1055-1092,Observed):持有 KV 块的请求永远先被清空(“Requests holding KV blocks are always drained first”,:1078-1080,kv_holding_waiting)——它们的 KV 已经在显存里,最先能跑;普通 waiting 在其后;没有 running 槽位或 token 预算时,只允许启动 async_kv_waiting 的异步 KV 装载(:1083-1090,装载不占 running 槽与预算)。
5. batch queue 与 deferred sampling:前向飞行流水化
step_with_batch_queue(vllm/v1/engine/core.py:759-884,异步调度启用)把 step 改成流水线(Observed):
- 能排就排:batch queue 未满且调度器有活时,立刻 schedule +
execute_model(non_block=True),把 future 塞进batch_queue.appendleft(:781-827),本步不等待就返回——多个前向在 GPU 上"飞行"。 - 满了才收:队列满时阻塞弹出队尾(最老的)future(:836-840),走 update_from_output。
- 结构化输出延迟提交(deferred sampling,:816-819):若本步有
pending_structured_output_tokens——请求的 grammar 掩码依赖前一步才产出的 token(xgrammar 增量编译需要前缀文本)——此时不能立刻算 bitmask,把(scheduler_output, exec_future)暂存self.deferred_step。 - 补交(:861-882):等某个 update_from_output 完成后,若队列中不再有与 deferred step 共享请求的飞行步(:861-863),取出暂存步:投机场景先
take_draft_token_ids补 draft id(:869-875),然后"We now have the tokens needed to compute the bitmask"——此刻才算 grammar 并sample_tokens,把结果 appendleft 回队列(:876-882)。注释点明这是 TTFT 与 TPOT 的取舍(:856-858)。
两个进阶专题的机制入口都在本章:投机解码的调度侧是预算里的 draft_slots(:730)与 num_tokens_with_spec 的 spec 分量(:708),采样侧 rejection sampler 在 06 章;结构化输出的 get_grammar_bitmask(scheduler.py:2310)就是五段之③,依赖前步 token 时的 deferred 机制见本节。
本篇小结
- 五段主循环(core.py:714-744):schedule → execute_model(non_block) → get_grammar_bitmask → sample_tokens → update_from_output;前向与采样在 GPU 侧分离(model_runner.py:2249-2275 / :2279)。
- 统一预算(scheduler.py:704-713):没有 prefill/decode 两阶段,只有"computed 追 spec"的差值补充(:824-828)——chunked prefill、前缀缓存、投机解码是同一算法的三个来源。
- 准入与抢占:allocate_slots 失败 → PRIORITY 按 priority+arrival_time 选 victim(:917-921)、FCFS 抢 running[-1](:923),预算全量回滚(:938-957);watermark 只门控 WAITING/PREEMPTED 且仅当已有请求在跑(kv_cache_manager.py:529-536)。
- 异步流水:batch queue 让前向飞行(core.py:759-884),结构化输出依赖前步 token 时经 deferred_step 延迟提交(:816-819/:861-882)。
前置:03-双入口与请求生命周期 | 下一篇:05-KVCache与显存管理 | 回目录:README