vLLM推理服务教程 · 03-双入口与请求生命周期
03 - 双入口与请求全生命周期
所属系列:vLLM 推理服务教程 | 前置:02-构建体系与首次运行 | 下一篇:04-EngineCore主循环与统一调度
证据基线:commit2e738227。主战场vllm/entrypoints/与vllm/v1/engine/。
本章沿着一条请求的一生走:怎么进来、怎么被装配成EngineCoreRequest、怎么变回RequestOutput、断连了怎么办。
本篇知识图谱
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇目标
- 对照走读两个入口的驱动方式:离线同步 while 循环调 step,在线异步生成器流式 yield——同一引擎,两种节奏。
- 拆清装配侧:InputProcessor 如何把任意输入变成
EngineCoreRequest,n>1 如何派生子请求并"双侧注册"。 - 拆清输出侧:增量 detokenizer 与 stop-string 偏移截断、logprobs、RequestOutput 的双路分发。
- 理解断连自动 abort:客户端断开如何经
CancelledError传导为引擎侧请求取消。
1. 一条请求的旅程总览
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
两个入口在 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 | while self.llm_engine.has_unfinished_requests(): # :610 |
循环直到无未完成请求,最后按 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 | q = await self.add_request(...) # 返回每请求的 RequestOutputCollector |
断连自动 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 对象避免拷贝(:310idx == 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):
- 统计:
_update_stats_from_output(:778-780)。 - 增量 detokenize:
req_state.detokenizer.update(new_token_ids, stop_terminated)(:828-830);若命中 stop string,改写 finish_reason 并_trim_surplus_tokens(:831-836)。 - logprobs:
req_state.logprobs_processor.update_from_output(:843-845)。 - 构造 RequestOutput:
req_state.make_request_output(...)(:852-860),然后双路分发(:864-869):有队列(AsyncLLM)→req_state.queue.put(request_output);无队列(LLMEngine)→ 攒进返回列表。 - 释放:完成即
_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