1概述
decode 阶段数百次 kernel launch 让 CPU 反成瓶颈;vLLM 以 torch.compile 编译优化与 CUDA Graphs 两件武器叠加应对,CompilationMode × CUDAGraphMode 两个正交维度决定整条链路的形态。
在大批量 prefill 阶段,GPU 计算量巨大,CPU 启动 kernel 的开销可以被摊薄;而在小 batch decode 阶段,每生成一个 token 都要执行一次完整的模型前向——层数 × 每层数十个算子,动辄 数百个 kernel,每个 kernel 的 CPU 端 launch 成本(参数打包、驱动调用、Python/aten 分发)约数微秒,累加之后 CPU 成为瓶颈,GPU 大部分时间在"等米下锅"。
vLLM 的答案是两件武器叠加:torch.compile 编译优化(Dynamo 追踪 + AOTAutograd + Inductor 代码生成,配合自研图 pass 做算子融合)与 CUDA Graphs(把一串 kernel 的 launch 参数一次性录制进 graph,replay 时 CPU 只提交一次调用)。两者的结合点是 vllm/compilation/ 包:编译期把模型 FX 图按 attention 等动态算子切成多段(piecewise),静态段落各自包上 CUDAGraphWrapper 进图,动态段落留在图外逐次执行。
- 编译模式
CompilationMode(vllm/config/compilation.py):NONE(纯 eager)/STOCK_TORCH_COMPILE(原版 torch.compile)/DYNAMO_TRACE_ONCE(单次追踪、丢弃 guard)/VLLM_COMPILE(vLLM 定制后端,V1 引擎默认)。 - 图模式
CUDAGraphMode:NONE/PIECEWISE/FULL/FULL_DECODE_ONLY/FULL_AND_PIECEWISE(V1 默认优化等级O2下的取值,见vllm/config/vllm.py中OPTIMIZATION_LEVEL_02)。
CUDA Graph 与编译逻辑在代码上是正交的:full cudagraph 可以脱离 torch.compile 单独使用;而 piecewise cudagraph 依赖编译期分段(mode=VLLM_COMPILE 且非空 splitting_ops),是两者协作最深的一条路径。本文基于 main 分支 commit 5d55ef1590(2026-11)逐文件解析,全部代码引用均来自真实源码。
2背景与动机
三个前提决定了方案形态:launch 开销在 decode 阶段占主导、CUDA Graph 的静态 shape/静态地址硬约束,以及 attention 动态性对"整图一把梭"的否决。
🧮2.1 kernel launch 开销为何在 decode 阶段占主导
以一个 32 层的 dense 模型为例,单层前向包含 RMSNorm、QKV 投影、RoPE、attention、O 投影、MLP(约 4~8 个 GEMM)、残差相加等 15~25 个算子;换算成底层 kernel,一次 decode 前向通常产生 300 个以上的 kernel launch。当 batch 为 1~16 时,单个 GEMM 在现代 GPU 上只需 5~20 微秒,而一次 cudaLaunchKernel 及其上层的 Python → aten → dispatcher 开销约为 2~10 微秒——CPU 侧的发射时间与 GPU 侧的计算时间同量级,流水线被打穿,GPU 利用率显著下滑。
eager PyTorch 之下还有更多隐性开销:每个算子的 nn.Module.__call__ 钩子分发、tensor 元信息(shape/stride 推断)的反复计算、guard 检查等。torch.compile 能消掉其中一部分(把 Python 字节码降级为融合后的 Triton kernel),但只要仍然逐个 launch,驱动调用次数就不会减少。CUDA Graph 则从数量级上解决问题:录制时把整串 kernel 的启动参数与拓扑固化到 GPU 侧,replay 只需一次 cudaGraphLaunch。
📐2.2 CUDA Graph 的硬约束:静态 shape 与静态地址
CUDA Graph 录制的是"这一批 kernel、作用于这一批特定地址的缓冲区"。replay 时输入数据必须写入捕获时的同一块内存,shape 也必须完全一致,否则读到的是旧地址/越界数据。LLM 推理的 batch 却在每个 step 间随机变化,这就产生了根本矛盾。vLLM 的解法是 bucket padding(按桶填充):
- 预先选定一组捕获尺寸
cudagraph_capture_sizes,默认为[1, 2, 4] + range(8, 256, 8) + range(256, max+1, 16),上限默认 512(数据中心 Blackwell 为 1024),且被min(max_num_seqs × decode_query_len × 2, 上限)约束(见vllm/config/vllm.py的_set_cudagraph_capture_sizes逻辑); - 运行时把真实 batch 向上取整到最近的桶,空位用 padding 行填充,由
input_buffers.is_padding掩码标记,采样时只取前num_tokens行; - 超过最大桶的 batch 直接回退 eager(
CudagraphDispatcher.dispatch返回CUDAGraphMode.NONE)。
🔀2.3 为什么不能"整图一把梭":attention 的动态性
理想情况是把整个模型 forward 录成一张 FULL graph,launch 次数变成 1。但 prefill / chunked prefill / 混合批次中,attention 的 KV 长度、cu_seqlens、block table 都是数据相关的动态 shape,很多 attention 后端(如 FlashAttention 的 varlen 路径)在捕获期必须拿到确定的元数据。为此 vLLM 引入 AttentionCGSupport(vllm/v1/attention/backend.py)四级支持度:ALWAYS支持混合批次 full 图、UNIFORM_BATCH支持等长 query 批、UNIFORM_SINGLE_TOKEN_DECODE仅支持单 token decode、NEVER完全不支持。CompilationConfig.resolve_cudagraph_mode_and_sizes() 依据支持度自动降级图模式(例如 FULL → FULL_AND_PIECEWISE / PIECEWISE),这也是默认模式最终收敛到 FULL_AND_PIECEWISE(decode 走 FULL、prefill 走 PIECEWISE)的原因。
3架构与核心组件
整体链路分为编译期(启动时一次)与运行期(capture 一次、replay 无数次):左列 VllmBackend 流水线,右列 GPUModelRunner 的捕获与回放。
整体链路分为编译期(进程启动时执行一次)与运行期(capture 一次、replay 无数次)。编译期由 @support_torch_compile 装饰器(vllm/compilation/decorators.py)把模型 forward 交给 torch.compile(fullgraph=True, dynamic=False),后端 VllmBackend 接管 Dynamo 产出的 FX 图并完成"切图 → 分段编译 → 包 CUDAGraphWrapper → 生成拼接代码"。运行期由 GPUModelRunner 驱动 CudagraphDispatcher 决定每个 batch 使用哪张图。
🧩组件职责一句话版
- vllm/compilation/backends.py —
VllmBackend:torch.compile 后端总入口,负责切图、分段编译、缓存与包装; - vllm/compilation/piecewise_backend.py —
PiecewiseBackend:单个静态段的"多 shape 编译 + 运行期按 shape 分发"; - vllm/compilation/cuda_graph.py —
CUDAGraphWrapper:把任意 runnable 变成"按 BatchDescriptor 捕获/回放"的图包装器; - vllm/v1/cudagraph_dispatcher.py —
CudagraphDispatcher:运行期唯一决策者,输出 (runtime_mode, BatchDescriptor); - vllm/v1/worker/gpu_model_runner.py — 模型包装、warmup、捕获编排与 dummy run;
- vllm/v1/worker/gpu/cudagraph_utils.py —
CudaGraphManager/ModelCudaGraphManager:FULL 图捕获与显存预估。
4代码地图
vllm/compilation/ 编译包与执行侧的关键文件、类与职责全景——20 个文件全部来自真实源码,是后续机制详解的索引。
| 文件 | 关键类 / 函数 | 职责 |
|---|---|---|
| vllm/config/compilation.py | CompilationConfig, CUDAGraphMode, CompilationMode, PassConfig | 编译与图模式总配置:mode、cudagraph_mode、cudagraph_capture_sizes、max_cudagraph_capture_size、splitting_ops(_attention_ops 列表)、compile_sizes、cache_dir 等,以及 resolve_cudagraph_mode_and_sizes() 自动降级 |
| vllm/config/vllm.py | OPTIMIZATION_LEVEL_0X, _set_cudagraph_capture_sizes | 优化等级默认值(O0=NONE, O1=PIECEWISE, O2/O3=FULL_AND_PIECEWISE)与捕获尺寸自动生成 |
| vllm/compilation/backends.py | VllmBackend, CompilerManager, split_graph(), PiecewiseCompileInterpreter, wrap_with_cudagraph_if_needed() | torch.compile 定制后端:FX 切分、分段编译、缓存 hash/目录管理、CUDAGraph 包装、make_copy_and_call 输入拷贝 |
| vllm/compilation/piecewise_backend.py | PiecewiseBackend, RangeEntry, create_concrete_args() | 静态段子图按 compile_sizes/compile_ranges 多份编译,运行期按首个符号 shape 索引分发 |
| vllm/compilation/cuda_graph.py | CUDAGraphWrapper, CUDAGraphEntry, CUDAGraphOptions, CUDAGraphLogging | PIECEWISE 段的捕获/回放核心;输入地址 debug 校验;padding 统计表(Unpadded/Padded/Num Paddings) |
| vllm/compilation/breakable_cudagraph.py | BreakableCUDAGraphCapture, BreakableCUDAGraphWrapper, eager_break_during_capture | 免编译的"可断点"捕获:单一 capture 上下文在 attention 自定义算子处断流,eager 执行后继续录制(受 VLLM_USE_BREAKABLE_CUDAGRAPH=1 控制) |
| vllm/compilation/partition_rules.py | should_split(), inductor_partition_rule_context() | 判断 FX 节点是否为切分点;Inductor 侧分区规则注册(use_inductor_graph_partition=True 路径) |
| vllm/compilation/passes/ | PostGradPassManager, NoOpEliminationPass, RMSNormQuantFusionPass, ActivationQuantFusionPass, AllReduceFusionPass, AttnQuantFusionPass, FixFunctionalizationPass 等 | post-grad 图 pass:noop 消除、RMSNorm/SiluMul+quant 融合、allreduce+rms 融合、IR 降级与 functionalization 修复 |
| vllm/compilation/codegen.py | generate_execution_code(), compile_execution_fn() | 为 split 后的拼接图生成纯 Python 执行函数,消除 FX 解释器与 nn.Module.__call__ 开销 |
| vllm/compilation/caching.py | VllmSerializableFunction, StandaloneCompiledArtifacts | 编译产物序列化/加载(AOT、mega artifact、standalone compile) |
| vllm/compilation/wrapper.py | TorchCompileWithNoGuardsWrapper | 模型级 torch.compile 包装:guard 剥离、bytecode hook 直达编译产物、动态 shape 标记入口 |
| vllm/compilation/decorators.py | @support_torch_compile, Collision-detect 的 __init__ | 把模型类混入编译包装基类,声明 dynamic_arg_dims 动态维度 |
| vllm/compilation/cudagraph_pool.py | capture_pool(), capture_outside_cumem_pool() | graph pool 路由:sleep 模式下用 cuMem 池,并把 NCCL 的图分配器指向同一池 |
| vllm/compilation/monitor.py | set_cudagraph_capturing_enabled(), validate_cudagraph_capturing_enabled() | 全局"是否允许捕获"开关,捕获窗口外的任何捕获立即抛错 |
| vllm/compilation/counter.py | CompilationCounter | 编译/捕获计数(图数、后端编译数、cudagraph 捕获数等),供测试断言与日志 |
| vllm/v1/worker/gpu_model_runner.py | GPUModelRunner.load_model / capture_model / _warmup_and_capture / _dummy_run | 模型分层包装(FULL/Breakable/UBatch)、捕获编排、warmup、padding 掩码与 forward context |
| vllm/v1/cudagraph_dispatcher.py | CudagraphDispatcher.dispatch / initialize_cudagraph_keys / get_capture_descs | 维护 PIECEWISE/FULL 两套合法 BatchDescriptor 集合;运行期 padding 查表与模式决策 |
| vllm/v1/worker/gpu/cudagraph_utils.py | CudaGraphManager, ModelCudaGraphManager, profile_cudagraph_memory() | FULL 图捕获/回放、输出静态 buffer、FULL 图显存抽样外推预估 |
| vllm/v1/worker/encoder_cudagraph.py | EncoderCudaGraphManager, BudgetGraphMetadata | 多模态 ViT 编码器按 token budget 桶捕获,replay 前 in-place 更新输入 buffer |
| vllm/forward_context.py | BatchDescriptor, set_forward_context() | 前向上下文:向图包装器传递 (num_tokens, num_reqs, uniform, lora 状态) |
5核心机制详解
编译流水线四步、一段多形编译、图包装状态机、执行侧 padding 与捕获编排、FULL/PIECEWISE 对决、pynccl 入图、Breakable 图、encoder 图与编译缓存——九个小节逐个拆开。
🔧5.1 编译流水线:VllmBackend 如何改造 torch.compile
vllm/compilation/backends.pyCompilationConfig.init_backend() 在 mode=VLLM_COMPILE 时返回 VllmBackend 实例。Dynamo 完成字节码追踪后调用其后端入口 __call__(graph, example_inputs),流程依次为:
- 计算缓存 hash 并建目录:四类因子
env_hash + config_hash + code_hash + compiler_hash做 SHA-256 取前 10 位,得到cache_dir = $VLLM_CACHE_ROOT/torch_compile_cache/<hash>,每个进程再细分rank_{rank}_{dp_rank}/<prefix>;目录内落盘cache_key_factors.json、computation_graph.py(split 后图的可读版本)、vllm_compile_cache.py(AOT artifact 索引)。 - 切图
split_graph(graph, fx_split_ops):遍历 FX 节点,should_split(node, splitting_ops)(partition_rules.py)命中切分算子时开新子图;连续的切分算子归入同一"splitting graph";_decompose_size_nodes()把x.size()拆成逐维sym_size.int以便跨段传递;_merge_empty_only_subgraphs()把只含空分配的段落并回前段;最终torch.fx.passes.split_module.split_module(..., keep_original_order=True)产出submod_0, submod_1, ...序列。 - 分段编译:
PiecewiseCompileInterpreter(一个torch.fx.Interpreter)在假想输入上"跑"一遍拼接图,对每个非切分子模块构造PiecewiseBackend并立刻完成所有 range/size 的编译,再用wrap_with_cudagraph_if_needed()包上平台相关的静态图包装器(默认CUDAGraphWrapper,平台可用current_platform.get_static_graph_wrapper_cls()替换,见base_static_graph.py的AbstractStaticGraphWrapper协议)。 - 生成执行代码:
codegen.generate_execution_code(split_gm)产出等价于拼接图的纯 Python 函数源码(含 liveness 分析驱动的del及时释放中间量),经compile_execution_fn编译后作为VllmSerializableFunction.optimized_call返回给 Dynamo。
CompilationConfig._attention_ops 是 piecewise 模式的默认切分集合,涵盖 vllm::unified_attention_with_output、vllm::unified_mla_attention_with_output、vllm::mamba_mixer2、vllm::short_conv、vllm::linear_attention、vllm::qwen_gdn_attention_core、vllm::sparse_attn_indexer、vllm::deepseek_v4_attention、vllm::step5_csa_attention 等动态算子;set_splitting_ops_for_v1() 还会追加 vllm::unified_kv_cache_update / vllm::unified_mla_kv_cache_update(其字符串参数妨碍 Inductor 复用图)。注意 splitting_ops 不等于集合通信:NCCL allreduce 默认留在图内(见 5.6)。
另一条路径是 use_inductor_graph_partition=True(需 torch ≥ 2.9):不再在 Dynamo FX 层预切,而是把切分算子注册进 Inductor 的 custom_should_partition_ops(inductor_partition_rule_context()),让所有 pass 与融合先作用于完整图,在 Inductor codegen 末段才分区——N 个 cudagraph-unsafe 算子产生 N+1 个分区,同一份编译结果同时服务 full 与 piecewise 两种图模式。
🧬5.2 PiecewiseBackend:一段多形
vllm/compilation/piecewise_backend.py每个静态段并不是只编译一次。CompilationConfig.compile_sizes(可含 "cudagraph_capture_sizes" 字面量,由 post_init_cudagraph_sizes() 展开)与 compile_ranges_endpoints 共同决定编译范围集合:单尺寸用 create_concrete_args() 把符号 shape 实例化为具体 size(Inductor 可做完全静态优化),区间则用 get_fake_args_from_graph() 的符号假想输入编译通用 shape 版本。每个 Range 对应一个 RangeEntry(compile_range, compiled, runnable)。运行期 __call__ 从 sym_shape_indices[0] 读出真实 batch,_find_range_for_shape() 先精确匹配单尺寸、再回退到覆盖区间,然后调用对应的 runnable——这就是"图按桶 padding,编译产物也按桶对齐"的实现层。
🎬5.3 CUDAGraphWrapper:捕获与回放的状态机
vllm/compilation/cuda_graph.pyCUDAGraphWrapper 是 PIECEWISE 段的图容器。初始化时通过 current_platform.get_global_graph_pool() 绑定全局共享 graph pool(多张图共用一块内存池,小图复用大图已分配的块)。每次调用时:
forward_context = get_forward_context() batch_descriptor = forward_context.batch_descriptor cudagraph_runtime_mode = forward_context.cudagraph_runtime_mode if cudagraph_runtime_mode == CUDAGraphMode.NONE or cudagraph_runtime_mode != self.runtime_mode: return self.runnable(*args, **kwargs) # 模式不匹配:透传 eager entry = self.concrete_cudagraph_entries[batch_descriptor] # 首见则新建 if entry.cudagraph is None: # ... capture 路径 with torch.cuda.graph(cudagraph, pool=graph_pool, stream=current_stream()): output = self.runnable(*args, **kwargs) entry.output = weak_ref_tensors(output) else: entry.cudagraph.replay() # replay 路径 return entry.output
几个精巧细节:(1)运行模式由 forward context 注入,包装器"盲信"外部决策,因此 FULL 外层图与 PIECEWISE 内层图可以嵌套共存;(2)输出统一 weak_ref_tensors,让 PyTorch 的 cudagraph pool 在捕获结束后立刻回收输出内存(仅最后一段开启,中间段输出还要被后段消费);(3)CUDAGraphOptions 区分段位:第一段负责日志、非首段禁用 gc(piecewise 逐段捕获时反复 gc.collect() 会拖慢捕获);(4)DEBUG 级别下记录捕获时所有输入的 data_ptr(),replay 前断言地址不变,捕捉静态缓冲被换掉的隐性 bug;(5)捕获合法性由 monitor.validate_cudagraph_capturing_enabled() 把关——capture_model() 之外的任何捕获都会立即 RuntimeError。
显式输入拷贝是可选项:cudagraph_copy_inputs=True 时,make_copy_and_call() 把符号 shape 输入克隆成静态 buffer,每次调用先 copy_ 再进图;V1 主路径则由模型 runner 的 input_ids.gpu[:num_tokens_padded] 等预分配缓冲直接保证地址稳定,无需拷贝。
🎛️5.4 执行侧:调度、padding 与捕获编排
vllm/v1/worker/gpu_model_runner.pyvllm/v1/cudagraph_dispatcher.py决策中枢是 CudagraphDispatcher:initialize_cudagraph_keys() 在 attention 后端初始化后,用 cudagraph_capture_sizes × lora_cases 笛卡尔积生成全部合法 BatchDescriptor(PIECEWISE 段还会放宽 num_reqs=None 以覆盖任意请求数);_compute_bs_to_padded_graph_size() 预计算"真实 batch → 桶 size"的查表数组。运行期 dispatch() 依次尝试 FULL 精确键、PIECEWISE 放宽键,都不命中则 NONE。
捕获编排在 GPUModelRunner.capture_model():
set_cudagraph_capturing_enabled(True)打开捕获窗口,进入graph_capture(device)(TP 组内 rank 同步,防止集合通信死锁);- 按
get_capture_descs()返回的顺序:PIECEWISE 先、FULL 后,组内大尺寸先——PIECEWISE 段激活更大,先捕获可以让 FULL 的激活塞进池中已分配的空闲块,显著省显存; - 每个描述符执行
_warmup_and_capture():先以CUDAGraphMode.NONE跑cudagraph_num_of_warmups次 warmup(触发 FlashInfer 自动调优、懒初始化等副作用),synchronize后再以真实模式跑一次_dummy_run(..., is_graph_capturing=True)完成录制,期间input_buffers.is_padding.fill_(True)把假数据标记为 padding; - 日志输出
Graph capturing finished in %.0f secs, took %.2f GiB(典型 5~20 秒),compilation_counter.num_cudagraph_captured记账。
模型侧的分层包装发生在 load_model():FULL_AND_PIECEWISE 时模型外层套 CUDAGraphWrapper(runtime_mode=CUDAGraphMode.FULL);若开启 VLLM_USE_BREAKABLE_CUDAGRAPH=1,则再套一层 BreakableCUDAGraphWrapper(runtime_mode=CUDAGraphMode.PIECEWISE)。运行时每一步通过 set_forward_context(..., cudagraph_runtime_mode=..., batch_descriptor=...) 把决策广播给所有包装器——FULL 步只有外层包装器动手,PIECEWISE 步外层透传、内层各段捕获/回放。
FULL 图的输出管理在 ModelCudaGraphManager(vllm/v1/worker/gpu/cudagraph_utils.py):捕获时 store_capture_output() 把 hidden_states 拷进首次分配的持久 buffer(池外),run_fullgraph() replay 后按 desc.num_tokens 切片返回,上层(采样器)从不触碰图池内存。启动期的 profile_cudagraph_memory() 只抽样捕获 2 张最大 FULL 图(_FULL_GRAPH_PROFILING_SAMPLES=2),按"首图建池基线 + 后续每图边际开销"外推总量,从而在 KV cache 分配前预留显存余量。
⚖️ 5.5 FULL 与 PIECEWISE 的对决(两种图模式对比)
| 维度 | FULL(整模型一张图) | PIECEWISE(分段图) |
|---|---|---|
| 覆盖范围 | 整个 forward(含 attention),launch 次数 = 1 | 每层 2 段左右静态图 + attention 图外 eager,约数十次 launch |
| 对 attention 要求 | 后端须 AttentionCGSupport.ALWAYS/UNIFORM_*,元数据需捕获兼容(for_capture=True) | 任意后端;attention 以真实 shape 逐次执行(for_capture=False) |
| 适用批次 | uniform decode(默认);混合批次需 ALWAYS 支持 | prefill / chunked prefill / 混合批次 |
| 需 padding 的维度 | num_tokens 与 num_reqs(FA3 scheduler_metadata 依赖请求数) | 仅 num_tokens(num_reqs=None 放宽) |
| 实现载体 | CudaGraphManager.graphs[desc] / 外层 CUDAGraphWrapper | 编译期分段 + 每段一个 CUDAGraphWrapper |
| 典型组合 | 默认 FULL_AND_PIECEWISE:decode 走 FULL、prefill/混合走 PIECEWISE;FULL_DECODE_ONLY 省显存(P/D 部署的 decode 实例) | |
📡5.6 集合通信与图:pynccl 可捕获
TP/EP 场景的 allreduce/all-gather 默认留在图内。vLLM 的 NCCL 封装(pynccl)使用 graph-safe 模式,捕获时通过 cudagraph_pool.capture_pool() → set_graph_pool_id(pool) 把 NCCL 的图内存分配器与 vLLM 的全局 graph pool 对齐,保证集合通信 kernel 与普通 kernel 共享同一池、可在 torch.cuda.graph() 上下文中录制。cudagraph_pool.py 还为 sleep 模式(显存休眠卸载)提供 cuMem 池路由,并用 capture_outside_cumem_pool() 让显存 profiling 的丢弃式捕获绕开 cuMem 以便正常释放。融合 pass AllReduceFusionPass(flashinfer trtllm allreduce + RMSNorm + quant)进一步把通信与后续计算压进单个 kernel。通信与图协同的完整机制留待系列第 13 篇展开。
✂️5.7 Breakable CUDA Graph:免编译的可断点图
传统 piecewise 依赖 torch.compile 切图;受 sglang 启发的 BreakableCUDAGraphCapture 提供了第二条路:单个 capture 上下文驱动整个 forward,attention 等 custom op 通过 @eager_break_during_capture 装饰器在 dispatcher 层被拦截——结束当前图段、在捕获流上 eager 执行该算子、再开启新图段。最终产物是 segments: list[Callable](图段的 graph.replay 与 eager 段的闭包交替),replay 按序调用。约束是被装饰算子必须写入调用方提供的输出 tensor(地址稳定),且装饰器必须置于最外层(避免把 PD 分离的 host 副作用录进图)。该路径由 VLLM_USE_BREAKABLE_CUDAGRAPH=1 启用,对未实现 @support_torch_compile 的模型也能享受 piecewise 图收益。
🖼️5.8 多模态编码器也有图
EncoderCudaGraphManager 面向 ViT 等 vision encoder:CompilationConfig 中 cudagraph_mm_encoder 开关 + encoder_cudagraph_token_budgets(缺省从模型预算范围按 2 的幂自动推断)。每个 budget 捕获一张图,元数据 BudgetGraphMetadata 记录 in-place 更新的输入 buffer(embedding、cu_seqlens 等)与输出 buffer;运行时把图片/视频帧 greedy 装箱进最小的合适 budget,replay 前把预算值写入 buffer、replay 后从输出 buffer 读回结果——与 decode 图相同的"静态地址 + 预先填充"哲学。
💾5.9 编译缓存:冷启动的救星
CompilerManager 持有 dict[(Range, graph_index, backend_name), artifact],底层 compiler 由 make_compiler() 选择:InductorAdaptor(默认)、InductorStandaloneAdaptor(VLLM_USE_STANDALONE_COMPILE + torch 有 standalone_compile)或 EagerAdaptor,亦支持平台自定义 CompilerInterface 实现(compiler_interface.py)。它还做了一层"同构图去重"优化:monkey-patch autograd_cache_key,后端缓存命中时抛出 StopCompiling 提前返回,直接复用内存中已存在的等价 artifact,省去重复的磁盘 IO。缓存键包含被追踪源码文件内容(traced_files),因此改一行模型代码就会换缓存目录,不会串味。
6动画演示
三组循环动画分别演示:CPU 时间线上的逐 kernel launch 与整图 replay(对应 2.1)、piecewise 切分后绿段进图/红段图外(对应 5.1)、以及 capture → warmup → replay 的图生命周期(对应 5.3 / 5.4)。
下排绿色块 = 同一批 kernel 作为一个 CUDA Graph 一次回放;绿色短条 = CPU 占用骤降,GPU 依靠图中固化的拓扑自主推进。动画循环展示两种模式的同一 decode step。
split_graph() 切出的静态段,由 CUDAGraphWrapper 捕获为 CUDA Graph(replay 一次即可);红色框 = 命中 _attention_ops 的切分段(should_split() 为真),每层都在图外以真实动态 shape eager 执行;黄色框 = 前后处理。虚线从左到右为一次 forward 的执行顺序,循环演示 32 层中截取的 3 层。_warmup_and_capture() 与 CUDAGraphWrapper.__call__ 的状态机——先以 CUDAGraphMode.NONE 做 warmup(触发懒初始化/自动调优),再进入 torch.cuda.graph() 上下文录制一次;此后每个同 BatchDescriptor 的 batch 直接 replay(),右侧计数器演示连续命中。循环重新开始代表换一个新的 batch 桶(新的 BatchDescriptor)重新走一轮。7设计亮点与权衡
五个设计亮点、六项权衡代价与一份调优速查。
7.1 设计亮点
- 亮点正交分层:编译(CompileMode)与图(CUDAGraphMode)解耦,forward context 作为两者之间的唯一通信信道;FULL/PIECEWISE 包装器可嵌套,平台可替换静态图实现(
AbstractStaticGraphWrapper协议)。 - 亮点共享 graph pool + 捕获顺序:所有图共用全局池,且按"PIECEWISE 先、大尺寸先"捕获,后捕获的图大量复用先前的显存,把几十张图的额外显存压到最低;输出一律 weak-ref,让池在捕获间隙回收中间量。
- 亮点失败安全:全局捕获开关(
set_cudagraph_capturing_enabled)把"意外捕获"(如某算子在服务期偷偷开图)变成立即报错而非静默错误;DEBUG 模式的输入地址断言同理。 - 亮点编译产物的多形分发:
PiecewiseBackend同时维护单尺寸(全静态、Inductor 满血优化)与区间(通用 shape)两档编译产物,精度与灵活性按需取用。 - 亮点可观测性:
CUDAGraphLogging汇总 Unpadded/Padded Tokens 与 padding 次数的统计表,CompilationCounter提供全链路计数,可直接用于回归测试断言(counter.expect())。
7.2 权衡与代价
| 权衡点 | 收益 | 代价 / 风险 |
|---|---|---|
| 桶 padding(静态 shape) | 任意 batch 命中图,replay 零 launch 开销 | padding 行浪费算力(桶间距 8/16);CUDAGraphLogging 可观测 padding 率;超过最大桶直接 eager |
| 多尺寸 × 多模式 × LoRA 特化捕获 | decode/prefill/LoRA 各得其所,cudagraph_specialize_lora 免去无 LoRA 时的额外计算 | 捕获数量膨胀(尺寸 × lora_cases × 模式),启动时间与显存随之上升;Mamba 还需校验 cache block 数量 |
| graph 显存占用 | 近乎消除 CPU 瓶颈 | 捕获期实测可达数 GiB,需要 profile_cudagraph_memory() 抽样外推预留;显存紧张时用户常需调低 max_cudagraph_capture_size 或 enforce_eager |
| 启动时间(warmup+编译+捕获) | 稳态吞吐/延迟大幅提升 | 典型 5~20 秒捕获 + 首次编译数十秒;靠 torch_compile_cache 与 AOT artifact 缓存把二次启动压回个位数秒 |
| piecewise vs full | piecewise 兼容任意 attention 后端与混合批次 | 每层仍有 1~2 次 eager 段的 CPU 开销;full 图则要求后端 AttentionCGSupport 达标并 padding num_reqs |
guard 剥离(skip_all_guards_unsafe) | Dynamo 永不重编译,单次追踪 | 要求模型 forward 无数据依赖控制流;违反时只能在 evaluate_guards 调试模式暴露 |
⚙️7.3 调优速查
mode=VLLM_COMPILE,cudagraph_mode=FULL_AND_PIECEWISE,backend="inductor"(平台可改),splitting_ops=attention 算子集enforce_eager 或 -cc.mode=none -cc.cudagraph_mode=none(等价 O0)-cc.cudagraph_mode=none:跑 Inductor 融合但不捕获图-cc.cudagraph_capture_sizes=[1,2,4,8,...] 显式覆盖默认序列$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_i_j/<prefix>,VLLM_CACHE_ROOT 默认 ~/.cache/vllmdebug_dump_path 配合 depyf 落盘 computation_graph.py / transformed_code.py;VLLM_LOGGING_LEVEL=DEBUG 开启输入地址校验8小结
一套协同的静态化流水线,围绕 CUDA Graph 的两大硬约束展开,并且可回退、可观测、可缓存。
CUDA Graphs 与 torch.compile 在 vLLM 中不是两个孤立开关,而是一套协同的静态化流水线:@support_torch_compile 把模型交给 Dynamo,VllmBackend 在 AOT 层接管 FX 图,按 _attention_ops 切出静态段;PiecewiseBackend 为每段产出多 shape 编译产物,CUDAGraphWrapper 再把每段变成按 BatchDescriptor 索引的可回放图;运行期 CudagraphDispatcher 用 padding 查表把任意 batch 映射到"FULL 精确图 → PIECEWISE 放宽图 → eager"三级降级路径。全套机制围绕 CUDA Graph 的两大硬约束(静态 shape、静态地址)展开:桶尺寸序列与 is_padding 掩码解决前者,全局共享 graph pool、持久输入/输出 buffer 与 weak-ref 内存管理解决后者。
工程上的成熟度同样值得学习:捕获窗口全局开关、输入地址断言、显存抽样外推、捕获顺序优化、多层编译缓存(env/config/code/compiler 四重 hash)、以及 BreakableCUDAGraph 与 encoder 图这类覆盖长尾场景的备选路径,共同把"高风险的图优化"做成了可回退、可观测、可缓存的默认能力。这也解释了为什么 V1 引擎敢把 FULL_AND_PIECEWISE 设为 O2 默认——在绝大多数模型与硬件组合上,它是净收益。