1概述
NCCL 是 vLLM 多卡/多机推理的通信底座;vLLM 没有把通信全部丢给 torch.distributed,而是自建了一套按消息尺寸 / 世界大小 / 硬件拓扑动态分发的通信网络。
NCCL(NVIDIA Collective Communications Library)是 vLLM 在 NVIDIA GPU 多卡/多机 场景下的通信底座:张量并行(TP)的 all_reduce、all_gather 与 reduce_scatter、专家并行(EP)的 all-to-all、流水线并行(PP)的隐状态 send/recv、乃至与外部训练器之间的权重热更新,底层都由 NCCL 承载。但 vLLM 并不直接把所有通信丢给 torch.distributed:它在 vllm/distributed/device_communicators/ 下自建了一条 纯 Python ctypes 封装(PyNcclCommunicator + NCCLLibrary),配合 custom_all_reduce.py、symm_mem.py 等替代后端,构成一张按 消息尺寸 / 世界大小 / 硬件拓扑 动态分发的通信网络。
本篇从真实代码出发,穷举 vLLM 中所有使用 NCCL 的场景:封装层的设计动机(stream 级控制、CUDA Graph 捕获安全、独立 world)、CudaCommunicator.all_reduce 的真实分发逻辑、12 类触发场景的调用链,以及 ROCm(RCCL)/XPU(xccl)/CPU(gloo) 多平台差异。所有结论均标注真实文件路径与行号,可直接对照源码验证。
🧭本篇阅读路线
- 只想知道"我的 all_reduce 走了哪条路":直读场景 2 + 动画 3,再看启动日志
_log_all_reduce_backend_selection - 关心 CUDA Graph 里通信为什么不炸:场景 7 + 封装层设计要点 2(流控制)
- 要做在线权重热更新 / 与 JAX trainer 对接:场景 11 + 封装层设计要点 3(独立 world)
- 排障与调优:场景 9(环境变量)+ 场景 13(排查速查表)
- 想快速建立全局感:先看图 13-1 调用栈分层 + 动画 1,再回来按场景精读
- 关心 ROCm / XPU / CPU 差异:场景 10 一张表讲完,另见第 7 节末尾的平台视角
2背景与动机:推理引擎为什么需要 NCCL
推理引擎的两个刚性约束——每 token 都在关键路径上、CUDA Graph 里不能有任何"非法调用"——决定了 vLLM 对 NCCL 的使用方式:按尺寸精确分工,而非全盘托付。
NCCL 是什么
NCCL 是 NVIDIA 提供的集合通信库,实现了 all_reduce / broadcast / reduce_scatter / all_gather / send / recv 等原语,并针对硬件拓扑自动选择算法:单机 NVLink 上用 Ring 环形规约或 NVLS(NVLink SHARP,交换机内归约),跨机走 InfiniBand/RoCE 的 Ring / Tree / CollNet。它的 API 是 C 接口,每个原语都以 cudaStream_t 结尾——即 NCCL 是一个 纯异步、流式 的库:调用立即返回,计算在指定流上排队执行,通信期间 CPU 完全自由。
推理引擎的两个刚性约束
⏱️约束一:每 token 都在关键路径上
训练中一次 all_reduce 对应几百个 token 的梯度;而 vLLM 解码阶段每次 forward 的 TP all_reduce 只搬运当前 step 的激活值——消息小(几 KB 到几百 KB)、频率极高(每个 Transformer 层一次)。此时集合通信的启动延迟比带宽更重要,这正是 CustomAllreduce(IPC + P2P 单跳)与对称内存(NVLS)被引入的原因:小消息根本不必走 NCCL 的通用路径。反过来,大模型 TP>8 或多机时单条消息可达数十 MB,此时 NCCL 的带宽调度又无可替代——所以 vLLM 的选择不是"用不用 NCCL",而是按尺寸精确分工。
🎬约束二:CUDA Graph 里不能有任何"非法调用"
vLLM V1 的解码靠 CUDA Graph 消除 CPU 开销,捕获期间所有 GPU 工作必须只提交到捕获流,且禁止同步类 API(cudaStreamSynchronize、事件查询等)。torch.distributed.all_reduce 在 NCCL 之上叠了不少潜在同步 API,历史上无法安全入图——这就是 pynccl_wrapper.py 文件头注释里记录的动机:试过 cupy(初始化易卡死)、试过 torch.distributed(含图捕获禁用的 CUDA API,见 PyTorch 官方论坛讨论),也否决了 C/C++ 绑定(每换一个 NCCL 版本都要重新编译,见 NVIDIA/nccl#1234)。最终方案是 纯 Python ctypes 绑定:换库只需改 VLLM_NCCL_SO_PATH 环境变量,零重编译。
NCCL 的执行模型:vLLM 视角
| 概念 | 含义 | vLLM 中的对应 |
|---|---|---|
communicator(ncclComm_t) | 一次 ncclCommInitRank 的产物,绑定一个 world 与探测好的拓扑(通道、算法) | c10d 组内嵌一个;每个 TP/DP/EP 组各建一个 PyNcclCommunicator;PP 旁路与权重热更新再建独立若干个 |
unique id(ncclUniqueId) | 128 字节会合令牌,rank 0 调 ncclGetUniqueId 生成,经带外通道发给全员 | 经 gloo 组 dist.broadcast(pynccl.py:157)或 StatelessProcessGroup.broadcast_obj;跨进程时以 base64 传递(场景 11) |
stream(cudaStream_t) | 每个原语的最后一个参数,决定 kernel 入哪个流——NCCL 自己不创建流 | pynccl 全部原语缺省 current_stream();图捕获期间即捕获流(场景 7 的全部秘密) |
group(ncclGroupStart/End) | 把多个调用合并为一次拓扑调度,典型用于变长集合与批量 p2p | all_gatherv / reduce_scatterv / all_to_all_single / batch_isend_irecv 以及 EPLB 专家搬运 |
| window(用户缓冲注册) | ncclCommWindowRegister 把用户显存注册进通信器,启用 NVLS 零拷贝 | pynccl_allocator.py 的对称内存池 + register_comm_window_raw(场景 8) |
| 算法(Ring/Tree/NVLS/GIN) | NCCL 内部按消息尺寸与拓扑自动选择,可用环境变量干预 | pin_nccl_env 精细 pin;BatchInvariant 强制单通道 Tree(场景 9);GIN 用作 DeepEPv2 的能力探针(场景 6) |
为什么还需要"独立 world"
PyTorch 的 ProcessGroup 由全局 world 划分而来,而 vLLM 有几类通信需要完全独立的 NCCL communicator:权重热更新要与外部 trainer(JAX/PyTorch)组成一个与推理 TP 无关的 world;EPLB 专家再平衡要按专家粒度收发;Elastic EP 新 worker 通过 128 字节的 ncclUniqueId 带外加入,不经过 TCPStore 握手。这些场景都由 PyNcclCommunicator(必要时用 from_unique_id_bytes 构造)实现,互不干扰——这是自建封装相对 c10d 的核心增量能力之一。
3NCCL 封装层架构(调用栈分层)
vllm/distributed/vllm/distributed/device_communicators/整个调用栈自上而下分六层,一次 TP 解码 all_reduce 从模型层一路下探到 NVLink/NVSwitch 与 InfiniBand 硬件。
整个调用栈自上而下分六层。以 TP 解码一次 all_reduce 为例:RowParallelLinear.forward 调用 communication_op.tensor_model_parallel_all_reduce;由于 CUDA 平台 use_custom_op_collectives() 返回 True(platforms/cuda.py:712),GroupCoordinator.all_reduce 走 torch.ops.vllm.all_reduce(input_, group_name=...) 自定义 op(为了 torch.compile 可追踪、CUDA Graph 可捕获),再按 group name 查回 GroupCoordinator,交给 CudaCommunicator.all_reduce 做按尺寸分发;命中 NCCL 路径时进入 PyNcclCommunicator.all_reduce,由 NCCLLibrary 直接调 libnccl.so.2 的 C 符号,把工作提交到当前流(图捕获时即捕获流),最终由 NVLink/NVSwitch 或 IB 硬件完成传输。
封装层三个关键设计
🔌1. 纯 ctypes 绑定,而非扩展模块 device_communicators/pynccl_wrapper.py
NCCLLibrary 用 ctypes.CDLL(so_file) 加载 find_nccl_library()(vllm/utils/nccl.py)找到的库——CUDA 下 libnccl.so.2、ROCm 下 librccl.so.1、或 VLLM_NCCL_SO_PATH 指定路径;按 exported_functions 表逐个绑定 C 符号并设置 restype/argtypes,调用后统一过 NCCL_CHECK(结合 ncclGetErrorString + ncclGetLastError 抛出可读错误)。可选符号做缺符号容忍:ROCm 上 ncclCommWindowRegister、ncclCommSuspend/Resume 缺失时跳过而不是在图捕获中抛异常(pynccl_wrapper.py:437)。ncclDataTypeEnum 维护 torch dtype → NCCL dtype 的映射,含 fp8_e4m3(ncclFloat8e4m3)。
# pynccl_wrapper.py:184 NCCLLibrary.exported_functions(节选,真实签名) Function("ncclCommInitRank", ncclResult_t, [ctypes.POINTER(ncclComm_t), ctypes.c_int, ncclUniqueId, ctypes.c_int]), Function("ncclAllReduce", ncclResult_t, [buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ncclRedOp_t, ncclComm_t, cudaStream_t]), Function("ncclGroupStart", ncclResult_t, []), Function("ncclCommWindowRegister", ncclResult_t, [ncclComm_t, buffer_type, ctypes.c_size_t, ctypes.POINTER(ncclWindow_t), ctypes.c_int]), Function("ncclCommSuspend", ncclResult_t, [ncclComm_t, ctypes.c_int]),
🌊2. 流控制与图捕获安全 device_communicators/pynccl.py
每个原语签名都带 stream=None 参数,缺省取 current_stream()——这是全部图安全性的来源:NCCL 只是往调用者给的流上 enqueue kernel,捕获期间它就是往捕获流 enqueue,不产生任何 CPU 侧同步。初始化时(_init_comm)做一次单元素 all_reduce 热身并 stream.synchronize()(pynccl.py:191),把惰性初始化的内部缓冲在图捕获之前分配掉。构造函数强制挂在非 NCCL 的 group 上(pynccl.py:114 的 assert):unique id 由 rank 0 经 gloo 广播,设备通信与元数据通道彻底分离。销毁同样讲究:ncclCommDestroy 是集体调用会自死锁,所以 destroy() 在 daemon 线程里调 ncclCommAbort 并限时 5 秒,让主线程先行释放 CUDA Graph(pynccl.py:250)。
🪟3. NCCL window / 用户缓冲区注册 device_communicators/pynccl_allocator.py
这是 NCCL 对称内存 的基础设施:用 load_inline 现场编译一段调用 ncclMemAlloc/ncclMemFree 的 C 代码,包装成 CUDAPluggableAllocator 插件;get_nccl_mem_pool() 基于它建一个 torch.cuda.MemPool。nccl_symm_mem_context 进入时切到该池分配(得到 NCCL 管理的对齐显存),退出时对新出现的段调用 register_comm_window_raw(segment.address, total_size)——即 ncclCommWindowRegister,把用户缓冲注册进通信器,NCCL 才能启用 NVLS 零拷贝路径;图捕获中还要先暂停 CUDA Graph 内存池(细节见场景 7)。门控:VLLM_USE_NCCL_SYMM_MEM(默认关)+ NCCL ≥ 2.27.3 + world_size > 1 + torch ≥ 2.8 + allocator 编译成功。
三类 NCCL 通信器并存
一个生产部署里同时活跃的 NCCL communicator 往往不止一个,它们的关系容易混淆,列表如下:
| 通信器 | 建立方式 | world | 典型用途 | 销毁 |
|---|---|---|---|---|
c10d ProcessGroupNCCL(device_group) | init_distributed_environment → new_group(backend="nccl") | 全局 world 的子集 | 冷路径 broadcast/gather、兜底 all_reduce、XPU/CPU 之外平台的基类实现 | 随进程组生命周期 |
PyNcclCommunicator(每组一个) | CudaCommunicator.__init__ 手工 ncclCommInitRank | 与组同员但独立成域 | 热路径 TP/EP 集合通信、图捕获、EPLB 搬运 | destroy():daemon 线程 + 5s 超时 ncclCommAbort |
| 旁路/外部通信器 | make_sibling_device_group(PP);from_unique_id_bytes(trainer) | 与 PP 组同员;或 trainer+vLLM 混合 | PP 采样 token 广播、权重热更新 | 会话式 shutdown() / 随组销毁 |
PyNccl 与 c10d-NCCL:什么时候用哪个
| 维度 | c10d ProcessGroupNCCL | PyNcclCommunicator |
|---|---|---|
| 建立方式 | init_process_group / new_group(backend="nccl"),由 torch 管 unique id | 手工 ncclCommInitRank,unique id 自己经 gloo 广播(pynccl.py:145) |
| CUDA Graph | 调用栈中含潜在同步 API,不可安全捕获(封装层注释记录的历史问题) | 纯 enqueue,可捕获;全靠 stream 参数 |
| stream 控制 | 内部流,用户不直接控制 | 每个原语显式 stream 参数(旁路流场景必需) |
| 变长原语 | 无 reduce_scatterv/all_gatherv | grouped ncclReduce / ncclBroadcast 组合实现 |
| 错误处理 | torch 层包装,细节常丢失 | NCCL_CHECK 直拼 ncclGetErrorString + ncclGetLastError |
| 生命周期 | 随 ProcessGroup,不可干预 | suspend/resume/abort 逐阶段管理 |
| 典型用途 | 冷路径 broadcast/gather、对象广播、兜底 all_reduce | 热路径 TP/EP 集合通信、图捕获、独立 world |
PyNcclCommunicator 的生命周期
| 阶段 | 动作 | 代码位置 |
|---|---|---|
| 会合 | rank 0 ncclGetUniqueId → 经 gloo 组广播 128 字节 id | pynccl.py:145-162 |
| 建组 | ncclCommInitRank(在目标 device 上下文中) | pynccl.py:180 |
| 热身 | 单元素 all_reduce + stream.synchronize(),预分配惰性缓冲;ROCm 弹性 EP 下可延迟 | pynccl.py:189;pynccl.py:38 |
| 注册(可选) | 对称池分配 + ncclCommWindowRegister | pynccl_allocator.py:134 |
| 服务 | 各原语 @current_stream();grouped 组合批量提交 | pynccl.py:273-676 |
| 挂起(可选) | ncclCommSuspend(comm, 0x01) 释放通信显存、保留拓扑 | pynccl.py:643 |
| 销毁 | daemon 线程限时 5s 调 ncclCommAbort(避免与图销毁互等) | pynccl.py:250-271 |
4代码地图
NCCL 相关的 28 个核心文件:从 ctypes 绑定层、分发枢纽、替代后端,到 EPLB / 权重热更新 / sleep 等外围挂钩,一张表定位全部职责。
| 文件 | 核心类 / 函数 | 职责 |
|---|---|---|
device_communicators/pynccl_wrapper.py | NCCLLibrary、NCCL_CHECK | ctypes 加载 libnccl/librccl,绑定 20+ C 符号;dtype/算子枚举映射 |
device_communicators/pynccl.py | PyNcclCommunicator | 独立通信器:all_reduce/all_gather(+v)/reduce_scatter(+v)/send/recv/broadcast/group_start,window 注册,suspend/resume,from_unique_id_bytes |
device_communicators/pynccl_allocator.py | nccl_symm_mem_context、get_nccl_mem_pool | ncclMemAlloc 内存池 + NCCL window 注册(NVLS 用户缓冲) |
device_communicators/cuda_wrapper.py | CudaRTLibrary | libcudart ctypes 封装:cudaMalloc、IPC 句柄、P2P 探测(custom AR 依赖) |
device_communicators/cuda_communicator.py | CudaCommunicator | 分发枢纽:按尺寸/世界大小选后端;all_gather/reduce_scatter(+v)、send/recv、all2all manager 装配 |
device_communicators/base_device_communicator.py | DeviceCommunicatorBase | c10d 兜底(dist.all_reduce / all_gather_into_tensor / reduce_scatter_tensor) |
device_communicators/cpu_communicator.py | CpuCommunicator | gloo(+CPUSHM 共享内存)后端,CPU 平台对照 |
device_communicators/xpu_communicator.py | XpuCommunicator | Intel XPU:走 c10d xccl,无 pynccl |
device_communicators/custom_all_reduce.py | CustomAllreduce | IPC + P2P 单跳 all-reduce,单节点 NVLink 小/中消息(何时不用 NCCL) |
device_communicators/symm_mem.py | SymmMemCommunicator | torch 对称内存 NVLS 路径,按 capability/world_size 尺寸表 |
device_communicators/quick_all_reduce.py | QuickAllReduce | ROCm MI300 quickreduce,补充 custom AR |
device_communicators/flashinfer_all_reduce.py | FlashInferAllReduce | MNNVL all-reduce(GB200 NVLink domain),按 tuning 表限尺寸 |
device_communicators/all2all.py | AgRsAll2AllManager 等 11 个 manager | EP dispatch/combine:naive 路径复用 all_gatherv/reduce_scatterv(→NCCL);DeepEP/MoRI/MoonEP/NIXL 为替代 |
device_communicators/shm_broadcast.py | MessageQueue | 同节点对象广播:shm + zmq 通知,替代 gloo/NCCL broadcast_object |
device_communicators/all_reduce_utils.py | should_nccl_symm_mem_allreduce | 尺寸门控配置表 + 真实 P2P 探测缓存 |
distributed/parallel_state.py | GroupCoordinator、init_distributed_environment、suspend_device_comms | 分组管理、custom op 注册、graph_capture 上下文、通信器挂起 |
distributed/communication_op.py | tensor_model_parallel_all_reduce 等 | 模型层最常用的入口包装 |
utils/nccl.py | find_nccl_library、pin_nccl_env、query_nccl_gin_type | 库定位、NCCL 环境变量 pin(NCCL_NO_CACHE)、GIN 能力查询 |
distributed/weight_transfer/nccl_engine.py 等 | NCCLWeightTransferEngine | 与外部 trainer 的独立 NCCL world,权重广播(dense/sparse 两引擎) |
distributed/eplb/eplb_communicator.py | PyNcclEplbCommunicator | EPLB 专家权重搬运:pynccl group send/recv |
v1/worker/gpu_worker.py | init_device、sleep 流程 | 清 Ray 注入的 NCCL 变量、内存快照避让 NCCL 缓冲、suspend/resume 挂钩 |
v1/worker/gpu/pp_utils.py | PPHandler | PP 采样 token 广播:旁路流 + sibling 通信器 |
v1/worker/gpu/sample/batch_shard.py | get_tp_pynccl_comm | 采样 logits 分片 all_to_all_single(复用 TP 通信器) |
v1/worker/dp_utils.py | _run_ar | DP 元数据 all_reduce(NCCL 或降级 gloo) |
model_executor/determinism/batch_invariant.py | all_reduce_batch_invariant 等 | 强制 NCCL 单通道树归约的确定性环境变量组 |
distributed/elastic_ep/standby_state.py | defer_comm_warmup_on_rocm 挂钩 | ROCm 上把新通信器热身推迟到 commit,避免与在役集体死锁 |
compilation/cudagraph_pool.py | set_graph_pool_id | cuMem 图池与 NCCL 对称内存池的互斥切换 |
collect_env.py / ray/ray_env.py / utils/mem_utils.py | 环境收集 / 前缀透传 / 显存预算 | 诊断输出列出 nccl 包;NCCL_ 前缀传播给 Ray worker;预算预扣 NCCL 显存 |
5使用场景逐个详解(核心)
触发条件 → 调用链 → 代码位置:穷举 vLLM 中所有真正走到 NCCL 的 12+ 个调用场景,含排查速查表与场景总表。
场景 1初始化:后端选择与双通道建组
触发条件:任意多卡启动。调用链:
- 平台层决定默认后端:
platforms/cuda.py:232与platforms/rocm.py:659均为dist_backend="nccl",XPU 为"xccl"(xpu.py:111),CPU 为"gloo"(cpu.py:113) init_distributed_environment(parallel_state.py:1843,形参默认backend="nccl")→torch.distributed.init_process_group;NCCL 不可用时打印告警回退 glooplatforms/cuda.py:615assert is_nccl_available(),其下手工构造ProcessGroupNCCL挂到 c10d 组init_world_group / init_model_parallel_group为 TP/PP/DP/EP 各建device_group(nccl)+cpu_group(gloo)use_device_communicator=True时按get_device_communicator_cls()实例化CudaCommunicator(parallel_state.py:554)CudaCommunicator.__init__(cuda_communicator.py:107)创建PyNcclCommunicator:rank 0ncclGetUniqueId→ gloo 广播 →ncclCommInitRank→ 单元素 all_reduce 热身 +stream.synchronize()
关键结构:每个 GroupCoordinator 同时持有两个组——device_group(backend=nccl,张量通信)与 cpu_group(backend=gloo,元数据/超时控制),见 GroupCoordinator.__init__(parallel_state.py:455)。注意:pynccl 与 c10d-NCCL 是两套并存的通信器——前者服务热路径与图捕获,后者兜底与对象广播,两者 world 相同但拓扑与缓冲完全独立。建组与热身的完整动作:
# pynccl.py:165 _init_comm —— 建组与热身(节选) with torch.accelerator.device_index(device.index): self.comm = self.nccl.ncclCommInitRank( self.world_size, self.unique_id, self.rank) if _warmup_deferred(): # ROCm 弹性 EP:推迟到 commit 时热身 return stream = current_stream() data = torch.zeros(1, device=device) self.all_reduce(data) # 触发 NCCL 惰性初始化(缓冲/通道分配) stream.synchronize() # 全链路唯一一次显式同步 del data
CudaCommunicator._log_all_reduce_backend_selection(cuda_communicator.py:308)启动时打印该组可用后端及分发顺序,是排查"到底走了哪条路"的第一现场。场景 2TP all-reduce:RowParallelLinear 前向(最高频)
触发条件:TP>1 时每个 Transformer 层的 MLP/Attention 输出投影。调用链:
RowParallelLinear.forward(linear.py:1822):output = tensor_model_parallel_all_reduce(output_parallel)tensor_model_parallel_all_reduce(communication_op.py:12)→get_tp_group().all_reduceGroupCoordinator.all_reduce(parallel_state.py:730):world_size==1 直接旁路;use_custom_op_call=True时走torch.ops.vllm.all_reduce(input_, group_name=...)- custom op 按字符串组名查注册表(parallel_state.py:199)→
_all_reduce_out_place→CudaCommunicator.all_reduce(cuda_communicator.py:384) - 按尺寸分发命中后 →
PyNcclCommunicator.all_reduce(pynccl.py:273)→ncclAllReduce@当前流
真实分发代码(节选、顺序即优先级,注释为笔者所加):
# cuda_communicator.py:384 CudaCommunicator.all_reduce —— 尺寸/世界大小分发链 if (self.pynccl_comm is not None and not use_fi_ar and should_nccl_symm_mem_allreduce(self.pynccl_comm.world_size, input_)): out = torch.ops.vllm.all_reduce_symmetric_with_copy(input_) # NCCL window / NVLS if qr_comm is not None and qr_comm.should_quick_allreduce(input_): return qr_comm.quick_all_reduce(input_) # ROCm quickreduce if fi_pcie_ipc_ar_comm is not None and fi_pcie_ipc_ar_comm.should_use(input_): return fi_pcie_ipc_ar_comm.all_reduce(input_) # FlashInfer PCIe IPC if use_fi_ar: return fi_ar_comm.all_reduce(input_) # FlashInfer MNNVL if (ca_comm is not None and not ca_comm.disabled and ca_comm.should_custom_ar(input_)): return ca_comm.custom_all_reduce(input_) # IPC+P2P 单跳 if symm_mem_comm is not None and symm_mem_comm.should_use_symm_mem(input_): return symm_mem_comm.all_reduce(input_) # torch symm mem pynccl_comm = self.pynccl_comm if pynccl_comm is None or pynccl_comm.disabled: out = input_.clone() torch.distributed.all_reduce(out, group=self.device_group) # c10d-NCCL 兜底 return out return pynccl_comm.all_reduce(input_) # PyNccl:ncclAllReduce@当前流
命中 pynccl 时执行的就是一次 C FFI 调用(PyNcclCommunicator.all_reduce,pynccl.py:273):
self.nccl.ncclAllReduce(
buffer_type(in_tensor.data_ptr()), buffer_type(out_tensor.data_ptr()),
in_tensor.numel(),
ncclDataTypeEnum.from_torch(in_tensor.dtype),
ncclRedOpTypeEnum.from_torch(op),
self.comm,
cudaStream_t(stream.cuda_stream), # stream 缺省 = current_stream(),图捕获时即捕获流
)NCCL symm-mem 分支的门控在 all_reduce_utils.py,配置直接来自 H100/GB200 实测(注释中给出 8 卡与 4 卡的分段性能数据):
# all_reduce_utils.py:111 —— custom AR 只在"中段尺寸"赢,两端都还给 NCCL symm NCCL_SYMM_MEM_ALL_REDUCE_CONFIG = { "min_world_size": 4, "custom_ar_preferred_ranges": {4: (16 * KiB, 512 * KiB), 8: (16 * KiB, 128 * KiB)}, "always_use_above_world_size": 8, # world_size > 8 一律 NCCL symm mem }
all_reduce_symmetric_with_copy(注册 window 后的 NVLS all-reduce,见场景 8),32K–64K 让给 custom AR;4 卡分界为 16K/512K;min_world_size=4 意味着 2 卡 TP 不启用 NCCL symm,靠 custom AR + pynccl。VLLM_BATCH_INVARIANT 开启时该分支整体关闭(见场景 9)。场景 3all_gather:并行输出汇聚
触发条件:列并行权重输出需要拼回完整张量,或并行 logits 汇聚。调用链:
ColumnParallelLinear.forward(linear.py:631):tensor_model_parallel_all_gather(gather_output=True时)LogitsProcessor(logits_processor.py:130):use_all_gather时对 vocab 分片 logits 汇聚;另有多处 LM head 分支按 dim=-1 gather(logits_processor.py:258/305/315)GroupCoordinator.all_gather→ custom op →CudaCommunicator.all_gather(cuda_communicator.py:482)- pynccl 路径:手工
torch.empty输出 →ncclAllGather→ reshape/movedim;dim=0 且 symm 开启时改走_all_gather_symm_mem(NVLS)
两条旁路值得注意:(a) ROCm 上刻意保留基类 c10d 路径——代码注释明说手工 pynccl 分配在 ROCm 上有每步额外分配与拷贝开销,会造成解码回退(cuda_communicator.py:501);(b) 大模型上 vocab 分片 logits 的 TP all-gather 单条消息可达数十 MB,是典型 NCCL 大消息场景,NVLS/多通道带宽直接决定首 token 延迟。
场景 4reduce_scatter / all_gatherv:DP 注意力与 MoE 组合
触发条件:DP attention 把各 DP rank 的请求拼成统一批次;EP/MoE 的 combine 需要按 rank 归约;序列并行的 gather-before-GEMM。调用链:
- 模型/MoE 层调用
GroupCoordinator.reduce_scatter / reduce_scatterv / reduce_scatterv_into_output(parallel_state.py:789/805/812) CudaCommunicator.reduce_scatter(cuda_communicator.py:518):均匀切分 →pynccl_comm.reduce_scatter(ncclReduceScatter);symm 开启 →_reduce_scatter_symm_mem- 变长 sizes →
_reduce_scatterv(cuda_communicator.py:569)→pynccl_comm.reduce_scatterv(grouped ncclReduce) - BatchInvariant(ROCm 浮点)→
reduce_scatter_batch_invariant;确定性模式还可reduce(root=0)+scatter组合(cuda_communicator.py:664)
# pynccl.py:392 reduce_scatterv —— 变长归约 = grouped ncclReduce(每 rank 一个 root) self.nccl.ncclGroupStart() for root, split_size in enumerate(sizes): chunk = input_tensor[split_offset : split_offset + split_size, ...] self.nccl.ncclReduce( buffer_type(chunk.data_ptr()), buffer_type(output_tensor.data_ptr()), chunk.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype), ncclRedOpTypeEnum.from_torch(op), root, self.comm, cudaStream_t(stream.cuda_stream)) split_offset += split_size self.nccl.ncclGroupEnd()
对偶的 all_gatherv(pynccl.py:329)用 grouped ncclBroadcast 实现。EP 的 naive 后端 AgRsAll2AllManager(all2all.py:57)正是用这对原语模拟 all-to-all:dispatch = all_gatherv(每 rank 收全量 hidden states),combine = reduce_scatterv(各自算完按 sizes 归回)。MoE 热路径还提供 reduce_scatterv_into_output:输出张量由上层预分配,通信直接写入目标缓冲,避免图捕获期分配——对称内存时要求输出本身已注册(或 NCCL ≥ 2.29.2 支持非注册输出,见 NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION,cuda_communicator.py:32)。
DP 元数据同步是另一个小而重要的场景:v1/worker/dp_utils.py:_run_ar 把各 DP rank 的 padding 宽度、ubatch 标志等四项打包成一个 int32 张量,在 DP device_group(c10d-NCCL)上 dist.all_reduce;若配置 disable_nccl_for_dp_synchronization(config/vllm.py:1752 起,检测到会 rebuild CPU 组的拓扑时自动置 True)则改在 CPU gloo 组上同步,避免设备组 collective 阻塞异步调度。
场景 5broadcast:对象/张量广播的真实走向
广播在 vLLM 里被分流成三条路,很少直接用 NCCL:
| 需求 | 实现 | 位置 |
|---|---|---|
| Python 对象广播(配置、采样元数据) | MessageQueue(shm + zmq 通知,4MiB 缓冲);同节点优先,跨节点才 dist.broadcast_object_list(gloo) | shm_broadcast.py;parallel_state.py:860 broadcast_object |
| 张量广播 | torch.distributed.broadcast 走 device_group(c10d-NCCL) | parallel_state.py:845 GroupCoordinator.broadcast |
| 权重热更新广播 | PyNcclCommunicator.broadcast(独立 world,发送端 sendbuff=recvbuff 同指针) | weight_transfer/nccl_engine.py:242;pynccl.py:597 |
PP 还有一条隐蔽的 broadcast:v1/worker/gpu/pp_utils.py 的 PPHandler 把"最后一个 stage 采样出的 token"广播回所有 PP stage。为了不与层间隐状态 send/recv 在同一条 NCCL 通信线上串行化,它通过 make_sibling_device_group(group_desc="pp_broadcast")(parallel_state.py:595)另建一个与 PP device_group 同成员的独立 c10d-NCCL 子组,并在旁路 broadcast_stream 上异步执行;T 步的 recv 在 T+pp_size 步才经 FIFO 队列消费(pp_utils.py:60 注释原文:"Uses a dedicated NCCL communicator (sibling of the PP device_group) ... so it does not serialize on the wire")。
场景 6EP all-to-all:与 DeepEP 的边界
触发条件:启用 EP 的 MoE dispatch/combine。all2all.py 提供 11 个 manager,边界清晰:naive / allgather_reducescatter 后端经 GroupCoordinator.all_gatherv / reduce_scatterv 最终落到 NCCL;其余 deepep_low_latency / deepep_high_throughput / deepep_v2 / mori / moonep / nixl_ep / flashinfer_nvlink 双向与单向 / passthrough 全部走各自 RDMA/NVLink 库,不经 NCCL。但有一个反向依赖值得注意:DeepEPv2All2AllManager(all2all.py:1237)调用 query_nccl_gin_type(utils/nccl.py:88,经 ncclCommQueryProperties 查 c10d 组的 comm 指针)硬性要求 NCCL GIN(GPU-Initiated Networking,GH200/GB200 上由 GPU 发起的网络),否则直接报错——NCCL 在这里扮演"能力探针"而非传输者。
EP 家族的另两个 NCCL 用户:
- EPLB 专家再平衡:
PyNcclEplbCommunicator(eplb_communicator.py:694)以 group +ncclSend/ncclRecv在 EP rank 间搬专家权重,可指定独立 stream;再平衡期间经eplb_utils.py:121设NCCL_MAX_CTAS限制通信 kernel 占用的 SM 数,给搬运留算力 - 采样 logits 分片交换:
batch_shard.py:403用pynccl_comm.all_to_all_single(grouped ncclSend/ncclRecv,pynccl.py:489)把各 TP rank 的 logits 分片换回本 rank 的行——注释明确:复用 TP 通信器可避免 c10d all_to_all 令 NCCL 再分配一整套点对点缓冲
# eplb_communicator.py:709 PyNcclEplbCommunicator —— 专家权重搬运(节选) def add_send(self, tensors, dst_rank, expert_id): self._ensure_group_started() # 惰性 ncclGroupStart for tensor in tensors: self._pynccl_comm.send(tensor, dst_rank, stream=self._stream) def execute(self): if self._group_started: self._pynccl_comm.group_end() # 一次性提交整批收发
场景 7CUDA Graph 捕获期间的 NCCL(重点)
触发条件:V1 引擎 FULL/PIECE CUDA Graph 捕获,且模型含 TP 集合通信。机制:捕获开始时 GroupCoordinator.graph_capture(parallel_state.py:678)新建捕获流并 stream.wait_stream(curr_stream) 保证初始化已完成;随后 torch.cuda.stream(stream) 切流。此后所有 pynccl 原语取到的 current_stream() 就是捕获流,ncclAllReduce 等 C 调用只向该流 enqueue kernel,没有任何 CPU 同步,因而天然可捕获——这正是"custom op + pynccl"组合存在的原因(链上每个环节都是普通 kernel 调用)。
# parallel_state.py:678 graph_capture —— pynccl 无需任何注册,custom AR 才需要 with (torch.cuda.stream(stream), maybe_ca_context, # CustomAllreduce.capture(): 注册 IPC 图缓冲 maybe_fi_pcie_ipc_context, maybe_aiter_ar_context): yield graph_capture_context # 期间所有 pynccl 调用 enqueue 到捕获流
四个配套细节:(a) 替代后端在图内同样安全:custom AR 经 ca_comm.capture() 把 IPC buffer 注册为图缓冲(register_graph_buffers;使用 cuMem 图池时跳过注册、改为捕获期拷贝,cuda_communicator.py:124);(b) NCCL symm-mem 路径在图捕获期间分配临时对称缓冲会打破图内存池,nccl_symm_mem_context.__enter__ 因此先 torch._C._cuda_endAllocateToPool 暂停图池、__exit__ 再恢复(pynccl_allocator.py:170,图池 id 由 compilation/cudagraph_pool.py 经 set_graph_pool_id 注入);(c) CudaCommunicator._get_symm_scratch(cuda_communicator.py:682)把对称缓冲做成按 (role, ubatch, shape, dtype) 缓存的持久高水位 scratch——因为每次 nccl_symm_mem_context 的快照+注册扫描约 0.5ms,远超 NVLS 传输本身;被替换的旧缓冲仍保留引用,因为已捕获的图可能还在用它的指针;(d) 捕获前的 warmup:PyNccl 建组即热身(场景 1),defer_comm_warmup_on_rocm(pynccl.py:38)在 ROCm 上允许 elastic EP 新 worker 把热身推迟到 commit 时,避免与在役引擎的活跃 collective 死锁(standby_state.py 同样挂接)。
# pynccl_allocator.py:161 nccl_symm_mem_context —— 图捕获期间的内存池切换(节选) if self.is_graph_capture: # 暂停 CUDA Graph 内存池,让下面的 empty 落入 ncclMemAlloc 对称池 torch._C._cuda_endAllocateToPool(self.device, _graph_pool_id) self._mem_pool_ctx.__enter__() ... # __exit__:对池快照中新增的每个 segment 注册 NCCL window(集体操作) self.pynccl_comm.register_comm_window_raw( segment["address"], segment["total_size"]) if self.is_graph_capture: torch._C._cuda_beginAllocateCurrentThreadToPool(self.device, _graph_pool_id)
_reduce_scatterv 只在 uniform sizes 时才走 symm 路径(cuda_communicator.py:638 注释原文)。场景 8NCCL window(对称内存)与 NVLS
触发条件:VLLM_USE_NCCL_SYMM_MEM=1 且硬件/版本满足。这是"把用户缓冲注册进 NCCL"的完整链路:compile_nccl_allocator 现场编译 ncclMemAlloc/ncclMemFree 插件 → torch.cuda.MemPool → nccl_symm_mem_context 中分配的张量自动落入该池 → 退出上下文时把新 segment 经 ncclCommWindowRegister 注册。注册后 register_nccl_symmetric_ops(pynccl.py:62)注册的 custom op torch.ops.vllm.all_reduce_symmetric_with_copy 即走 NVLS 多播归约(输入先 copy 进对称缓冲,输出再返回)。all_gather/reduce_scatter 侧:should_nccl_symm_mem_ag_rs(all_reduce_utils.py:159)只看开关与 BatchInvariant,dim=0 的 gather 与 uniform reduce_scatter 分别走 _all_gather_symm_mem / _reduce_scatter_symm_mem,且只需单侧是对称内存(AG 只要求输出,RS 按 2.29.2 起允许非注册输出)。
场景 9环境变量与运行时控制
代码中显式读写的 NCCL_* 变量按用途分四组:
| 变量 | 设置点 | 含义 |
|---|---|---|
NCCL_NO_CACHE | utils/nccl.py:156 pin_nccl_env | 把 vLLM pin 的变量列入 NCCL 重读名单(NCCL ≥ 2.29.7),使"本进程专用"的通信器带这些参数、共享通信器不带(unpinned_nccl_env 上下文);若版本不够则告警"对端必须设相同变量否则挂起" |
NCCL_CUMEM_ENABLE / NCCL_SHM_DISABLE / NCCL_IB_DISABLE / NCCL_NVLS_ENABLE / NCCL_CUMEM_HOST_ENABLE | v1/executor/cuda_checkpoint_executor.py:107-130 | 进程 checkpoint(CRIU)环境强制关闭 NCCL 的高阶内存/传输特性,保证可冻结;与 NCCL_DISABLE_MEM_MANAGER 交互决定 NVLS 开关 |
NCCL_LAUNCH_MODE=GROUP / NCCL_ALGO / NCCL_MIN_NCHANNELS=1 / NCCL_MAX_NCHANNELS=1 / NCCL_PROTO=Simple / NCCL_NTHREADS=1 / NCCL_COLLNET_ENABLE=0 / NCCL_NVLS_ENABLE=0 | determinism/batch_invariant.py:1405 | VLLM_BATCH_INVARIANT 下强制 NCCL 单通道树形规约(NCCL_ALGO=ring,tree;allreduce:tree),保证浮点求和顺序确定;同时禁用 symm-mem 分支与 FlashInfer AR(它们无固定归约顺序) |
NCCL_GRAPH_REGISTER=0 | config/vllm.py:2378 | cuMem 图池下默认关闭 NCCL 图注册(注册会把 sleep 时卸载的图池钉死),非 0 打印告警 |
NCCL_MAX_CTAS | eplb/eplb_utils.py:121 | EPLB 再平衡期间限制 NCCL kernel 占用的 CTAS,给搬运留算力 |
NCCL_RAS_ENABLE=0 | platforms/rocm.py:454 | ROCm/RCCL 默认关闭 RAS 线程 |
NCCL_ASYNC_ERROR_HANDLING | v1/worker/gpu_worker.py:459 | Ray 注入的该变量会导致图构建异常,init_device 时主动 pop |
NCCL_IB_DISABLE=1 | snapshot/runtime.py:261 | 快照子进程继承的前缀环境;同理 ray/ray_env.py:40 把 NCCL_ 前缀列入透传 Ray worker 的默认集合 |
vLLM 侧门控变量:VLLM_NCCL_SO_PATH(指定 .so)、VLLM_DISABLE_PYNCCL(整体禁用 pynccl,回落 c10d)、VLLM_USE_NCCL_SYMM_MEM(默认 0,开启 window/NVLS 路径)、VLLM_NCCL_INCLUDE_PATH(allocator 编译时找 nccl.h)。另有 collect_env.py 把 nccl 列入诊断输出、utils/mem_utils.py:258 在显存预算中固定预扣 0.5–1 GiB"NCCL 专用显存"、gpu_worker.py:509-545 的内存快照特意在 NCCL 初始化之后测量。
场景 10多平台:RCCL / xccl / gloo
| 平台 | 后端 / 库 | 适配要点(代码证据) |
|---|---|---|
| NVIDIA CUDA | NCCL libnccl.so.2 | 主线路径;platforms/cuda.py 断言 is_nccl_available();全部高级特性(window/suspend)按版本探测 |
| AMD ROCm | RCCL librccl.so.1 | find_nccl_library(utils/nccl.py:33)按 torch.version.hip 选库;绑定层对缺失符号(ncclCommSuspend/Resume 等)continue 容忍(pynccl_wrapper.py:437);类名仍叫 NCCL,API 兼容;symm-mem all_gather 在 ROCm 上让位 c10d(场景 3) |
| Intel XPU | xccl(oneCCL,c10d 集成) | XpuCommunicator 只用 torch.distributed(xpu_communicator.py:69),平台 dist_backend="xccl";无 pynccl、无 IPC 路径;all2all 仅支持 AgRs(xpu_communicator.py:31) |
| CPU | gloo(+ CPUSHM) | CpuCommunicator(cpu_communicator.py:20):x86/ARM/PPC/s390 上 TP/PP 组启用共享内存 SHM 后端替代套接字,与 NCCL 无关——作为"同一套 GroupCoordinator 接口、不同实现"的对照 |
扩展场景 11权重热更新:与外部 trainer 的独立 NCCL world
触发条件:配置 weight_transfer_config(在线学习/金丝雀更新)。vLLM 与 trainer 组成一个与推理 world 完全无关的新 NCCL world:weight_transfer/nccl_common.py 定义两种会合方式——master_address/master_port(TCPStore + StatelessProcessGroup,要求对端有 torch),或 128 字节 ncclUniqueId 的标准 base64(供无 torch 的 JAX trainer 带外广播,数据类字段 nccl_unique_id_b64 明确拒绝 URL-safe 编码)。NCCLWeightTransferEngine.receive_weights(nccl_engine.py:182)随后按参数逐个 model_update_group.broadcast(或打包的 packed_nccl_broadcast_producer/consumer);sparse 引擎(sparse_nccl_engine.py)只传变化的切片。会话管理上还有 unpinned_nccl_env:trainer 侧 pin 的 NCCL 参数只作用于自己的通信器,不影响与 vLLM 共享的那条。
# pynccl.py:194 from_unique_id_bytes —— torch-free 对端的会合(节选) if len(unique_id_bytes) != NCCL_UNIQUE_ID_BYTES: # 128 字节 ncclUniqueId raise ValueError(...) self.unique_id = self.nccl.unique_id_from_bytes(unique_id_bytes) self._init_comm(device) # _init_comm 内:ncclCommInitRank 之后立刻做一次单元素 all_reduce 热身, # 外部对端必须配合发一次,否则全体死锁(docstring 明文要求)
扩展场景 12sleep 模式:ncclCommSuspend 释放通信显存
触发条件:enable_sleep_mode + enable_nccl_comm_suspend(config/model.py:392,实验特性)。睡眠时 gpu_worker.py:328 调 suspend_device_comms()(parallel_state.py:189,遍历所有设备通信器)→ PyNcclCommunicator.suspend → ncclCommSuspend(comm, 0x01)(要求 NCCL ≥ 2.29.7,按 has_symbol 探测,缺失则 warning_once 跳过),释放通信器内部缓冲显存但保留拓扑;唤醒时 resume_device_comms → ncclCommResume。同族 API 还有 checkpoint 场景的 checkpoint_prepare/restore(FlashInfer 工作区与 NCCL 缓冲先腾后还,cuda_communicator.py:890)。sleep_mode_backend.py 的 docstring 把"是否销毁集体通信器、是否保留含通信 kernel 的图"列为各后端的核心差异维度。
场景 13排查速查表
NCCL_DEBUG=INFO(NCCL 自身日志,由库读取而非 vLLM 设置)与上文启动日志,基本可以定位绝大多数 TP 通信异常。| 问题 / 症状 | 背后的机制 | 定位 |
|---|---|---|
| 想确认本次部署启用了哪些 all-reduce 后端 | 启动日志打印分发顺序与启用集合(潜在后端全集 8 个) | cuda_communicator.py:308 |
| TP=2 为什么没走 NCCL symm-mem | min_world_size=4,2 卡只可能 custom AR / pynccl | all_reduce_utils.py:111 |
| 怀疑两卡 P2P 实际不通、custom AR 静默退化 | gpu_p2p_access_check 用子进程做真实 IPC 读写探测并写 JSON 缓存(VLLM_CACHE_ROOT),不信 can_device_access_peer | all_reduce_utils.py:246 |
| 图捕获报 NCCL unhandled cuda error | 常见原因:走了含同步 API 的 c10d 路径(如误设 VLLM_DISABLE_PYNCCL=1);错误字符串经 NCCL_CHECK + ncclGetLastError 抛出 | pynccl_wrapper.py:458 |
| 想换 NCCL 版本做 A/B 实验 | VLLM_NCCL_SO_PATH 指定 .so 路径即可,无需重编译;symm-mem 需另外提供 nccl.h | utils/nccl.py:20;pynccl_allocator.py:104 |
| 通信器销毁阶段卡死 | destroy() 故意在 daemon 线程限时 5s 调 ncclCommAbort,因为 abort 要等所有引用它的图先销毁 | pynccl.py:250 |
| symm-mem 报"requires NCCL 2.27.3" | nccl_symm_mem_context.__enter__ 的版本断言;window 符号缺失也会在绑定层 warning | pynccl_allocator.py:167 |
| BatchInvariant 下仍不确定 | 强制单通道 Tree + 禁用 NVLS/CollNet/symm/FlashInfer;ROCm 浮点还有专用 kernel | batch_invariant.py:1405 |
场景总表
| 场景 | 通信原语 | 调用入口 | 代码位置 | 备注 |
|---|---|---|---|---|
| 1 初始化建组 | —(建 ncclComm_t) | init_distributed_environment → CudaCommunicator.__init__ | parallel_state.py:1843;cuda_communicator.py:107 | device_group(nccl)+cpu_group(gloo) 双通道 |
| 2 TP all-reduce | ncclAllReduce | RowParallelLinear.forward | linear.py:1822 → cuda_communicator.py:384 | 按尺寸分发,NCCL symm/custom AR/pynccl 竞争 |
| 3 TP all-gather | ncclAllGather | ColumnParallelLinear / LogitsProcessor | linear.py:631;logits_processor.py:130 | dim=0 且 symm 开启走 NVLS |
| 4 DP/EP 归约散布 | ncclReduceScatter / grouped ncclReduce / ncclBroadcast | reduce_scatter(v) / all_gatherv / AgRs | cuda_communicator.py:518/569;pynccl.py:329/392 | 变长 sizes 用 grouped 组合;into_output 免分配 |
| 5 广播 | ncclBroadcast / c10d broadcast | PPHandler、权重热更新、对象广播 | pp_utils.py:60;nccl_engine.py:242;shm_broadcast.py | 对象广播同节点优先 shm+zmq |
| 6 EP all-to-all(naive) | ncclSend/Recv(grouped) | all_to_all_single、AgRs dispatch/combine | pynccl.py:489;all2all.py:57;batch_shard.py:403 | DeepEP/MoRI/MoonEP 为非 NCCL 替代;DeepEPv2 依赖 NCCL GIN 探测 |
| 7 CUDA Graph 捕获 | 任意 pynccl 原语@捕获流 | graph_capture 上下文 | parallel_state.py:678;pynccl.py:293 | current_stream 即捕获流,无 CPU 同步 |
| 8 NCCL window(对称内存) | ncclCommWindowRegister / ncclMemAlloc | nccl_symm_mem_context | pynccl_allocator.py:134;cuda_communicator.py:682 | NVLS 零拷贝,scratch 高水位缓存 |
| 9 DP 元数据同步 | c10d all_reduce(nccl 或 gloo) | _run_ar | dp_utils.py:57;config/vllm.py:1752 | 可整体切 CPU gloo |
| 10 权重热更新 | ncclBroadcast(独立 world) | receive_weights | weight_transfer/nccl_engine.py;pynccl.py:194 | 支持 torch-free trainer(unique-id bytes) |
| 11 EPLB 再平衡 | grouped ncclSend/Recv | PyNcclEplbCommunicator | eplb_communicator.py:694 | 配 NCCL_MAX_CTAS 限流 |
| 12 sleep 挂起 | ncclCommSuspend/Resume | suspend_device_comms | parallel_state.py:189;pynccl.py:643 | 释放通信显存,保留拓扑 |
6动画演示
三个动画全部自动循环、无交互依赖:动画 1 建立分层心智模型,动画 2 还原 NCCL 内部最核心的 Ring 两阶段算法,动画 3 把场景 2 的分发代码转成可视路由。
| 动画 | 演示内容 | 实现技术 / 周期 |
|---|---|---|
| 1 · 调用栈下沉 | 一次 TP all-reduce 从模型层穿过六层直达硬件,逐层高亮 | CSS keyframes(14s 循环) |
| 2 · Ring AllReduce | 4 卡环形拓扑,Reduce-Scatter 与 All-Gather 两阶段换色 | SVG animate + animateTransform(12s 循环) |
| 3 · 尺寸→后端分发 | 消息从 1KB 增长到 1GB,三条后端通道按门控轮流点亮 | CSS keyframes(15s 循环) |
动画 1 · 一次 TP all-reduce 的调用栈下沉
数据包(青色光点)自模型层出发,依次点亮六层:自定义 op 注册层 → 组查找与分发枢纽 → 各 all-reduce 后端 → NCCLLibrary 的 C 符号 → 硬件互连。每次下行都是一次普通函数 / FFI 调用,唯一入队的 GPU 工作在 PyNccl 层产生并绑定当前流。
RowParallelLinear.forwardlinear.py:1822tensor_model_parallel_all_reduce → torch.ops.vllm.all_reducecommunication_op.py:12GroupCoordinator 按 group_name 查组parallel_state.py:730CudaCommunicator.all_reduce 尺寸分发cuda_communicator.py:384PyNcclCommunicator.all_reduce → ncclAllReduce(..., stream)pynccl.py:273- 青色光点 = 张量指针逐层下沉;每层高亮约 2.2 秒,对应数据到达。
- 第⑤层发生的是 Dynamo 友好的 custom op 包装:PyTorch custom op 不允许传入任意对象(
self),所以只传字符串组名(parallel_state.py:730 docstring 说明了这一约束)。 - 第③层是一次"竞标":多个后端按尺寸门槛依次表态,光点最终只能走一条。
- 第②层之后不再有 Python 对象——只剩裸指针、元素数、dtype 枚举和流句柄五个 C 参数。
动画 2 · NCCL Ring AllReduce 两阶段(4 卡)
NCCL 对中等消息的经典算法:4 卡各把张量切成 4 块,阶段① Reduce-Scatter(绿色)中每个 chunk 沿环顺时针走一跳、在途经卡上与本卡对应块相加,N-1 步后每卡持有一块完整和;阶段② All-Gather(蓝色)中这些完整块再沿环回流一圈,每卡集齐全部结果。
- 总传输量 = 2×(N-1)/N×张量大小,与卡数近似无关——这就是 Ring 对大消息友好的原因。
- 每卡的收发带宽对称:每步每卡只发 1/N 的数据,N 卡同时进行,链路无热点。
- vLLM 侧对应
pynccl_comm.all_reduce提交的ncclAllReduce;NCCL 内部再按拓扑决定 Ring/Tree/NVLS,动画展示的是 Ring。 - 对照:
CustomAllreduce在小消息时直接用 IPC 单跳完成,连环都不建——这是分发链上它排在 NCCL 前面的原因。
动画 3 · 消息尺寸 → 后端分发(8 卡 NVLink 集群)
光标沿尺寸轴从 1KB 扫到 1GB 循环移动,三条通道按 NCCL_SYMM_MEM_ALL_REDUCE_CONFIG 与 CustomAllreduce 的门控依次点亮,对应 CudaCommunicator.all_reduce 的真实决策(8 卡:≤16KiB → NCCL symm;16–128KiB → custom AR;≥128KiB → NCCL symm;pynccl 作为未启用 symm 时的承接与兜底)。
中段尺寸 16KiB–128KiB(ws=8)
custom_all_reduce.py / quick_all_reduce.py
ws ≥ 4 且 >8 一律启用
pynccl + ncclCommWindowRegister
VLLM_USE_NCCL_SYMM_MEM=0 时承接全部
fp8/fp4 大带宽场景
- 小消息段(≤16KiB):NVLS 多播一次入网,延迟低于任何 P2P 拼接;all_reduce_utils.py 注释实测 1.21x–1.48x 优势。
- 中段(16–128KiB):custom AR 的"一次 kernel + 零拷贝读对端"胜出,NCCL symm 的 copy-in/copy-out 反而吃亏。
- 大消息(≥128KiB 到 GB 级):带宽为王,NVLS/Ring 重新接管,实测最高 6.14x 优势。
- 前提条件动画未画:custom AR 还要求单节点 + full-mesh P2P + TP 组;多节点部署中段消息会直接落到 PyNccl。
三个动画合起来读:动画 1 是"软件栈怎么走",动画 2 是"数据在硬件上怎么流",动画 3 是"每一次调用由谁承接"。三者叠加,即为 vLLM 中一次 NCCL 通信的完整画像。
7与其他通信后端的关系
vLLM 的通信层是一条逐级竞争、逐级回退的链,NCCL 是兜底而非唯一;分发链的"宽度"本身就是硬件能力的函数。
vLLM 的通信层是一条逐级竞争、逐级回退的链,NCCL 是兜底而非唯一。CudaCommunicator.all_reduce 的尝试顺序即优先级,把它画成决策树(对应场景 2 的代码,箭头后为命中的实现):
CudaCommunicator.all_reduce(input_)
├─ FlashInfer MNNVL 预判(should_use_fi_ar)────── 命中则压制 NCCL symm 分支
├─ NCCL symm mem:ws≥4 且 (≤16KiB 或 ≥128KiB/512KiB)
│ └─▶ torch.ops.vllm.all_reduce_symmetric_with_copy(pynccl + window)
├─ QuickReduce(ROCm MI300)命中 ──────────────────▶ quickreduce kernel
├─ FlashInfer PCIe IPC 拓扑命中 ──────────────────▶ PCIe IPC kernel
├─ AITER custom / CustomAllreduce:
│ 单节点 full-mesh P2P + 中段尺寸 + TP 组 ─────▶ IPC 单跳 all-reduce
├─ BatchInvariant(ROCm 浮点)───────────────────▶ batch_invariant kernel
├─ torch symm_mem(尺寸表命中)───────────────────▶ one/two-shot 对称内存
└─ 其余一切 ─────────────────────────────────────▶ PyNcclCommunicator.all_reduce
├─ pynccl 可用 ──▶ ncclAllReduce @ current_stream(可图捕获)
└─ 不可用/禁用 ──▶ torch.distributed.all_reduce(device_group, c10d-NCCL)各后端"何时不用 NCCL"的分工:
| 后端 | 何时胜过 NCCL | 何时让位 / 失效 |
|---|---|---|
CustomAllreduce(custom_all_reduce.py) | 单节点、full-mesh P2P(NVLink)、TP 组、中小消息(8 卡约 16–128KiB 窗口);一次 kernel 完成,无 NCCL 启动开销 | 多节点、P2P 探测失败(gpu_p2p_access_check 真实探测而非仅 API)、ws>8、超大消息;图缓冲需 register_graph_buffers |
SymmMemCommunicator(symm_mem.py) | 启用 VLLM_ALLREDUCE_USE_SYMM_MEM(默认开)且尺寸在按 capability 的 SYMM_MEM_ALL_REDUCE_MAX_SIZES 表内 | H100/GB200 之外无 NVLS、超表、BatchInvariant |
FlashInferAllReduce / PcieIpc | GB200 NVLink domain(MNNVL)按 tuning 表;PCIe IPC 拓扑 | 无对应硬件;VLLM_BATCH_INVARIANT(非固定归约顺序) |
QuickAllReduce | ROCm MI300 补充中段窗口 | 非 MI300;与 custom AR 互补而非互斥(cuda_communicator.py:191 注释) |
gloo / CPUSHM | CPU 组元数据、DP 同步降级、CPU 平台推理 | 张量热路径完全不用(带宽低一个量级) |
shm_broadcast.MessageQueue | 同节点对象广播(4MiB 缓冲),免去 pickle+NCCL 往返 | 跨节点自动退回 dist.broadcast_object_list |
| DeepEP / MoRI / MoonEP / NIXL | EP 大规模 token 交换,占用专用 RDMA/NVLink 通道 | naive 后端(小规模 EP)反而用回 NCCL 的 ag/rs 组合 |
反过来,NCCL 也有别人替代不了的时刻:超大消息带宽场景(TP>8、多机、大 logits)、变长聚合(grouped ncclReduce/Broadcast 组合出 reduce_scatterv/all_gatherv)、独立 world 需求(权重热更新、PP 旁路组、elastic EP)、确定性模式(BatchInvariant 通过 NCCL 环境变量强制单通道树归约,而非禁用 NCCL),以及能力探针(DeepEPv2 的 GIN 检查)。系列第 15 篇将展开各替代 kernel 的内部实现。
最后补一张视角:这张竞争网络在平台层还有一层退化——同样的 GroupCoordinator 接口,XPU 上只有 xccl 一条路(无 IPC、无对称内存),CPU 上换成 gloo+SHM,ROCm 上则是 RCCL + AITER + QuickReduce 的组合。也就是说,分发链的"宽度"本身就是硬件能力的函数;阅读任何一段通信代码时,先确认平台分支,再看尺寸分支,最后才是世界大小分支——三层过滤之后剩下的那条路径,才是这次通信真正的归宿。
8小结
三句话浓缩:自建一层薄而可控的封装、NCCL 是分发链上的重要一环而非默认、运行时治理齐全。
vLLM 对 NCCL 的使用可以浓缩为三句话。第一,自建一层薄而可控的封装:NCCLLibrary 用 ctypes 直连 C 符号换取版本自由,PyNcclCommunicator 用"一切原语接受 stream 参数"换取 CUDA Graph 安全,用独立 communicator 换取与 c10d 组解耦的 world(权重热更新、elastic EP、EPLB 都受益)。第二,NCCL 是分发链上的重要一环而非默认:小消息让给 IPC 单跳、NVLS 窗口让给对称内存、EP 大交换让给专用 RDMA 库,尺寸门控表直接来自 H100/GB200 实测(NCCL_SYMM_MEM_ALL_REDUCE_CONFIG),并有 _log_all_reduce_backend_selection 把决策过程写进日志。第三,运行时治理齐全:从 pin_nccl_env 的 NCCL_NO_CACHE 机制、BatchInvariant 的强制树归约,到 sleep 模式的 ncclCommSuspend、checkpoint 进程的 NCCL_CUMEM 系列关闭,NCCL 的每个生命周期阶段都被显式管理。
八个速查事实
以下事实全部可在源码中一键定位,面试、评审与排障时可直接引用:
stream.synchronize() 在建组热身(pynccl.py:191),之后全部异步group_name,经 parallel_state.py:199 的注册表查回组对象ncclCommDestroy 是集体调用;abort 放 daemon 线程限时 5s(pynccl.py:250)ncclFloat8e4m3,p2p send/recv 一律转 uint8 传字节(pynccl.py:552)librccl.so.1,缺符号容忍而非报错(utils/nccl.py:33)self.group 会在 C++ 析构里放 GIL 导致崩溃,故先取出裸引用(pynccl.py:258 注释)set_graph_pool_id(compilation/cudagraph_pool.py)供对称内存上下文暂停/恢复 CUDA Graph 池使用理解这张网的关键,是记住 CudaCommunicator.all_reduce(cuda_communicator.py:384)这一个函数——它是所有 TP 通信的分岔口;其余场景(EPLB、权重热更新、PP 旁路组)则是 PyNcclCommunicator 独立建组能力的延伸。下一篇(第 14 篇)我们将从 Git 历史看这套封装如何一步步演化成今天的形态。