【vllm】vLLM v1 系统级架构分析(总)

张开发
2026/4/21 9:03:30 15 分钟阅读

分享文章

【vllm】vLLM v1 系统级架构分析(总)
vLLM v1 系统级架构分析分析日期2026-04-20代码目录vllm/vllm/v1目录整体架构概览架构模式与设计思路整体运行流程子模块详细分析4.1 engine — 引擎层4.2 core/sched — 核心调度层4.3 worker — 工作执行层4.4 attention — 注意力计算层4.5 sample — 采样层4.6 spec_decode — 推测解码层4.7 executor — 执行器层4.8 pool — 池化模块4.9 structured_output — 结构化输出4.10 kv_offload — KV缓存卸载4.11 metrics — 指标监控模块调用关系与数据流架构图索引1. 整体架构概览vLLM v1 是 vLLM 推理引擎的第二代架构采用六层分层架构 插件式后端设计。相比 v0 架构v1 的核心改进在于进程分离将 EngineCore 运行在独立后台进程中通过 ZMQ/TensorIPC 与前端通信实现计算与 I/O 重叠统一调度Scheduler 统一管理生成和池化请求支持分块预填充chunked prefill插件式后端Attention、SpecDecode、StructuredOutput、KVOffload 均通过注册机制 运行时选择实现多设备抽象WorkerBase → GPUWorker/CPUWorker/XPUWorker 多设备后端核心数据流用户请求 → AsyncLLM → InputProcessor → CoreClient → [ZMQ] → EngineCore → Scheduler → SchedulerOutput → Executor → Worker → GPUModelRunner → [Model Forward Attention Sample] → ModelRunnerOutput → [返回路径] → EngineCore → CoreClient → OutputProcessor → RequestOutput模块统计模块目录文件数核心职责engine/14API入口、输入处理、输出组装、进程间通信core/8请求调度、KV缓存管理、前缀缓存worker/30GPU/CPU/XPU执行、批量管理、CUDA Graphattention/30注意力后端FlashAttn/FlashInfer/MLA等sample/10采样、logits处理、TopK/TopPspec_decode/10推测解码Eagle/Medusa/Ngrampool/3池化元数据、晚交互评分structured_output/7结构化输出xgrammar/outlineskv_offload/12KV缓存CPU卸载、LRU/ARC淘汰executor/8执行器抽象、多进程/Ray分布式metrics/8Prometheus指标、性能统计2. 架构模式与设计思路2.1 分层架构Layered Architecturev1 采用严格的六层分层层次名称核心组件职责L1API/FrontendAsyncLLM, InputProcessor, OutputProcessor请求接收、参数验证、输出格式化L2Engine CoreEngineCore, CoreClient, Coordinator调度循环、进程间通信、数据并行协调L3SchedulingScheduler, KVCacheManager, RequestQueue请求调度、KV缓存块管理、前缀缓存L4Worker/ExecutionGPUWorker, GPUModelRunner, InputBatch模型执行、批量状态管理、CUDA GraphL5Functional SubsystemsAttention, Sample, SpecDecode, Pool, StructOutput, KVOffload具体计算功能实现L6Executor/DistributedMultiprocExecutor, RayExecutor多GPU编排、分布式通信层次间通信方式L1 ↔ L2ZMQ多进程或直接调用单进程 InprocClientL2 ↔ L3EngineCore 直接调用 SchedulerL3 ↔ L4SchedulerOutput 通过 Executor 传递到 WorkerL4 ↔ L5GPUModelRunner 通过接口调用各子系统L4 ↔ L6Executor 创建并管理 Worker 进程2.2 插件式后端Plugin Backend多个子系统采用抽象基类 注册表 运行时选择模式AttentionBackend (ABC) → FlashAttn / FlashInfer / MLA / TritonAttn / ... ↕ Registry AttentionSelector (根据硬件/模型自动选择) Executor (ABC) → UniprocExecutor / MultiprocExecutor / RayExecutor ↕ Executor.get_class() (根据配置选择) KVOffloadManager (ABC) → CPUOffloadManager ↕ factory.py (根据配置创建) StructuredOutputBackend → xgrammar / outlines / lm_format_enforcer ↕ StructuredOutputManager (根据请求选择)2.3 数据并行架构v1 支持 Data Parallel (DP) 推理DPCoordinator协调多引擎的数据并行CoreClient通过 CRC32 哈希将晚交互请求路由到特定引擎Wave机制DP 场景下按波调度请求确保同步完成2.4 关键设计决策EngineCore 独立进程避免 GIL 限制调度循环不阻塞 API 层TensorIPCGPU 张量零拷贝传输通过共享内存避免序列化开销分块预填充长 prompt 可跨多步调度与 decode 请求混合执行Block-based KV Cache以固定大小 block 为单位管理 KV 缓存支持前缀共享CUDA Graph 重放将 decode 步骤捕获为 CUDA Graph通过重放避免 CPU 开销3. 整体运行流程3.1 生成请求Generation Request完整生命周期┌──────────────────────────────────────────────────────────────────┐ │ Phase 1: 请求接收 │ │ AsyncLLM.generate(prompt, SamplingParams) │ │ → InputProcessor.process() │ │ → Renderer: prompt → token_ids mm_features │ │ → SamplingParams.verify() → 设置 task, temperature 等 │ │ → CoreClient.add_request(EngineCoreRequest) │ │ → ZMQ socket 发送 msgpack 编码的请求 │ ├──────────────────────────────────────────────────────────────────┤ │ Phase 2: 调度 │ │ EngineCore 调度循环: │ │ → Scheduler.schedule() │ │ → RequestQueue: 取出待调度请求 │ │ → KVCacheManager: 分配 KV cache blocks │ │ → 前缀缓存匹配hash-based block reuse │ │ → 构建 SchedulerOutput (NewRequestData CachedRequestData) │ │ → Executor.execute_model(SchedulerOutput) │ ├──────────────────────────────────────────────────────────────────┤ │ Phase 3: 执行 │ │ Executor → GPUWorker → GPUModelRunner │ │ → InputBatch: 组装批量数据 │ │ → Model.forward() → hidden_states │ │ → Attention: 根据后端选择执行注意力计算 │ │ → Sampler: logits → penalties → topk_topp → sample tokens │ │ → (若 spec_decode: draft tokens → rejection sampling) │ │ → (若 pool: PoolingRunner.pool() → embedding) │ │ → (若 structured_output: grammar-guided sampling) │ │ → ModelRunnerOutput (token_ids, logprobs, pooler_output, ...) │ ├──────────────────────────────────────────────────────────────────┤ │ Phase 4: 输出处理 │ │ EngineCore.update_from_output() │ │ → Scheduler 处理完成的请求释放 KV blocks │ │ → EngineCoreOutput → CoreClient → OutputProcessor │ │ → Detokenizer: token_ids → text │ │ → LogprobsProcessor: 格式化 logprobs │ │ → RequestOutput 返回给用户 │ └──────────────────────────────────────────────────────────────────┘3.2 分块预填充Chunked Prefill长 prompt (e.g. 4096 tokens, chunk_size1024) │ ├─ Step 1: schedule 1024 tokens (prefill chunk 1) │ → KVCacheManager 分配 blocks 0-15 │ → Model forward (prefill attention) │ → 保存 hidden_states 到 PoolingStates若 pool 请求 │ → 不输出任何 token未完成全部 prefill │ ├─ Step 2: schedule 1024 tokens (prefill chunk 2) │ → 复用 blocks 0-15, 新增 blocks 16-31 │ → Model forward │ → 仍不输出 token │ ├─ ... (chunk 3, 4) │ └─ Step 4: 最后一个 chunk 完成 → PoolingCursor.is_finished() True → 执行池化聚合 → 输出 embedding / classification → (若是生成请求) → 开始 decode 步骤3.3 推测解码流程Step 1: Draft (推测) SpecDecodeProposer (Eagle/Medusa/Ngram) → 生成 k 个 draft tokens (概率分布) Step 2: Verify (验证) GPUModelRunner.execute_model() → 将 draft tokens 一起送入模型 → 模型输出每个位置的 logits Step 3: Reject (拒绝采样) RejectionSampler → 比较模型 logits vs draft 概率 → 接受匹配的 draft tokens → 拒绝不匹配的从模型分布重新采样 → 输出最终 token 序列 接受长度 Metric: acceptance_rate accepted / proposed4. 子模块详细分析4.1 engine — 引擎层核心作用engine 模块是 v1 的入口和编排层负责请求的全生命周期管理从 API 接收到输出返回。它是前端API 进程与后端EngineCore 进程的桥梁。关键类/方法类文件核心方法说明AsyncLLMasync_llm.pygenerate(),encode(),abort()异步 API 主入口InputProcessorinput_processor.pyprocess(),process_pooling()将原始 prompt 转为 EngineCoreRequestOutputProcessoroutput_processor.pyprocess_outputs()将 EngineCoreOutput 转为 RequestOutputEngineCorecore.pyrun(),step()后台进程中的调度循环CoreClientcore_client.pyadd_request(),get_outputs()前端与 EngineCore 的通信抽象InprocClientcore_client.py直接方法调用单进程模式AsyncMPClientcore_client.pyZMQ async socket多进程异步模式SyncMPClientcore_client.pyZMQ sync socket多进程同步模式Detokenizerdetokenizer.pydecode()增量 detokenizationCoordinatorcoordinator.pyDP 协调数据并行引擎协调TensorIPCtensor_ipc.pysend(),recv()GPU 张量零拷贝传输数据结构结构说明EngineCoreRequestmsgspec.Struct包含 request_id, prompt_token_ids, sampling_params, pooling_params 等EngineCoreOutputmsgspec.Struct包含 request_id, new_token_ids, finish_reason, pooling_output 等EngineCoreOutputsmsgspec.Struct包含 outputs 列表 scheduler_stats4.2 core/sched — 核心调度层核心作用core/sched 模块是 v1 的调度中枢决定每个 step 处理哪些请求、分配多少 KV cache blocks、如何混合 prefill 和 decode。关键类/方法类文件核心方法说明Schedulerscheduler.pyschedule(),update_from_outputs()主调度器决定请求调度SchedulerInterfaceinterface.py抽象接口调度器抽象基类AsyncSchedulerasync_scheduler.py异步调度支持异步调度模式KVCacheManagerkv_cache_manager.pyallocate(),free(),get_prefix_cache_blocks()KV 缓存块管理KVCacheUtilskv_cache_utils.pygenerate_scheduler_kv_cache_config()块哈希、调度器配置BlockPoolblock_pool.pyget_free_block(),free_block()空闲块池管理RequestQueuerequest_queue.pypush(),pop()优先级请求队列EncoderCacheManagerencoder_cache_manager.pyMM 编码器输出缓存多模态编码器缓存调度策略优先级调度请求按 priority 排序分块预填充长 prompt 分多个 chunk 调度与 decode 请求混合前缀缓存通过 block hash 匹配已有 KV cache避免重复计算抢占当 GPU 内存不足时抢占低优先级请求释放 blocksALL pooling 检测若当前批次全部为 pool 请求跳过 decode 步骤SchedulerOutput 数据结构dataclassclassSchedulerOutput:scheduled_new_reqs:list[NewRequestData]# 新请求scheduled_cached_reqs:list[CachedRequestData]# 缓存请求有前缀命中num_scheduled_tokens:int# 本步总 token 数total_num_scheduled_tokens:list[int]# 各组 token 数grammar_outputs:list[GrammarOutput]# 结构化输出...4.3 worker — 工作执行层核心作用worker 模块是 v1 的执行引擎负责模型加载、forward pass、CUDA Graph 捕获/重放、批量状态管理。关键类/方法类文件核心方法说明WorkerBaseworker_base.pyinit_device(),load_model(),execute_model()工作器抽象基类GPUWorkergpu_worker.pyexecute_model(),determine_available_memory()GPU 工作器GPUModelRunnergpu_model_runner.pyexecute_model(),_execute_pooling()GPU 模型执行器~5700行最核心文件InputBatchgpu_input_batch.pyadd_request(),get_sampling_metadata(),get_pooling_metadata()批量状态管理CPUWorkercpu_worker.pyCPU 后端执行XPUWorkerxpu_worker.pyXPU (Intel GPU) 后端CachedRequestStategpu_input_batch.py请求级缓存状态GPUModelRunner 核心流程execute_model(scheduler_output) → 解析 new/cached requests → InputBatch.add_request() / update() → _execute_forward() → Model.forward(hidden_states) → Attention (根据 backend) → Sampler / PoolingRunner → LateInteractionRunner.postprocess() → _execute_decode() (CUDA Graph 重放模式) → 构建 ModelRunnerOutputGPU 子系统子目录职责gpu/sample/采样器Gumbel、LogitBias、MinP、Penalties、Logprobgpu/pool/池化执行器PoolingRunner、LateInteractionRunnergpu/mm/多模态EncoderRunner、EncoderCache、RoPEgpu/spec_decode/推测解码Eagle Speculator、RejectionSamplergpu/model_states/模型状态管理Default、Whispergpu/metrics/Logits 指标4.4 attention — 注意力计算层核心作用attention 模块实现了 v1 的注意力计算抽象层通过后端注册 运行时选择支持多种 GPU 注意力实现。关键类/方法类/函数文件说明AttentionBackendbackend.py抽象基类定义接口AttentionMetadatabackend.py注意力批量元数据FlashAttnBackendbackends/flash_attn.pyFlashAttention-2 后端FlashInferBackendbackends/flashinfer.pyFlashInfer 后端TritonAttnBackendbackends/triton_attn.pyTriton 自定义后端FlexAttentionBackendbackends/flex_attention.pyPyTorch FlexAttentionMLABackendbackends/mla/Multi-head Latent AttentionDeepSeek系列MambaAttnBackendbackends/mamba_attn.pyMamba/SSM 后端AttentionSelectorselector.py根据硬件/模型自动选择后端BackendRegistrybackends/registry.py后端注册表注意力操作ops/文件说明paged_attn.pyPaged Attention kernelchunked_prefill_paged_decode.py混合 prefill decodeprefix_prefill.py前缀缓存 prefillmerge_attn_states.py合并注意力状态triton_decode_attention.pyTriton decode 专用triton_prefill_attention.pyTriton prefill 专用flashmla.pyFlashMLA kerneldcp_alltoall.pyDisaggregated prefill 通信MLA 子系统MLA (Multi-head Latent Attention) 是 DeepSeek 系列模型的专用注意力机制包含多种实现flashmla.py— FlashMLA 官方 kernelcutlass_mla.py— CUTLASS 实现flashinfer_mla.py— FlashInfer MLAtriton_mla.py— Triton 自定义aiter_triton_mla.py— AMD ROCm 实现indexer.py— MLA 索引构建4.5 sample — 采样层核心作用sample 模块负责从模型 logits 中采样下一个 token包括各种惩罚、约束和采样策略。关键类/方法类文件核心方法说明Samplersampler.pyforward()主采样器9步采样管线SamplingMetadatametadata.py—批量采样参数LogitsProcessorlogits_processor/interface.pyapply()Logits 处理器接口BuiltinLogitsProclogits_processor/builtin.py—内建处理器temperature, top_k, min_p 等TopKTopPSamplerops/topk_topp_sampler.pyforward()GPU TopK/TopP 采样RejectionSamplerrejection_sampler.pyforward()推测解码拒绝采样Sampler 9步管线1. (若请求) 计算/克隆 logprobs 2. Logits → float32 3. 应用 allowed_token_ids 白名单 4. 应用 bad_words 排除 5. 应用非 argmax-invariant 处理器min_tokens, logit_bias 6. 应用惩罚repetition/frequency/presence 7. 采样 a. 若 all_greedy → argmax b. 应用 temperature c. 应用 min_p d. 应用 top_k / top_p e. 随机采样 8. 收集 top logprobs 9. 返回 SamplerOutput4.6 spec_decode — 推测解码层核心作用spec_decode 模块实现推测解码Speculative Decoding通过先让轻量级 draft 模型生成候选 token再由目标模型并行验证在不损失质量的前提下加速推理。关键类/方法类文件说明EagleProposereagle.pyEagle/Eagle3 推测解码MedusaProposermedusa.pyMedusa 多头推测NgramProposerngram_proposer.pyCPU n-gram推测NgramProposerGPUngram_proposer_gpu.pyGPU n-gram推测SuffixDecodingsuffix_decoding.py后缀数组推测DFlashProposerdflash.pyDFlash 推测DraftModelProposerdraft_model.py基于独立 draft 模型SpecDecodeMetadatametadata.py批量推测解码元数据SpecDecodeMetricsmetrics.py接受率等指标extract_hidden_statesextract_hidden_states.py提取 draft 用的隐藏状态推测解码流程1. Proposer 生成 k 个 draft tokens 2. 将 draft tokens 与当前序列拼接 3. 一次 forward pass 并行验证所有位置 4. RejectionSampler: - 从左到右逐个验证 - 接受: draft token target distribution 样本 - 拒绝: 从 target distribution 重新采样 5. 输出: 接受的 token 补充采样的 token4.7 executor — 执行器层核心作用executor 模块负责创建和管理 Worker 进程是分布式推理的核心编排层。关键类/方法类文件说明Executorabstract.py抽象基类UniprocExecutoruniproc_executor.py单 GPU 进程MultiprocExecutormultiproc_executor.py多 GPU 进程spawnRayExecutorray_executor.pyRay 分布式执行RayExecutorV2ray_executor_v2.pyRay V2 APICUDAGraphDispatchercudagraph_dispatcher.pyCUDA Graph 捕获/重放调度Executor 抽象接口classExecutor(ABC):defdetermine_available_memory()-intdefinitialize_cache(num_gpu_blocks)defexecute_model(scheduler_output)-ModelRunnerOutputdefcollective_rpc(method,timeout,args)-list[Any]defcheck_health()-None执行器选择逻辑Executor.get_class(vllm_config): if isinstance(backend, type(Executor)): → 直接使用 elif backend ray: → RayExecutor elif backend mp: → MultiprocExecutor elif TP 1: → UniprocExecutor else: → MultiprocExecutor (default)4.8 pool — 池化模块核心作用pool 模块为池化任务Embedding、Classification提供元数据构建和晚交互评分。关键类/方法类/函数文件说明PoolingMetadatametadata.py批量池化元数据prompt_lens, token_ids, cursorPoolingCursormetadata.pyGPU 索引追踪器first/last token 位置PoolingStatesmetadata.py分块预填充隐藏状态缓存get_late_interaction_engine_index()late_interaction.pyCRC32 引擎路由compute_maxsim_score_batched()late_interaction.py批量 MaxSim 评分build_late_interaction_query_params()late_interaction.py构建 cache_query 参数build_late_interaction_doc_params()late_interaction.py构建 score_doc 参数详细分析见前一份 G-77-pool 报告4.9 structured_output — 结构化输出核心作用structured_output 模块确保模型输出符合预定义的格式约束JSON Schema、Regex、Grammar避免无效输出。关键类/方法类/函数文件说明StructuredOutputManagerinit.py管理结构化输出请求StructuredOutputRequestrequest.py单个请求的语法约束BackendXGrammarbackend_xgrammar.pyxgrammar 后端BackendOutlinesbackend_outlines.pyoutlines 后端BackendGuidancebackend_guidance.pyguidance 后端BackendLMFormatEnforcerbackend_lm_format_enforcer.pylm-format-enforcer 后端StructuredOutputGrammarbackend_types.py语法对象抽象工作原理1. 用户请求含 json_schema / regex / grammar 约束 2. StructuredOutputManager 创建对应后端的 Grammar 3. 每个 decode 步骤: Grammar → 允许的 token mask 4. Sampler 应用 mask: 只从允许 token 中采样 5. 保证输出始终符合约束4.10 kv_offload — KV缓存卸载核心作用kv_offload 模块实现KV Cache 的 CPU 卸载将不活跃的 KV blocks 从 GPU 转移到 CPU释放 GPU 内存以服务更多请求。关键类/方法类文件说明OffloadingManager(ABC)abstract.py卸载管理器抽象基类CPUOffloadManagercpu/manager.pyCPU 卸载实现LRUPolicycpu/policies/lru.pyLRU 淘汰策略ARCPolicycpu/policies/arc.pyARC 自适应淘汰策略SharedOffloadRegioncpu/shared_offload_region.py共享卸载区域OffloadMediumsmediums.py卸载介质抽象ReuseManagerreuse_manager.pyBlock 重用管理卸载操作lookup() → 查找已卸载的 block 链长度 prepare_load() → 准备加载保护 block 不被淘汰 touch() → 标记 block 为最近使用 complete_load() → 完成加载 prepare_store() → 准备存储可能触发淘汰 complete_store() → 完成存储block 可被加载4.11 metrics — 指标监控核心作用metrics 模块提供运行时指标收集和导出用于性能分析和监控。关键类/方法类/函数文件说明PrometheusMetricsprometheus.pyPrometheus 指标导出StatLoggerManagerloggers.py统计日志管理PerfStatsperf.py性能统计IterationStatsstats.py每步迭代统计SchedulerStatsstats.py调度器统计MetricsReaderreader.py指标读取5. 模块调用关系与数据流5.1 核心调用链AsyncLLM.generate() → InputProcessor.process() → Renderer.encode() → token_ids → SamplingParams.verify() → CoreClient.add_request(EngineCoreRequest) → [ZMQ msgpack] → EngineCore EngineCore.step() → Scheduler.schedule() → RequestQueue.pop() → KVCacheManager.allocate() → BlockPool.get_free_block() → Prefix cache match (hash lookup) → return SchedulerOutput → Executor.execute_model(SchedulerOutput) → GPUWorker.execute_model() → GPUModelRunner.execute_model() → InputBatch.add_request() → Model.forward(hidden_states, kv_caches) → AttentionBackend.forward() → Sampler.forward(logits) → LogitsProcessor → TopKTopP → sample → [optional] LateInteractionRunner.postprocess() → return ModelRunnerOutput → Scheduler.update_from_outputs() → 释放完成的请求 blocks → 构建完成请求列表 → [TensorIPC] → CoreClient → OutputProcessor → Detokenizer.decode() → LogprobsProcessor.format() → return RequestOutput → 用户5.2 模块间数据传递矩阵源模块目标模块数据结构传递方式AsyncLLMInputProcessorPrompt Params方法调用InputProcessorCoreClientEngineCoreRequestZMQ msgpackCoreClientEngineCoreEngineCoreRequestZMQ socketEngineCoreScheduler—直接调用SchedulerExecutorSchedulerOutput方法调用ExecutorWorkerSchedulerOutput进程间通信WorkerGPUModelRunnerscheduler_output方法调用GPUModelRunnerAttentionhidden_states kv_caches方法调用GPUModelRunnerSamplerlogits SamplingMetadata方法调用GPUModelRunnerPoolhidden_states PoolingMetadata方法调用SamplerGPU Sample opslogits tensorGPU kernelEngineCoreCoreClientEngineCoreOutputs GPU tensorsZMQ TensorIPCCoreClientOutputProcessorEngineCoreOutputs方法调用OutputProcessorAsyncLLMRequestOutputasyncio Event5.3 GPU 数据流单步执行SchedulerOutput │ ├─ new_reqs ──── InputBatch.add_request() │ → token_ids_cpu, seq_lens, block_ids │ → SamplingMetadata / PoolingMetadata 构建 │ ├─ cached_reqs ── InputBatch.update() │ → 复用已有 block_ids, 更新 num_computed_tokens │ └─ num_scheduled_tokens → 确定 forward batch 大小 Model.forward(input_ids, positions, kv_caches) │ ├─ hidden_states ──→ Attention.forward() │ │ │ ├─ Prefill: chunked_prefill_paged_decode │ └─ Decode: paged_attention │ └─ logits ──→ Sampler.forward() │ ├─ LogitsProcessor.apply() ├─ apply_all_penalties() ├─ TopKTopPSampler.forward() └─ 返回 SamplerOutput(token_ids, logprobs) [若 Pool 请求]: hidden_states ──→ PoolingRunner.pool() → F.normalize(last_hidden_states) → LateInteractionRunner.postprocess() → compute_maxsim_score_batched() (若晚交互) ModelRunnerOutput: ├── sampled_token_ids (GPU tensor) ├── logprobs (CPU numpy) ├── pooler_output (list[Tensor]) └── spec_decode_draft_ids (optional)

更多文章