vLLM推理服务教程 · 03-双入口与请求生命周期

03 - 双入口与请求全生命周期

所属系列:vLLM 推理服务教程 | 前置:02-构建体系与首次运行 | 下一篇:04-EngineCore主循环与统一调度
证据基线:commit 2e738227。主战场 vllm/entrypoints/ 与 vllm/v1/engine/。
本章沿着一条请求的一生走:怎么进来、怎么被装配成 EngineCoreRequest、怎么变回 RequestOutput、断连了怎么办。

本篇知识图谱

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
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((双入口与请求生命周期))
离线入口
LLM.generate llm.py:427
_run_engine offline.py:589
while 循环调 step :610
LLMEngine.step 三段 :323
在线入口
build_and_serve entry.py:115
create_completion serving.py:161
engine_client.generate :257
AsyncLLM.generate :740
断连 CancelledError abort :821
装配侧
InputProcessor process_inputs :367
EngineCoreRequest :552
process_inputs_async 不阻塞事件循环
ParentRequest 派生 :306
双侧注册
输出侧
process_outputs :731
增量detokenizer :142
stop串 偏移截断 :180
logprobs :845
队列或列表 双路 :864
后台handler
output_handler :870
分块处理 :905
停止串补abort :932

本篇目标

  1. 对照走读两个入口的驱动方式:离线同步 while 循环调 step,在线异步生成器流式 yield——同一引擎,两种节奏。
  2. 拆清装配侧:InputProcessor 如何把任意输入变成 EngineCoreRequest,n>1 如何派生子请求并"双侧注册"。
  3. 拆清输出侧:增量 detokenizer 与 stop-string 偏移截断、logprobs、RequestOutput 的双路分发。
  4. 理解断连自动 abort:客户端断开如何经 CancelledError 传导为引擎侧请求取消。

1. 一条请求的旅程总览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
flowchart TD
subgraph OFF["离线:同步世界"]
G["LLM.generate<br/>llm.py:427-491"] --> RC["_run_completion :482"]
RC --> RE["_run_engine 循环<br/>offline.py:589-642<br/>while has_unfinished: step"]
end
subgraph ON["在线:异步世界"]
API["create_completion 路由<br/>completion/serving.py:161"] --> EG["engine_client.generate<br/>:257-266"]
EG --> AG["AsyncLLM.generate 异步生成器<br/>async_llm.py:740-826"]
end
RE --> ADD["add_request<br/>llm_engine.py:231-321"]
AG --> ADD
ADD --> IP["InputProcessor<br/>→ EngineCoreRequest"]
IP --> CORE["EngineCore(04章)"]
CORE --> PO["OutputProcessor.process_outputs<br/>output_processor.py:731-897"]
PO --> BACK["RequestOutput"]
BACK --> RE
BACK --> AG

两个入口在 add_request 汇合,装配与输出机制完全共用——分叉只在谁来驱动 step 与谁来消费输出。

2. 离线入口:LLM.generate 的同步循环

  • LLM.generate(vllm/entrypoints/llm.py:427-491)校验 runner 类型后调 _run_completion(:482-491),它把所有请求 add_request 进引擎后调 _run_engine(vllm/entrypoints/llm.py:581)。
  • _run_engine(vllm/entrypoints/common/offline.py:589-642)就是一个 while 循环(Observed):
1
2
3
4
5
while self.llm_engine.has_unfinished_requests():        # :610
step_outputs = self.llm_engine.step() # :611
# 收集 output.finished 的输出,tqdm 记速
...
return sorted(outputs, key=lambda x: int(x.request_id)) # :642

循环直到无未完成请求,最后按 request_id 排序还原输入顺序(:639-642 注释:请求可能乱序完成)。

  • LLMEngine.step(vllm/v1/engine/llm_engine.py:323-363)三段式(Observed):① engine_core.get_output() 取回 EngineCoreOutput(:331);② output_processor.process_outputs 转 RequestOutput(:344-349);③ 对因 stop string 而完成的请求补发 engine_core.abort_requests(:360-362)。

3. 在线入口:vllm serve 的异步流

3.1 服务搭建与路由

build_and_serve(vllm/entrypoints/launchers/api_server/entry.py:115-161)构建 FastAPI app(build_app,:136,按 supported_tasks 挂路由)、初始化 app state(:137),交给 uvicorn 的 serve_http(:141-161)。completion 路由的处理函数是 create_completion(vllm/entrypoints/openai/completion/serving.py:161)。

3.2 路由 → engine_client.generate

create_completion 对每个 prompt 调 self.engine_client.generate(...)(serving.py:257-266),n 路 prompt 的生成器用 merge_async_iterators 合流(:270);流式请求转 completion_stream_generator(:278-289),非流式则攒完整响应。

3.3 AsyncLLM.generate:异步生成器

AsyncLLM.generate(vllm/v1/engine/async_llm.py:740)的骨架(Observed,:785-826):

1
2
3
4
5
6
7
8
q = await self.add_request(...)            # 返回每请求的 RequestOutputCollector
while not finished:
out = q.get_nowait() or await q.get() # :809 尽量不 await,减少任务切换
finished = out.finished
yield out # 逐 token 流式吐给上层
except (asyncio.CancelledError, GeneratorExit): # :821
await self.abort(q.request_id, internal=True) # 断连→abort
raise

断连自动 abort 就住在这里:客户端断开 → FastAPI 取消 handler → 生成器收到 CancelledError/GeneratorExit → abort(request_id, internal=True)(:821-823,原文注释 “If the request is disconnected by the client, generate() is cancelled”)。

3.4 output_handler:后台输出泵

AsyncLLM 在首个 add_request 时启动后台任务 _run_output_handler(vllm/v1/engine/async_llm.py:870-944,Observed):死循环 await engine_core.get_output_async()(:894),按 VLLM_V1_OUTPUT_PROC_CHUNK_SIZE 分块调 process_outputs(:905-924,块间 asyncio.sleep(0) 让出事件循环),并注释明确"RequestOutputs are pushed to their queues"(:925-926);对 stop-string 完成的请求补 abort(:932-936)。

4. 装配侧:add_request 经 InputProcessor

4.1 process_inputs:任意输入 → EngineCoreRequest

InputProcessor.process_inputs(vllm/v1/engine/input_processor.py:367-424,返回类型 EngineCoreRequest :382)依次做(Observed):参数与 LoRA 校验(:383-384)、DP rank 校验(:386-394)、经 renderer 渲染并分词(renderer.render_cmpl,:419-422)、enc/dec 输入拆分(:424)、平台与模型输入校验(:426-427),最终在 :552 构造 EngineCoreRequest。

在线路径有同步/异步两个变体(vllm/v1/engine/async_llm.py:494-528):已渲染的 EngineInput 走同步 process_inputs(:495-511);raw prompt 则必须走 process_inputs_async——源码注释:“Raw prompts require tokenization and possibly multimodal processing, which must not block the event loop”(:513-515)。这就是"分词/多模态在装配侧完成"的落点。

4.2 n>1:ParentRequest 派生与双侧注册

LLMEngine.add_request(vllm/v1/engine/llm_engine.py:231-321)拿到装配好的 request 后(Observed):

  • n==1:output_processor.add_request(建 RequestState 与队列)+ engine_core.add_request(送 EngineCore)——各一次,:299-304。
  • n>1:包成 ParentRequest(:307,类定义 vllm/v1/engine/parallel_sampling.py:13),循环 get_child_info(idx) 派生 n 个子请求(:308-312,get_child_info 在 parallel_sampling.py:84),每个子请求都双侧注册:OutputProcessor 侧建状态与队列(:315-317)、EngineCore 侧排进调度(:319)。第 n 个子请求复用原 request 对象避免拷贝(:310 idx == n - 1 判断)。

所谓"双侧注册":前端 OutputProcessor 要跟踪每个子请求的输出状态,EngineCore 要调度它们——两个账本必须同时建,少一边就丢输出或白算。

5. 输出侧:detokenizer → logprobs → RequestOutput

OutputProcessor.process_outputs(vllm/v1/engine/output_processor.py:731-897)是"唯一允许遍历整个 batch 的函数"(docstring :749-753,V1 刻意最小化 Python 循环)。对每个 EngineCoreOutput 依次(Observed):

  1. 统计:_update_stats_from_output(:778-780)。
  2. 增量 detokenize:req_state.detokenizer.update(new_token_ids, stop_terminated)(:828-830);若命中 stop string,改写 finish_reason 并 _trim_surplus_tokens(:831-836)。
  3. logprobs:req_state.logprobs_processor.update_from_output(:843-845)。
  4. 构造 RequestOutput:req_state.make_request_output(...)(:852-860),然后双路分发(:864-869):有队列(AsyncLLM)→ req_state.queue.put(request_output);无队列(LLMEngine)→ 攒进返回列表。
  5. 释放:完成即 _finish_request;若 EngineCore 侧可能还持有请求(此处检测到 stop string),追加 reqs_to_abort(:872-885)——与 3.4 节 handler 的补 abort 首尾呼应。

5.1 增量 detokenizer 与 stop-string 偏移截断

detokenizer 家族(vllm/v1/engine/detokenizer.py,Observed):基类 IncrementalDetokenizer(:76)定义 update 协议,BaseIncrementalDetokenizer(:115)实现通用逻辑,FastIncrementalDetokenizer(:225,Numpy 加速)与 SlowIncrementalDetokenizer(:310,纯 Python 兜底)二选一。

BaseIncrementalDetokenizer.update(:142-201)两步走:

  • 增量解码(:161-170):只对新增 token 调 decode_next,逐步拼接 output_text,同时记录每个新 token 的字符偏移 token_offsets(:165-170)。
  • stop string 判定与截断(:178-199):check_stop_strings 只扫新增字符(new_char_count,:183-188);命中后按 truncate_to 偏移截文本(:198-199),并用 bisect_left(token_offsets, stop_end)(:196)把完成 stop 串之后多出的 token 从 token_ids 里删掉——一步 decode 出多个 token 时(如投机解码),多余部分必须回滚。include_stop_str_in_output 决定 stop 串本身是否保留(:192-193)。

6. 双入口对照速查

维度 离线 LLM.generate 在线 vllm serve
驱动 用户线程 while 循环调 step(offline.py:610-611) output_handler 后台任务 + 事件循环(async_llm.py:890-938)
输出消费 step() 返回列表,结束统一排序(:642) 每请求队列 → 异步生成器逐个 yield(:809-816)
装配 process_inputs 同步 渲染输入同步、raw prompt 走 async(async_llm.py:494-528)
断连 不适用(跑完为止) CancelledError → abort(async_llm.py:821-823)
n>1 ParentRequest 派生,双侧注册(llm_engine.py:306-319) 同一机制,共用

本篇小结

  • 同一引擎,两种节奏:离线是"调用方拉"(while step),在线是"引擎推"(队列+生成器);分叉点在 add_request(llm_engine.py:231-321)之前与 process_outputs(:731-897)之后。
  • 装配:InputProcessor 的 process_inputs(input_processor.py:367)负责渲染/分词/校验,产 EngineCoreRequest(:552);n>1 经 ParentRequest(parallel_sampling.py:13)派生子请求并双侧注册。
  • 输出:增量 detokenizer(detokenizer.py:142-201)用 token 字符偏移做 stop-string 截断与投机多 token 回滚;logprobs 独立更新;RequestOutput 按有无队列双路分发。
  • 断连即取消:在线生成器捕获 CancelledError/GeneratorExit 自动 abort(async_llm.py:821-823),后台 handler 与输出侧共同兜底 stop-string 类补 abort。

前置:02-构建体系与首次运行 | 下一篇:04-EngineCore主循环与统一调度 | 回目录:README