第 8 章 集合通信与网络
第8章 集合通信与网络
本章界定集合通信原语与成本模型,解析 NCCL 内部机制与通信算法,梳理 NVLink/NVSwitch 与 InfiniBand/RoCE 两类 互联架构,并展开通信计算重叠、MoE All-to-All 优化与 NCCL 性能调试实践。网络拓扑的集群级设计与上层并行策略编 排不在本章展开。
8.1 集合通信原语与复杂度
集合通信(Collective Communication)是多 GPU 训练的基础设施,没有高效的集合通信就没有分布式训练。本节系统 定义各通信原语的语义,并使用 α-β 模型和 LogP 模型分析其复杂度。
8.1.1 通信原语定义
分布式训练中最常用的七种集合通信原语,其数据流向如图8-1所示。 AllGather AllReduce Reduce Broadcast All-to-All ReduceScatter Rank 0: d[0:3] Rank 0: d0 Rank 0: d0 sum Rank 1: copy Barrier Rank 0: [P chunks] Rank 0: full d Sync point: all ranks proce Each sends to each Each: 1/P of Σd Rank 1: d[3:6] All: full d Rank 1: d1 All: Σdi Rank 1: d1 sum Root: Σdi Rank 0: data Rank 2: copy ed after reaching it Rank 1: [P chunks] Rank 1: full d Rank 2: d[6:9] Rank 2: d2 Rank 2: d2 sum Rank 3: copy 图8-1 集合通信原语可视化
8.1.2 原语语义与形式化
设 P 个 rank,每个 rank i 持有向量 v ∈ R ,各原语的前置条件、后置条件与示例用途如表8-1所示。 i M 表8-1 集合通信原语语义 原语 前置条件 后置条件 (rank i) 示例用途 Broadcast rank root 持有 v 所有 rank 持有 v 分发超参数 Reduce 各有 v i rank root 持有 ∑ v j j 收集损失 AllReduce 各有 v i 各有 ∑ v j j 梯度同步 AllGather 各有 v 的 1/P i 各有完整 [v , …, v ] 0 P −1 FSDP 参数收集 ReduceScatter 各有完整 v i rank i 持有 (∑ v )[i] j j FSDP 梯度分发 All-to-All 各有 P 个 M /P 大小的块 各块的转置重新分配 MoE token 分发 Barrier 无额外数据 所有 rank 同步到同一点 训练步骤边界
8.1.3 α-β 成本模型
对于简单的点对点(P2P)发送 M 字节消息,时间建模为: Tp2p (M ) = α + β ⋅ M 其中 α 为端到端延迟(IB/RoCE 约 1-10 μs),β = 1/B 为带宽倒数。 扩展到集合通信,依赖算法选择: Ring AllReduce: P −1 TRing AllReduce (M , P ) = 2(P − 1)α + 2 ⋅ βM P 两项分别对应 Reduce-Scatter(P − 1 步)和 All-Gather(P − 1 步)。对 M ≫ αB(大消息),带宽项主导,每 GPU 传 输约 2M 字节。 Tree AllReduce: 使用二叉树归约(depth log P ),先 Reduce 到根再 Broadcast: TTree AllReduce (M , P ) = 2 log2 P ⋅ α + 2βM 延迟仅 O(log P ) 但对大消息带宽利用差:带宽项固定为 2βM ,不随 P 缩放,但根节点是单一瓶颈——所有 P − 1 个 rank 的数据都汇聚到根节点进行归约,根节点必须接收 P − 1 条消息并发送 P − 1 条广播,链路在归约和广播阶段均接近满 载,而其余 P − 1 个节点在多数时间处于空闲等待状态。相比之下,Ring AllReduce 中每个节点同时发送和接收,链路 利用率均匀(约 50%)。这是大消息场景弃用树算法的主因。 Recursive Halving Doubling: TRHD (M , P ) = 2 log2 P ⋅ α + 2 ⋅ βM 延迟 O(log P ),带宽 O(M ),对中到大型消息最优。 All-to-All: 使用直接传输(Bruck 算法变种): P −1 TAll-to-All (M , P ) = (P − 1)α + ⋅ βMtotal P 其中 M 是每 rank 发送的总数据量。每个 rank 发送 P × (M /P ) = M 字节到所有其他 rank。 total
8.1.4 LogP 模型修正
α-β 模型的不足在于忽略了 CPU overhead( o )和 send gap( g )。LogP 模型的更精确表达: TLogP P2P = L + 2o 其中 L 为网络延迟上限(不同于 α 的端到端延迟),o 为 CPU 消息处理开销(约 0.5-5 μs),g 为连续发送的最小间隔( g= M )。 Beff 对于 Ring AllReduce,两阶段各需 P − 1 步,LogP 修正为: TLogP Ring = 2(P − 1) ⋅ max(g, L + 2o) 当 g > L + 2o 时系统是带宽限制的(大消息),否则是延迟限制的(小消息)。
8.1.5 算法选择策略
NCCL 内部根据消息大小和 GPU 数自动选择算法:小消息走低延迟的 Tree,中到大消息走 Ring,超大消息启用多通道并 在支持硬件上用 CollNet 在网归约,具体阈值随网络拓扑和 GPU 代数浮动。NCCL 2.17+ 在 H100/B200 NVSwitch 系统上 额外提供 NVLS(NVLink SHARP)算法,可将节点内大消息 AllReduce 的每 GPU 传输量降低约一半。
8.1.6 带宽利用率分析
理想带宽利用率: Mpayload Util = Mtransmitted per GPU •Ring AllReduce:M = M ,M payload ≈ 2M ⋅ (P − 1)/P ,Util ≈ 50% transmitted •Recursive Halving Doubling:Util ≈ 50% 对中等消息,接近 100% 对大消息 实践中 NCCL 的 AllReduce 带宽利用率可达 80-95%(对 100MB+ 消息,P=8),得益于流水线和 multi-rail 优化。
8.1.7 PyTorch 框架集成
PyTorch 通过 torch.distributed 暴露集合通信原语,典型用法如下:
import torch.distributed as dist
tensor = torch.ones(1024, 1024, device='cuda')
# Standard pattern for gradient aggregation
dist.all_reduce(tensor, op=dist.ReduceOp.SUM) # Sum
dist.all_reduce(tensor, op=dist.ReduceOp.AVG) # Average
# Parameter gathering in FSDP
gathered = [torch.zeros_like(tensor) for _ in range(world_size)]
dist.all_gather(gathered, tensor)
# MoE token dispatch (All-to-All via P2P communication)
dist.all_to_all(output_list, input_list)参考文献:Thakur et al., “Optimization of Collective Communication Operations in MPICH”, IJHPCA 2005。Culler et al., “LogP: Towards a Realistic Model of Parallel Computation”, PPoPP 1993。
8.2 通信算法深度解析
本节深入分析 NCCL 和 MPI 中实现集合通信的具体算法,包括其数学原理、GPU 实现细节和性能权衡。
8.2.1 Ring 算法
Ring 算法将 P 个 GPU 组织为逻辑环,消息切成 P 个 chunk 沿环推进。两阶段伪代码体现了 chunk 的调度方式。
- Reduce-Scatter 阶段(P − 1 步) Step k (k = 0, 1, ..., P-2): Each GPU: send_idx = chunk of (rank - k) mod P recv_idx = chunk of (rank - k - 1) mod P After receiving, accumulate locally 每步传输一个 chunk(大小 M /P 字节)。
- All-Gather 阶段(P − 1 步) Step k (k = 0, 1, ..., P-2): Each GPU: Send the held reduced chunk to downstream Receive the chunk from upstream 每步只交换一个 chunk,chunk 沿环流水推进。前一个 chunk 的归约尚未完成时后一个已在链路上传输,通信与计算得 以重叠,这是 Ring 在工程上实现高带宽利用率的关键。 Ring 算法特点: •带宽最优:总通信量约 2M 量级,吞吐接近带宽上限 •简单:逻辑拓扑为环,适合 GPU 的实际连接拓扑 •延迟随 P 线性增长,超过 8-16 个 GPU 时小消息延迟不可忽视
8.2.2 Tree 算法
树算法使用二叉树归约,深度为 ⌈log P ⌉。完全二叉树结构如下: 2 Level 0 (root): GPU 0 Level 1: GPU 1, GPU 2 Level 2: GPU 3-6 Level 3: GPU 7-14 ... Reduce: leaf▶root (bottom-up accumulate), logP steps Broadcast: root▶leaf (top-down broadcast), logP steps Total: 2 logP steps 树算法的带宽利用率受根节点瓶颈限制:所有 rank 的数据都须经根节点进出,根成为吞吐天花板。 树算法的 GPU 实现中,NCCL 使用双二叉树(two complementary binary trees per communicator)。两棵树的内部节 点与叶节点角色互换,使每个 rank 在其中一棵树上承担转发(内部节点),在另一棵树上只作接收(叶节点),从而让所 有 GPU 均摊带宽,消除单根瓶颈。两棵树各自执行完整的 AllReduce(reduce + broadcast 两阶段)。
8.2.3 RHD 算法
RHD 是针对大消息的递归算法: Recursive Halving 阶段(Reduce-Scatter 的等价操作): For k = 0 to log2(P) - 1: partner = rank XOR (1 << k) Exchange half of remaining data with partner Keep sum of local + remote on the half that belongs to result Doubling 阶段(All-Gather 的等价操作): For k = 0 to log2(P) - 1: partner = rank XOR (1 << k) Exchange the already-filled portion with partner 每次交换时传输的数据量递减(M /2, M /4, M /8, …),因此总通信量为 2M 。延迟仅 2 log P 步。 2 RHD 要求 P 为 2 的幂次,非幂次情况需用到配对交换(pairwise exchange)作为补充。
8.2.4 Butterfly 与混合算法
Butterfly 算法用于 All-to-All 通信,基于 Butterfly 网络结构: For step k = 1 to log2(P): For each rank i: Exchange with rank i XOR (1 << (k-1)) 每步交换的数据模式类似 Butterfly 网络拓扑,但 NCCL 的 All-to-All 实现并不直接使用 Butterfly 算法。NCCL AlltoAll 底 层使用点对点 send/recv,由调度器决定哪对 GPU 在哪步交换。Butterfly 模式描述了一种数据交换的拓扑概念,不代表 NCCL 的实际算法名称( NCCL_ALGO 中无 Butterfly 选项)。 Rabenseifner 算法:针对非 2 的幂次 P 值,Rabenseifner(2004)提出混合算法,结合 Reduce-Scatter 与 All- Gather:
- 对于 P 个 ranks,找到最大的 2 的幂次 p = 2 ⌊log2 P ⌋
- 在 p 个 ranks 上使用 RHD
- 剩余的 P − p 个 ranks 通过 Gather + Scatter 参与
8.2.5 多轨通信
当节点有多个 NIC 时,NCCL 支持 Multi-Rail,同时使用多个网络接口传输数据: 1 GPU ▶ 4 IB HCAs ▶ 4 switches ▶ 4 IB HCAs ▶ 1 GPU (peer) Multi-Rail 将 M 字节的消息按轮转(round-robin)分配到不同 NIC(rail),实现接近线性的带宽聚合。DGX H100 配备 8 个 ConnectX-7 IB HCAs(每 GPU 1 个,合计 400 GB/s),需 multi-rail 来充分利用。
8.2.6 在网归约 SHARP 与 NVLS
Mellanox SHARP(Scalable Hierarchical Aggregation and Reduction Protocol)将归约操作卸载到 InfiniBand 交换机 上: GPU0 ─┐ GPU1 ─┤ GPU2 ─┼─▶ IB Switch (SHARP aggregator) ──▶ all GPUs GPU3 ─┘ SUM operation completed on switch 优势: •减少网络总数据量:每个 GPU 只需发送一次 M 字节,交换机在网聚合后向外广播结果,避免传统 AllReduce 多跳数 据倍增 •减少延迟:交换机硬件处理比 CPU/GPU 转发更快 •适合 AllReduce 和 Barrier NCCL 检测到支持 SHARP 的拓扑时自动启用。环境变量 NCCL_NET_GDR_LEVEL 影响是否允许 GPUDirect RDMA 与 SHARP 结合。 NVLS(NVLink SHARP)是 Hopper 起在 NVSwitch 内部集成的 SHARP 引擎,NCCL 2.17+ 将其暴露为 NVLS 与 NVLSTree 两种算法。思路与网络级 SHARP 相同:各 GPU 把本地数据写入 NVSwitch 管理的多播内存区域,归约在交 换机 ASIC 内一次性完成,结果多播回所有 GPU。相比传统 Ring AllReduce 每 GPU 发送与接收约 2M 字节,NVLS 中每 GPU 仅发送和接收 M 字节各一次,节点内大消息 AllReduce 的每 GPU 传输量显著降低。跨节点场景由 NVLSTree 将节 点内 NVLS 与节点间 Tree/CollNet 分层组合;NVLS 需要 CUDA 多播内存 API( cuMulticastCreate )与 Hopper/Blackwell 硬件支持。 NVLS 可通过 NCCL_ALGO 强制指定:
NCCL_ALGO values available from
export NCCL_ALGO=NVLS # force NVLink SHARP (intra-node only) export NCCL_ALGO=NVLSTree # NVLS intra-node + Tree inter-node 约束:NVLS 需要 NVSwitch 拓扑(DGX H100 / HGX H100),仅适用于节点内,消息需超过约 1 MB 才能摊薄 NVSwitch 调度开销。在 DGX H100(8 GPU)上测量,1 GB AllReduce 时 NVLS 有效带宽约达 400 GB/s,而 Ring 约 270 GB/s,达 到 NVLink 4.0 单向峰值(450 GB/s)的约 89%。 参考文献:Rabenseifner, “Optimization of Collective Reduction Operations”, ICCS 2004。Graham et al., “Scalable Hierarchical Aggregation and Reduction Protocol (SHARP)”, SC 2016。
8.3 NCCL 内部机制与拓扑
NCCL(NVIDIA Collective Communications Library)是多 GPU 系统中集合通信的底层实现库,也是 PyTorch、 TensorFlow、JAX 等框架的后端。理解 NCCL 内部机制对诊断多 GPU 通信瓶颈至关重要。
8.3.1 初始化全流程
NCCL 从 ncclCommInitRank 到通信通道建立的六步过程如图8-2所示。 App ncclTopo ncclGraph ncclTransport
- Bootstrap (unique ID exchange) 2-way handshake over TCP socket
- Topology Detection Read PCIe topology + NVML GPU info
- Graph Construction Build logical connectivity graph
- Ring/Tree Path Search Search for optimal communication paths
- Channel Establishment Allocate connections + buffers
- Communicator Ready App ncclTopo ncclGraph ncclTransport 图8-2 NCCL 初始化流程
8.3.2 Bootstrap 与拓扑检测
Bootstrap 负责在各 rank 之间建立初始通信以交换拓扑信息。NCCL 使用 ncclUniqueId 作为共享令牌:
import torch.distributed as dist
# PyTorch handles bootstrap automatically, calls ncclGetUniqueId internally
dist.init_process_group(backend='nccl', init_method='tcp://master:29500')Bootstrap 的通信协议通过 TCP socket 建立所有 rank 间的初始连接,然后完成拓扑信息交换。 NCCL 通过以下来源获取系统拓扑:
- NVML(NVIDIA Management Library):查询 GPU 型号、PCIe 位置、NVLink 连接
- PCIe 拓扑:从 /sys/bus/pci/devices/ 读取 PCI 树,构建 GPU ↔ NIC ↔ PCIe Switch 的关系
- 网络拓扑:从 IB/RoCE 子网管理器获取交换机和 HCA 连接信息
- CPU/NUMA 拓扑: /sys/devices/system/node/ 用于 NUMA-aware 通信路径选择 合并后构建一个完整的系统拓扑图 ncclTopoSystem ,其中: •节点:GPU、NIC、PCIe Switch、NUMA Node •边:链路类型(NVLink, PCIe, Network)和带宽
8.3.3 图搜索与路径规划
NCCL 在拓扑图中搜索最优的通信路径( ncclTopoCompute ):
- Ring 路径搜索:寻找一条哈密顿回路使总延迟最小。权重 = 链路的传输时间估计。
- Tree 路径搜索:以每个 node 为根,寻找满足双二叉树性质的最优路径。
- 通道分割:NCCL 将大消息分割到多个通道(channel)上并行传输。通道数 n = min(maxChannels, 可用路径数) channels ,典型值为 8-32。
8.3.4 通道选择与协议
NCCL 的通道分配策略: •Ring 通道:适合中到大消息(≥256KB),每通道使用不同的物理 NVLink/网卡路径 •Tree 通道:适合小消息,用于低延迟集合通信(如 Barrier)。树通道也用于 NCCL 的控制面 算法选择阈值规则:消息小于 256 KB 走 Tree(低延迟优先),256 KB 到 4 MB 走 Ring(带宽-延迟平衡),大于 4 MB 走 多通道 Ring,在支持 SHARP 的硬件上改用 CollNetDirect/CollNetChain 在网归约;阈值随网络拓扑和 GPU 代数浮动。 协议选择:NCCL 有三种内部协议,其适用消息大小、延迟与带宽特征如表8-2所示。 表8-2 NCCL内部协议 协议 适用消息大小 延迟 带宽 原理 LL (Low-Latency) < 16 KB 极低 (约2 μs) 低 通过 GPU 共享内存或 NVLink 的直接写入(direct store) LL128 16 KB - 256 KB 低 (约5 μs) 中 128 字节对齐的 warp-level 操作 Simple > 256 KB 高 (约10 μs) 高 GPU DMA 引擎直接传输 (GDR) 协议选择的阈值为 NCCL_LL_THREAD_THRESHOLD 和 NCCL_PROTO :
Check the protocol currently used
export NCCL_DEBUG=INFO
8.3.5 NVLink 与 GDR
Log will show: "protocol LL128" or "protocol Simple"
节点内 GPU 之间通过 NVLink 直接通信,无需经过 PCIe 或网络。NVLink 4.0 每 GPU 双向带宽 900 GB/s,NVSwitch 系 统中任意 GPU 对都有直接的 NVLink 路径。NVLink 的直接内存访问使得 AllReduce 在节点内极为高效。NCCL 通过 ncclTopoGetNetDev 检查 NVLink 路径是否存在。对于 NVSwitch 系统(DGX H100 / B200) ,所有 8 个 GPU 通过全连 接的 NVSwitch 互联。 GPUDirect RDMA(GDR):允许 NIC 直接从 GPU 内存读取/写入数据,跳过 CPU 中转: Without GDR: GPU memory ▶ CPU memory (copy) ▶ NIC ▶ network ▶ NIC ▶ CPU memory (copy) ▶ GPU memory With GDR: GPU memory ▶ NIC ▶ network ▶ NIC ▶ GPU memory GDR 消除了两次 CPU-GPU 内存拷贝,减少延迟约 50% 并节省 CPU 带宽。NCCL 通过环境变量控制 GDR 行为。
8.3.6 关键环境变量
NCCL 的关键环境变量及作用如表8-3所示。 表8-3 NCCL关键环境变量 变量 作用 常用值 Tree , Ring , CollNetDirect , CollNetChain , NVLS (NCCL 2.17+), NCCL_ALGO 算法选择 NVLSTree (NCCL 2.17+) NCCL_PROTO 协议选择 LL , LL128 , Simple NCCL_DEBUG 调试信息级别 WARN , INFO , TRACE NCCL_DEBUG_SUBSYS 调试子系统 ALL , INIT , GRAPH , TUNING NCCL_IB_DISABLE 禁用 IB 0 (启用), 1 (禁用) NCCL_SOCKET_IFNAME 指定网络接口 ib0 , bond0 , eth0 RoCE GID 索 可通过 show_gids 查询 NCCL_IB_GID_INDEX 引 NCCL_NET_GDR_LEVEL GDR 级别 0 (禁用)- 5 (最大) LOC (同芯片), NVL (NVLink), PIX (同PCIe交换机), PXB (跨PCIe桥), PHB (同PCIe NCCL_P2P_LEVEL P2P 传输级别 根), SYS (任意) 指定 HCA 设 mlx5_0,mlx5_1 NCCL_IB_HCA 备 NCCL_IB_QPS_PER_CONNE CTION 每连接 QP 数 1 (默认);调优推荐 4-8,可提升 AllReduce 带宽 NCCL_NET_PLUGIN 网络插件 用于自定义网络库 (如 AWS EFA) NCCL_MIN_NCHANNELS 最小通道数 4 (默认) NCCL_MAX_NCHANNELS 最大通道数 自动检测 拓扑 Dump ./nccl_topo.xml 用于可视化 NCCL_TOPO_DUMP_FILE 路径 NCCL_NET_GDR_LEVEL 的分级行为: NCCL_NET_GDR_LEVEL controls the maximum allowed topological distance between GPU and NIC for GDR to be enabled. Higher values = more permissive: 0 = LOC (most restrictive: GPU and NIC on same chip only) 1 = NVL (GPU and NIC behind same NVLink) 2 = PIX (within same PCIe switch) 3 = PXB (cross PCIe bridge, same NIC root) 4 = PHB (within same PCIe root complex) 5 = SYS (most permissive: any GPU-NIC combination may use GDR) Note: NCCL selects the highest feasible level automatically; lower values disable GDR for farther-apart pairs (useful for debugging GDR issues). NCCL 根据硬件能力自动选择最高级别的 GDR,但可用环境变量降级排查问题。
8.3.7 通道机制与调试
NCCL 将数据分割到多个逻辑 Ring 上并行传输: Single Channel (1 Channel): Data (M bytes) ▶ Ring (1) ▶ result Multi-Channel (k Channels): Data (M bytes) ▶ k Rings (each transmits M/k bytes) ▶ merge results 多通道增加并行度的同时也增加 launch 开销。NCCL 默认最多 32 个通道,但在 8 GPU 的 DGX 中通常只用 4-8 个。 NCCL 日志解读:配合 NCCL_DEBUG=INFO 与 NCCL_DEBUG_SUBSYS=INIT,GRAPH ,可看到如下典型输出: export NCCL_DEBUG=INFO export NCCL_DEBUG_SUBSYS=INIT,GRAPH
# Typical log snippet
# ncclCommInitRank: comm 0x...
# ncclTopoDetect: found GPU 0 ...
# ncclTopoCompute: ring graph search
# NCCL INFO Channel 0/0 : GPU0 [0x...] GPU1 [0x...] connected
# NCCL INFO Using 4 channels for ring重定向这些日志配合 NCCL_TOPO_DUMP_FILE 可以完整可视化 NCCL 的内部通路选择。 参考文献:NCCL 官方文档: https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/。Awan et al., “Understanding the Cost of NCCL Calls in Distributed Deep Learning”, CLUSTER 2021。
8.4 NVLink 与 NVSwitch
NVLink 和 NVSwitch 是 NVIDIA 专有的高带宽 GPU 间互联技术,是 Tensor Parallelism 和节点内 AllReduce 通信的物理 基础。理解其拓扑结构对配置并行策略和诊断节点内通信瓶颈至关重要。
8.4.1 NVSwitch 架构
NVSwitch 是 GPU 的全连接交换机,将所有 GPU 的 NVLink 端口连接到统一的交叉矩阵。DGX H100 节点内 8 个 GPU 与 4 颗 NVSwitch 的互联关系如图8-3所示。 DGX H100 internal NVSwitch topology GPU 3 H100 GPU 2 H100 GPU 1 NVSwitch 3 H100 GPU 7 H100 GPU 6 H100 GPU 0 NVSwitch 2 H100 GPU 5 H100 NVSwitch 1 NVSwitch 0 (900GB/s ×18) GPU 4 H100 图8-3 DGX H100 的 NVSwitch 全连接拓扑 NVSwitch 经历了四代演进:第一代(DGX-2, V100)用 6 颗交换机把 16 个 V100 全连接;第二代(DGX A100)将 NVSwitch 集成到主板上(baseboard),直接桥接所有 GPU,不走 PCIe 交换机;第三代(DGX H100)8 个 H100 通过 4 颗第三代 NVSwitch 芯片全连接;第四代(DGX B200)每 GPU 连接到 2 颗 NVSwitch,共 8 颗构成冗余的双层交叉矩 阵,支持 576 GPU 的超大规模 NVLink 域。 DGX B200 的 8-GPU NVSwitch 全连接拓扑如图8-4所示,与 H100 的 4-NVSwitch 拓扑不同,B200 使用 8 颗 NVSwitch 4.0 芯片构成双层交叉矩阵: DGX B200 8-GPU NVSwitch 4.0 Topology GPU 0 B200 NVSwitch 0 1800 GB/s GPU 1 B200 NVSwitch 4 GPU 2 B200 NVSwitch 5 NVSwitch 1 GPU 4 B200 NVSwitch 6 GPU 3 B200 NVSwitch 7 GPU 5 NVSwitch 2 B200 GPU 6 B200 GPU 7 B200 NVSwitch 3 图8-4 DGX B200 的 8 路 NVSwitch 4.0 拓扑 B200 的拓扑结构较 H100 更复杂:每个 GPU 连接到 2 个 NVSwitch,总共 8 个 NVSwitch 构成冗余的交叉矩阵。这种设 计满足 Blackwell 架构更大规模 NVLink 域(NVL72: 72 GPU 单域)的互联需求。
8.4.2 NVLink-C2C 互联
NVLink-C2C 是 NVIDIA Grace CPU 与 Hopper GPU 之间的芯片到芯片互联: Grace CPU ◀─ NVLink-C2C (900 GB/s) ──▶ Hopper GPU C2C 提供 CPU-GPU 间的统一内存访问(UMA),且延迟远低于 PCIe(< 100 ns vs 约 1000 ns)。对于 CPU offloading 场 景,C2C 比 PCIe 快 10 倍以上。Grace-Hopper 超级芯片上的 CPU offloading 成为可行的高性能方案。
8.4.3 拓扑与 Ring 映射
NCCL 建立 Ring 通信时,需要将逻辑环映射到物理 NVLink 拓扑。一个 8 GPU DGX A100 的检测结果: $ nvidia-smi topo -m GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 GPU0 X NV12 NV12 NV12 NV12 NV12 NV12 NV12 GPU1 NV12 X NV12 NV12 NV12 NV12 NV12 NV12 GPU2 NV12 NV12 X NV12 NV12 NV12 NV12 NV12 ... NV12 表示通过 12 条 NVLink 连接(A100 的完整 NVSwitch 连接)。这是最优拓扑,所有 GPU 两两全连接,Ring 的任何 排列都等效。 对于非 NVSwitch 的拓扑(如 4 GPU 通过 NVLink Bridge 互联),拓扑不对称:
Example: 4 GPUs connected via
GPU0 GPU1 GPU2 GPU3 GPU0 X NV4 NV4 NV2 ◀ GPU0 and GPU3 have only 2 NVLinks GPU1 NV4 X NV2 NV4 GPU2 NV4 NV2 X NV4 GPU3 NV2 NV4 NV4 X 此时 NCCL 的路径搜索会将 Ring 排列为 0→1→3→2→0(优先走 NV4),避免经过 NV2 的慢路径。
8.4.4 DGX 内部拓扑
以 DGX H100 为例,节点内 8 个 H100 SXM GPU 通过 4 颗 NVSwitch 全互联(如图8-3所示),其物理布局与 NUMA 亲和 性如下: Physical layout (dual-socket Intel/AMD): NUMA Node 0 (CPU 0): GPU 0, GPU 1, GPU 2, GPU 3 NUMA Node 1 (CPU 1): GPU 4, GPU 5, GPU 6, GPU 7 NVLink topology (uniform across all 8 GPUs): GPU 0─7 ◀── 4 × NVSwitch 3.0 chips (full crossbar) ──▶ GPU 0─7 Any GPU pair can communicate at full NVLink 4.0 bandwidth NUMA-aware 通信:GPU 间的 NVSwitch 带宽是均匀的,任意 GPU pair 的 NVLink 路径均经过 NVSwitch 交换。NUMA 区别仅影响 CPU-GPU 亲和性(GPU 0-3 通过 PCIe 连接到 CPU 0,GPU 4-7 连接到 CPU 1),与 GPU-GPU 通信无关。 NCCL 自动处理拓扑,但在极端排查场景下可手动限制 GPU 范围: export CUDA_VISIBLE_DEVICES=0,1,2,3 # Limit to one NUMA node's GPUs
8.4.5 NVLink 与 PCIe 对比
NVLink 在 GPU-GPU 通信中比同代 PCIe 快约 7–14 倍。以 AllReduce 1 GB 消息为例,8 个 GPU 通过 NVLink 4.0 的 busbw 约 400 GB/s,而等效带宽若走 PCIe Gen5 仅约 56 GB/s,差距直接影响训练 throughput。NCCL 在 PCIe 上同样 使用 Ring/Tree 算法,但由于 PCIe 带宽远低于 NVLink,通信延迟会高出数倍(如下文 Llama-70B TP AllReduce 示例所 示),导致训练步时显著劣化。这就是为什么 TP 必须部署在节点内——不是因为 NCCL 不支持 PCIe 上的 Ring/Tree,而 是因为 PCIe 的带宽和延迟使 TP 通信成为不可接受的瓶颈。 在实际训练中,每 token 的 TP AllReduce 通信量约为 2 × hidden_size × 4 字节(FP32 梯度)。以 Llama-70B (hidden_size=8192)为例,单层 TP AllReduce 约 512 MB。在 NVLink 4.0 上耗时约 1.3 ms,而在 PCIe Gen5 上需要 约 9.1 ms,7 倍的差距直接转化为训练步时的显著差异。
8.4.6 拓扑可视化
export NCCL_TOPO_DUMP_FILE=./nccl_topo.xml
# Run any distributed training script
# Visualize the generated XML topology
# Use nvidia-smi topo --xml or nccl-topo-viewer (community tool)生成的 XML 包含所有检测到的 GPU、NIC、PCIe Switch、NUMA 节点的详细连接关系,是排查通信问题的关键工具。
8.4.7 NVLink 域规模与并行约束
NVLink 域可按规模分为三个层级,各类系统的典型拓扑如下: •单节点 NVSwitch(8 GPU):所有 GPU 通过 NVSwitch 全连接,任意 GPU 对等带宽。DGX H100/B200 均为这种拓 扑,适合 TP=8、FSDP/ZeRO-3。 •双节点 NVSwitch 桥接(16 GPU):两个 DGX 节点通过外部 NVSwitch 芯片级联,形成 16 GPU 的扁平 NVLink 域。例 如 HGX H100 2 节点配置中,两台服务器的 NVSwitch 通过额外的 NVSwitch 互联,跨节点 GPU 对也可获得约 450 GB/s 有效带宽。这在 NVL72 等超大域出现前是 NVLink 跨节点扩展的主要方式。 •多节点 NVLink 域(72-576 GPU):NVL72(GB200 NVL72)将 36 个 Grace-Blackwell 超级芯片(共 72 GPU)通过 9 个 NVLink Switch Tray 全连接,形成单 NVLink 域内 130 TB/s 的总聚合带宽。更大规模的 NVL576 通过三层 NVSwitch 树级联 576 GPU。这种拓扑使得 TP 可以跨节点扩展到 72 甚至更多 GPU,消除了传统上需要 IB 网络的节点 间 AllReduce 延迟。 不同 NVLink 拓扑对 AllReduce 性能的影响(1 GB 消息,8 GPU 每节点)如表8-4所示。 表8-4 不同NVLink拓扑的AllReduce性能 拓扑 NVLink 代际 节点内 busbw 跨节点 busbw 适用 TP 规模 单节点 NVSwitch (H100) NVLink 4.0 约 400 GB/s N/A TP ≤ 8 双节点桥接 (H100) NVLink 4.0 约 400 GB/s 约 200 GB/s TP ≤ 16 NVL72 (B200) NVLink 5.0 约 800 GB/s 约 600 GB/s TP ≤ 72 NVL576 (B200) NVLink 5.0 约 800 GB/s 约 400 GB/s TP ≤ 576 注:busbw 为 nccl-tests 实测值,受协议开销和拓扑竞争影响低于理论峰值。 从 NVLink 拓扑角度审视并行策略的约束: •TP ≤ 节点 GPU 数:TP 的频繁 AllReduce 必须在 NVLink 上运行,不可跨越节点边界 •PP 跨节点:P2P 通信量小(bsh),可以走节点间网络 •DP 全局:AllReduce 频率低(每步一次),可以走节点间网络,但有延迟代价 •NVSwitch 节点内推荐 TP=8:全连接的 NVSwitch 使得任意 GPU 配对等价,TP=8 不会产生次优通信路径 •无 NVSwitch 的节点推荐 TP≤4:受限于 NVLink bridge 拓扑,TP=8 会导致某些 ring 段走慢路径 参考文献:NVIDIA NVLink/NVSwitch 白皮书。Li et al., “NCCL: Accelerating GPU Communication with
8.5 InfiniBand 与 RoCEv2
Topology-Aware Hierarchical Collectives”, NVIDIA Developer Blog。 节点间的 GPU 通信依赖高性能网络。InfiniBand(IB)和 RoCEv2(RDMA over Converged Ethernet)是 AI 训练集群中 的两种主流选择。本节从架构层面分析两者的设计差异、性能特征和部署考量。
8.5.1 IB 架构总览
IB 采用通道化 I/O 架构,其组件关系如图8-5所示。 InfiniBand network architecture HCA 1× 400Gb/s management (Host Channel Adapter) ConnectX-7 400Gb/s 1× 400Gb/s Subnet Manager IB Switch 2 IB Switch 1 QM9700 64×400G (runs on switch or host) management QM9700 64×400G management IB Gateway (IB-to-Ethernet) 图8-5 InfiniBand 网络架构示意 •HCA:Host Channel Adapter,即 IB 网卡(Mellanox/NVIDIA ConnectX 系列) •IB Switch:专用 IB 交换机(如 QM9700 NDR 400G),非以太网交换机 •Subnet Manager(SM):负责路由表计算、LID 分配、链路初始化和故障恢复。IB 子网必须有至少一个 SM IB 在链路层采用基于 credit 的无损流控(Link-Level Flow Control):接收端为每条虚拟通道(Virtual Lane, VL)维护独 立的接收缓冲 credit,发送端只有确认对端有足够 credit 时才允许发包,从而在硬件层面保证不丢包。VL 还用于流量隔 离(如将控制面与数据面流量分到不同 VL),避免 head-of-line blocking。相比 RoCEv2 依赖 PFC 暂停帧维持无损,IB 的逐链路 credit 机制无需端到端暂停,天然规避了 PFC 的拥塞扩散问题,这是 IB 在万卡集群中延迟更稳定的物理基础。
8.5.2 IB 链路速率世代
IB 各代际的信号速率、编码与有效带宽如表8-5所示。 表8-5 IB链路速率世代 代际 信号速率 编码 有效带宽 (4× lanes) 代表产品 FDR 14 Gbps 64/66 54 Gb/s ConnectX-3 EDR 25 Gbps 64/66 97 Gb/s ConnectX-4 HDR 50 Gbps 64/66 194 Gb/s ConnectX-6 HDR100 50 Gbps 64/66 97 Gb/s ConnectX-6 (单口) NDR 100 Gbps 64/66 389 Gb/s ConnectX-7 NDR200 100 Gbps 64/66 194 Gb/s ConnectX-7 (单口) XDR 200 Gbps PAM4 4× 778 Gb/s ConnectX-8 每个 HCA 可以有 1/2/4/8 个端口(port)。DGX H100 配备 8 个 ConnectX-7 单端口 HCA(合计 8 × 400 Gb/s = 3.2 Tb/s 节点总带宽)。
8.5.3 RDMA 编程模型
RDMA 允许直接从远程主机内存读写数据,绕过远端 CPU:
// RDMA verbs simplified programming model
// 1. Create protection domain and queue pair
pd = ibv_alloc_pd(context);
qp = ibv_create_qp(pd, ...);
// 2. Register memory region
mr = ibv_reg_mr(pd, buffer, length, IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ);
// 3. Exchange QP informationconnect_qp(local_qp, remote_qp_info); // 4. Execute RDMA operations // Send/Recv ibv_post_send(qp, send_wr); // Sender must post send WR ibv_post_recv(qp, recv_wr); // Receiver must post recv WR in advance // RDMA Write ibv_post_send(qp, rdma_write_wr); // Only sender operates; receiver is unaware // RDMA Read ibv_post_send(qp, rdma_read_wr); // Read from remote to local // Atomic (atomic operation on remote memory) ibv_post_send(qp, atomic_wr); // 5. Poll completion queue ibv_poll_cq(cq, &wc); NCCL 内部使用这些 verbs 操作来实现集合通信。Send/Recv 用于点对点通信(PP, Ring),RDMA Write/Read 用于 AllGather/AllReduce 等聚合场景,Atomic 用于同步操作。
8.5.4 RoCEv2 协议栈
RoCEv2 将 IB 传输层封装在 UDP/IP 之上,运行于标准以太网: RoCEv2 protocol stack: ┌─────────────────┐ │ IB Transport │ ◀ InfiniBand transport layer ├─────────────────┤ │ UDP │ ◀ Replaces IB Network Layer ├─────────────────┤ │ IP │ ◀ IPv4/IPv6 ├─────────────────┤ │ Ethernet │ ◀ Standard Ethernet (L2) └─────────────────┘ RoCEv2 的优势: •使用标准以太网交换机(成本低 2-3 倍) •可与现有数据中心以太网基础设施集成 •支持 IP 路由(跨子网) RoCEv2 的劣势: •需要无损以太网(PFC + ECN) •拥塞控制复杂度高 •没有内置的 SM(需要额外的配置)
8.5.5 拥塞控制机制
为避免丢包(RDMA 严重依赖无损传输),RoCEv2 依赖两层拥塞控制:
- PFC:Priority Flow Control,IEEE 802.1Qbb 定义的逐跳(per-hop)暂停帧机制。当接收缓冲区达到阈值时,发送 PAUSE 帧给上游交换机,粒度为一个优先级(8 个流量级别)。PFC 的主要问题是可能引发队头阻塞(head-of-line blocking)和拥塞死锁。
- ECN:Explicit Congestion Notification,端到端的拥塞通知。交换机标记经历拥塞的包,接收端通过 Congestion Notification Packet (CNP) 通知发送端降速。
- DCQCN:Data Center Quantized Congestion Notification,基于 ECN 的速率控制算法。发送端根据 CNP 的到达速率 调整发送速率: ={
R × (1 − α) current 收到 CNP newR R +β⋅R current 未收到 CNP target
8.5.6 IB 与 RoCEv2 对比
IB 与 RoCEv2 的关键维度对比如表8-6所示。 表8-6 InfiniBand与RoCEv2对比 维度 InfiniBand RoCEv2 网络设备 专用 IB 交换机 标准以太网交换机 (DCB-capable) 单端口速率 NDR 400G (100G per lane) 400G (100G per lane) 延迟 (小消息) 约 1.5 μs (端到端) 约 2-5 μs 拥塞控制 基于 credit 的无损流控 PFC + ECN/DCQCN 路由协议 SM 集中管理 IP 路由 (分布式) 网卡 ConnectX-7 IB ConnectX-7 VPI (支持 IB + Ethernet) GPU Direct RDMA 支持 支持 成本 (交换机) 约 $15/100Gbps 约 $5/100Gbps 生态成熟度 NVIDIA 主导, AI 集群首选 业界标准, 多供应商 大规模部署的实际选择: •超大规模训练(>1 万 GPU):InfiniBand 仍是首选,原因是其原生无损传输、更低的尾延迟(P99)和更成熟的 NCCL 优化路径。 •数百至数千卡与推理场景:RoCE v2(配合高速以太网)性价比更优,建设成本可节省 30–50%。 •RoCE v2 部署关键:必须开启 PFC(Priority Flow Control)并配置 ECN(Explicit Congestion Notification),DSCP 标记需与交换机 ACL 一致;强烈建议独立 RDMA 专用 VLAN,避免与普通 IP 流量混跑。 •云环境:AWS EFA 使用自定义 SRD 协议(类似 RoCE + 可靠性增强),GCP 使用 GPUDirect-TCPX 国内字节跳动、阿里云等机构的万卡集群已大量采用大规模 RoCE 方案(配合 UEC 标准演进),表明在充分的网络工程前 提下 RoCE 可以支撑超大规模训练。
8.5.7 新一代 AI 以太网
传统 RoCEv2 依赖 PFC 的逐跳流控,在大规模下易出现拥塞扩散与死锁,为此业界出现了两条演进路线。其一是 NVIDIA 的 Spectrum-X 平台(Spectrum-4 交换机 + BlueField-3 SuperNIC):它通过逐包自适应路由(per-packet adaptive routing)把同一 QP 的流量打散到多条等价路径,再在 BlueField-3 上做保序重组,配合硬件级可编程拥塞控制,把 RoCE 在大集群下的有效带宽利用率从约 60% 提升到 95% 左右,并显著压低尾延迟。其二是 Ultra Ethernet Consortium(UEC,2023 年由 AMD、Broadcom、Intel、Meta、Microsoft 等发起)制定的 Ultra Ethernet Transport (UET)标准,用多路径 packet spraying、无序可靠交付(out-of-order delivery)与轻量拥塞控制替代 go-back-N 重 传和 PFC,目标是在数万至十万卡规模上提供接近 InfiniBand 的性能而保持以太网生态开放。这些技术标志着 AI 网络从 “严格无损以太网”向“容损但可靠”的传输语义转变,也是选型时 IB 与以太网差距快速收窄的主因。
8.5.8 Rail 优化拓扑
DGX H100 的 8 个 ConnectX-7 NIC 按 rail-optimized 方式连接到网络: GPU0 ▶ NIC0 ▶ Rail 0 GPU1 ▶ NIC1 ▶ Rail 1 GPU2 ▶ NIC2 ▶ Rail 2 GPU3 ▶ NIC3 ▶ Rail 3 GPU4 ▶ NIC4 ▶ Rail 4 GPU5 ▶ NIC5 ▶ Rail 5 GPU6 ▶ NIC6 ▶ Rail 6 GPU7 ▶ NIC7 ▶ Rail 7 每个 Rail 对应一台 Leaf 交换机。AllReduce 时各 GPU 通过不同 Rail 同时传输,这要求交换机之间也有足够的 Spine 带 宽以避免拥塞。典型的 Fat-Tree 拓扑应满足: 总 Spine 带宽 ≥ 总 Leaf 下联带宽 。 以 1000 卡集群为例: Typical 1000-card IB network (Fat-Tree topology): Tier 1 (Leaf): 32x QM9700, each with 32x 400G ports -> 1024 ports Tier 2 (Spine): 16x QM9700, full-mesh interconnect Tier 3 (Core/Spine): for 10K-card scaling 1000-card network bandwidth: Per GPU: 400 Gbps x 4 ports = 1600 Gbps = 200 GB/s (NVIDIA ConnectX-7) Total non-blocking bandwidth: 1024 x 400 Gbps = 409.6 Tbps
8.5.9 配置与并行影响
Check IB device status
ibstat ibstatus
# Check IB link rate
ibportstate -D 0 1
# Check RoCE interfaces and GIDshow_gids
NCCL specifies a specific IB
export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3 export NCCL_SOCKET_IFNAME=ib0
RoCE GID index configuration
export NCCL_IB_GID_INDEX=3 # RoCEv2 uses GID index 3 export NCCL_IB_TC=160 # Traffic Class (DSCP 40)
Test bandwidth
ib_write_bw -d mlx5_0 -F --report-gbits
Install Mellanox OFED driver
mount -o ro,loop MLNX_OFED_LINUX-23.10-1.1.9.0-ubuntu22.04-x86_64.iso /mnt
/mnt/mlnxofedinstall --all
/etc/init.d/openibd restart
# Test IB bandwidth
ib_write_bw -d mlx5_0 --report_gbits
# Expected: ~392 Gbps (NDR 400 Gbps line rate minus protocol overhead)
# Test NCCL performance git clone https://github.com/NVIDIA/nccl-tests.git
cd nccl-tests && make MPI=1
mpirun -np 8 -H node1:4,node2:4
./build/all_reduce_perf -b 1M -e 4G -f 2 -g 1
Key metric: BusBw (algorithm bandwidth) in GB/s at various message sizes
网络拓扑对并行策略的影响: •DP 的 AllReduce:在 Fat-Tree 拓扑中,AllReduce 通过多 Rail 并行,带宽瓶颈在 Leaf-Spine 链路 •PP 的 P2P:跨节点 P2P 使用 IB Send/Recv,延迟约 2-3 μs •EP 的 All-to-All:All-to-All 产生 O(P ) 个连接,显著增加 IB QP 数,需增大 NCCL_IB_QPS_PER_CONNECTION 参考文献:Mellanox/NVIDIA, “RDMA Aware Networks Programming User Manual”。Guo et al., “RDMA over Commodity Ethernet at Scale”, SIGCOMM 2016。Zhu et al., “Congestion Control for Large-Scale RDMA Deployments”, SIGCOMM 2015。
8.6 通信计算重叠技术
通信-计算重叠(Communication-Computation Overlap)决定分布式训练的效率上限,当通信完全被计算遮蔽时,系 统效率接近理论峰值。本节介绍几种代表性的重叠技术,包括 DeepSeek 的 DualPipe 和 DeepEP。
8.6.1 重叠基本原理
在传统的流水线调度中,通信和计算是顺序执行的: Traditional 1F1B (no overlap): GPU: [Forward][Send][Recv][Backward][Send][Recv] ◀── communication exposed ──▶ 理想的重叠模式应使通信完全隐藏在计算之后: Ideal overlap: GPU: [Forward (with background Send)][Backward (with background Recv)] ◀── communication fully hidden ──▶ 实现理想重叠需要三个条件:
- 异步通信原语(非阻塞 Send/Recv)
- 独立的计算和通信资源(CUDA Stream 分离)
- 足够的计算量支撑重叠时间
8.6.2 DDP 梯度桶化
DDP 的 Reducer 将梯度分组到不同的桶(bucket)中,实现按层粒度的通信-反向传播重叠:
# DDP Reducer internal logic
def autograd_hook_then_allreduce(bucket_idx):
# Hook called after each layer's backward
if all(tensor.grad is not None for tensor in bucket):
# Immediately launch async AllReduce for this bucket
bucket.allreduce_fut = dist.all_reduce(
bucket.grads, async_op=True) # backward continues on next layer, parallel with this bucket's AllReduce NCCL 的异步 AllReduce 会将通信操作提交到独立的 CUDA Stream,计算在默认 Stream 上继续。GPU 的硬件调度器自 动管理两个 Stream 的重叠。
8.6.3 FSDP2 预取重叠
DDP 仅做梯度 AllReduce,每个 GPU 保存完整参数副本。ZeRO-3(PyTorch FSDP/FSDP2)对参数本身也做 Sharding,每个 GPU 只保存 1/N 的参数切片,引入了 Forward/Backward AllGather(前向/反向计算前聚合完整参数) 和 ReduceScatter(反向后分散梯度)。 FSDP2(PyTorch 2.2+)通过 backward_prefetch 将这些通信提前,与相邻层的计算重叠:
# FSDP2 backward_prefetch overlap pattern
# During backward of layer N:
# 1. Compute backward for layer N
# 2. Async AllGather(layer_{N-1}) for next backward
# 3. ReduceScatter(layer_N grads)
# 4. Continue with layer N-1 backward
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import BackwardPrefetch, ShardingStrategy
model = FSDP(model,
sharding_strategy=ShardingStrategy.FULL_SHARD, # ZeRO-3 equivalent
backward_prefetch=BackwardPrefetch.BACKWARD_PRE, # prefetch next layer's AllGather
forward_prefetch=True, # AllGather layer N+1 during layer N forward
limit_all_gathers=True, # cap concurrent in-flight AllGathers) 关键权衡: BACKWARD_PRE 需要同时持有两层的完整参数(peak memory +1 shard),换来通信-计算重叠。实测在 Llama-7B / 8×A100 上, BACKWARD_PRE 相比 BACKWARD_POST 吞吐提升约 10–15%。 limit_all_gathers=True 限 制 in-flight AllGather 数量,防止显存因预取过多激增。
8.6.4 DualPipe 双向调度
DeepSeek DualPipe(DeepSeek-V3 Technical Report, 2024)是通信-计算重叠的最新突破。DualPipe 引入双向流水线 概念:在流水线的两个方向上都安排微批次的计算和通信,调度示意如图8-6所示。 DualPipe scheduling (PP=4, m=8) GPU Stage 0 Forward + Backward S1 Forward + Backward S2 (peer direction) (peer direction) S3 GPU Stage 3 Reverse pipeline 图8-6 DeepSeek DualPipe 双向流水线调度 DualPipe 在每个 GPU 上同时维护两条流水线方向的计算任务,使得在等待某一方向的通信时填充另一方向的计算。关键 技术包括:
- 双向微批次调度:上游和下游的微批次交错执行,填充等待间隙
- 异步 P2P 通信:使用 isend / irecv 替代 send / recv ,实现非阻塞通信
- 双 Stream 体系:计算 Stream 和通信 Stream 独立,利用 CUDA 的并发执行能力 DualPipe 将 PP 的气泡率逼近理论下限。
8.6.5 DeepEP 专家通信
DeepEP(DeepSeek, 2024)是针对 MoE 场景的通信库,核心价值在于让节点内外的 All-to-All 通信与专家计算重叠。从 重叠角度看,其四个设计要点:
- 高吞吐 Kernels:将 token 分发(dispatching)和合并(combining)实现为定制 CUDA kernel,绕过 host 端 software dispatch
- SM 资源隔离:将部分 SM 专用于通信处理,避免与计算 kernel 争抢 CUDA cores
- NVLink-RDMA 转发:利用本地 GPU 作为 NVLink ↔ RDMA 的转发代理,单向转发延迟仅增加约 2-3 μs
- Non-blocking All-to-All:支持在通信进行期间启动计算 kernel 通过 NVLink-RDMA 混合路径,节点内 All-to-All 直接走 NVSwitch,跨节点时先经 NVLink 汇聚到代理 GPU 再走 RDMA, 全程不经过 CPU 内存搬运,通信与 expert FFN 计算得以并行执行。
8.6.6 高级重叠实践
在大规模分布式训练中,梯度 AllReduce 与微批次调度都可以进一步与计算重叠。
- 异步梯度归约优化器
# Multi-level gradient bucketing
class AsyncAllReduceOptimizer:
def __init__(self, model, world_size):
self.buckets = partition_gradients_by_layer(model)
self.allreduce_handles = {}
def backward_hook(self, bucket_idx):
bucket = self.buckets[bucket_idx]
if bucket_idx > 0:
# Check if the previous bucket's AllReduce has completed
prev_handle = self.allreduce_handles[bucket_idx - 1]
if prev_handle is not None:
prev_handle.wait() # Block until previous bucket completes
# Submit async AllReduce for the current bucket
handle = dist.all_reduce(bucket.grads, async_op=True)
self.allreduce_handles[bucket_idx] = handle
def step(self):
# Wait for all pending AllReduce operations
for handle in self.allreduce_handles.values():
handle.wait()
self.optimizer.step()按层切分梯度桶,桶级 AllReduce 与前向反向计算重叠,前一个桶的归约完成后立即启动下一个。 2) 微批次调度优化 在流水线并行(PP)中,微批次调度的顺序可以主动优化重叠: Traditional 1F1B: GPU0: F0 F1 F2 F3 B0 B1 B2 B3 ▲─── warmup ───▲ Optimized (interleaved + communication hidden): GPU0: F0[SND] F1[RCV] F2[SND] F3 B0[RCV] B1[SND] B2[RCV] B3 ▲ communication proceeds asynchronously during computation ▲ isend / irecv 的关键优势在于:可以在接收侧还未完成 Recv 时就开始后续的计算(如果该计算不依赖于未到达的数 据)。 3) MoE 通信计算重叠 MoE 训练中的 All-to-All 通信是主要瓶颈。重叠策略包括:
- Token Dispatch 与计算重叠:在等待 All-to-All 发送完成期间,开始准备下一批 token 的路由
- Expert Computation 与 AllReduce 重叠:专家的本地梯度计算后,立即启动 AllReduce,同时进行下一专家的计算
- 微批次级别的通信-计算交替:多个微批次之间交替安排需要通信和不需要通信的操作
- DeepSpeed-MoE overlap 配置 DeepSpeed-MoE 的 overlap_comm 配置: { "moe": { "overlap_comm": true, "use_tutel": true // Tutel: Microsoft's MoE communication optimization library
8.6.7 技术总结与量化
}} 各重叠技术的重叠类型与量化收益如表8-7所示。 表8-7 通信计算重叠技术对比 技术 重叠类型 实现库/论文 性能提升 Gradient Bucketing Backward + AllReduce PyTorch DDP 10-20% 吞吐 Async AllReduce Backward + AllReduce NCCL 5-10% 吞吐 DualPipe PP Forward/Backward + P2P DeepSeek 约 30% 吞吐 DeepEP MoE All-to-All + Compute DeepSeek 20-40% 吞吐 GDR Async RDMA + Compute NCCL/NVIDIA 10-15% 延迟 Overlap Comm (ZeRO) ZeRO AllGather + Compute DeepSpeed 15-25% 吞吐 通信-计算重叠率(Overlap Ratio)的定义: Tcomm + Tcomp − Ttotal Overlap Ratio = Tcomm •100% 重叠:T = max(T , T ),通信完全隐藏 total comm comp •0% 重叠:T = T + T ,通信全部暴露 total comm comp PyTorch Profiler 可用于测量重叠率。实际生产中,即使最好的优化也只能达到 60-80% 的重叠率,因为总存在依赖强制 同步的时刻。 参考文献:DeepSeek-AI, “DeepSeek-V3 Technical Report”, 2024。He et al., “DeepEP: Communication Library for Mixture-of-Experts Models”, 2024。
8.7 MoE All-to-All
MoE(Mixture of Experts)模型中的 All-to-All 通信是训练推理的核心瓶颈。与 DDP 的 AllReduce 不同,MoE 的 All-to- All 产生的是高度不对称、动态变化的通信负载。本节深入分析 MoE All-to-All 的通信模式及其优化技术。
8.7.1 通信模式分析
MoE 层每步产生的 All-to-All 通信包含两个阶段,其交互过程如图8-7所示:
- Token Dispatching(分发):将 token 按路由结果分发到对应的专家
- Token Combining(合并):将专家输出按原始 token 顺序重新排列 GPU 0 (Expert 0-3) GPU 1 (Expert 4-7) GPU 2 (Expert 8-11) GPU 3 (Expert 12-15) Token Dispatching Route: 60% to E0, 20% to E5, 20% to E9 20% tokens ▶ E5 20% tokens ▶ E9 15% tokens ▶ E3 Route: 70% to E7, 15% to E3, 15% to E11 15% tokens ▶ E14 Expert Computation (local) Compute E0, E1, E2, E3 Token Combining Return processed tokens Return G1's original tokens Return G2's original tokens GPU 0 (Expert 0-3) GPU 1 (Expert 4-7) GPU 2 (Expert 8-11) GPU 3 (Expert 12-15) 图8-7 MoE All-to-All 的 Token 分发与合并
8.7.2 非对称负载问题
MoE All-to-All 的分布是极端不均匀的,路由器的选择决定了每个专家接收多少 token。设第 i 个 expert 收到 t 个 token (∑ t = T ⋅ k),则 GPU g 的通信量: i i Cgsend = ∑ tj ⋅ h bytes j∈experts(g) 当某些专家非常“热门”时(如 t ≫ ),该 GPU 会产生远多于平均的通信量,引发负载倾斜。 i Tk E
8.7.3 容量与负载均衡
容量因子(Capacity Factor, CF)是限制每个专家处理 token 数量的关键超参数。设每个专家的容量为: T ⋅k C = CF ⋅ E 其中 T 为总 token 数,k 为 top-k 值,E 为专家总数。CF = 1.0 表示每个专家恰好处理均分量的 token;CF = 1.25 允许 25% 的溢额。超出容量的 token 会被丢弃(token dropping),产生“容量溢出损失”。 三种主流负载均衡策略:
- 辅助损失(Auxiliary Loss):在训练损失中加入负载均衡惩罚项,鼓励路由器均匀分配 token。GShard 和 Switch Transformer 均采用此方法: E Laux = α ⋅ E ⋅ ∑ fi ⋅ Pi i=1
其中 f 为分配给专家 i 的 token 比例,P 为路由器对专家 i 的平均概率。 i i 2. 专家选择(Expert Choice):翻转路由方向,由专家主动选择 top-k 个 token,天然保证每个专家恰好处理 C 个 token,无需容量溢出。缺点是某些 token 可能被多个专家选中或完全未被选中。代表实现:GLaM(Expert Choice 论 文的基础架构)。 3. Top-k 路由 + 容量限制:在标准 top-k 路由基础上硬性限制每专家 token 数上限(如 DeepSeek-V3、Mixtral 采用的 top-2 路由配合容量约束)。超出容量的 token 路由到次优专家或直接丢弃。 三种策略的负载均衡性与实现复杂度对比如表8-8所示。 表8-8 负载均衡策略对比 策略 负载均衡性 实现复杂度 代表模型 Auxiliary Loss 中等 低 GShard, Switch Transformer Expert Choice 完美 中 GLaM Top-k + Capacity 高 低 Mixtral 8×7B, DeepSeek-V3
8.7.4 层次化 A2A 通信
解决通信不对称问题的关键技术是层次化 All-to-All(Hierarchical All-to-All): Phase 1 (intra-node): Execute All-to-All within each node (using NVLink) node-local: GPU_0..7 within Node A exchange tokens locally Phase 2 (inter-node): Execute All-to-All between nodes (using IB/RoCE) inter-node: Node A ◀▶ Node B, Node C, ... exchange remainders 层次化的核心优势: •节点内通信带宽高(NVLink 双向聚合带宽 A100 600 GB/s、H100/H200 900 GB/s、H800 400 GB/s,远高于 IB 约 50 GB/s per link),先处理大部分 token •节点间传输量大幅减少,经过节点内 All-to-All 后,只有需要跨节点的 token 才走 IB
8.7.5 框架实现对比
两大主流 MoE 训练框架的通信设计对比如表8-9所示。 表8-9 MoE框架通信设计对比 维度 DeepSpeed-MoE Megatron-LM MoE All-to-All 实现 torch.distributed.all_to_all 自定义 fused kernel 负载均衡 Auxiliary Loss + capacity factor Auxiliary Loss (简化版) 通信-计算重叠 Tutel 库的 overlap_comm 手动 interleaved scheduling 量化支持 FP16/BF16 FP8 (Transformer Engine) 专家并行度 EP (独立维度) EP + TP 混合 节点内通信 NCCL All-to-All 定制 CUDA kernel 路由策略 Top-2 门控 Top-2 门控 + 随机路由 (token drop 时) Megatron-LM 的 MoE 实现重点在 fused dispatch kernel,将 token 排序、分组、permutation 合并为单个 CUDA kernel launch,减少 3-4 次单独的 kernel launch 开销。DeepSpeed-MoE 通过 Microsoft Tutel 库实现通信-计算 overlap,将 All-to-All 通信与 expert FFN 计算流水线化。
8.7.6 融合 MoE 优化
融合 MoE(Fused MoE)将 token dispatch + expert computation + token combine 三个阶段的 kernel launch 合并为 一次 launch,消除中间结果的显存往返: // Fused MoE kernel: dispatch + compute + combine in one pass // Source: Megatron-LM, fused_moe_kernel.cuh global void fused_moe_kernel(
const half* input, // [T, H]
half* output, // [T, H]
const half* expert_weights, // [E, K, 4*K] and [E, 4*K, K]
const int* topk_ids, // [T, k]: expert ids per token
const float* topk_weights, // [T, k]: routing weights per tokenint num_experts, int top_k ) { // Each block handles one (token, expert) pair int token_idx = blockIdx.x / top_k; int k_idx = blockIdx.x % top_k; int expert_id = topk_ids[token_idx * top_k + k_idx]; float weight = topk_weights[token_idx * top_k + k_idx];
// Fetch corresponding input chunk
const half* x = input + token_idx * H;
// Fused: gate-up projection ▶ SiLU ▶ down projection
// All in shared memory, no intermediate global memory writeshared half shared_buf[MAX_SHARED_BUF]; // ... gate_and_up_proj, silu, down_proj using shared memory ... // Accumulate to output with atomicAdd atomic_add_scaled(&output[token_idx * H], expert_output, weight); } 融合 kernel 的关键收益:将原本 3 次全局显存读写(dispatch write, expert compute read/write, combine read)压缩 为 1 次写入(最终输出),显存带宽需求降低约 60%。在 H100 上,融合 MoE 的细粒度 kernel 相比传统分步实现可实现 1.3-1.8× 的吞吐提升。
8.7.7 DeepEP 架构详解
DeepEP(DeepSeek, 2024)是专门为 MoE 优化的通信库,其核心设计包括:
- 高吞吐 Dispatching/Combining Kernels // DeepEP dispatch kernel (simplified) global void deep_ep_dispatch_kernel(
const uint32_t* token_to_expert, // [T]: routing target for each token
const float* input, // [T, H]: input tensor
float* output_buffers, // [E]: per-expert buffer list
int* expert_token_counts // [E]: token count per expert) { int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid < T) { int expert = token_to_expert[tid]; int slot = atomicAdd(&expert_token_counts[expert], 1); // Write to the corresponding expert buffer memcpy(&output_buffers[expert][slot * H], &input[tid * H], H * sizeof(float)); } } 使用 GPU 原生的原子操作和块级并行,将 dispatching 吞吐从 CPU 调度方案的约 20 GB/s 提升到约 200 GB/s。 2) SM 资源隔离 DeepEP 将 GPU 的 SM 分为两部分: •计算 SMs(通常占 85-90%):执行 expert FFN 和 attention 计算 •通信 SMs(10-15%):专门运行 dispatching/combining 和 RDMA 数据传输 SM 资源隔离的 CUDA 实现: // Restrict kernel to a specific set of SMs cudaLaunchKernel_ex(..., numSms=0.15 * num_total_sms, ...); 这样可以避免通信 kernel 和计算 kernel 抢占 SM 资源,实现真正的并行。 3) NVLink-RDMA 混合路径 节点间传输时,DeepEP 使用本地 GPU 作为代理: Send: GPU mem ▶ NVLink ▶ Proxy GPU ▶ GPUDirect RDMA ▶ NIC ▶ IB ▶ ... Recv: ... ▶ IB ▶ NIC ▶ GPUDirect RDMA ▶ Proxy GPU ▶ NVLink ▶ Target GPU 代理 GPU 的额外转发仅增加约 2-3 μs 延迟,但完全避免 CPU 参与数据搬移。
8.7.8 通信压缩技术
针对 MoE 场景的通信压缩技术:
- Top-k 稀疏路由压缩:只传输 top-k 的 token(路由选择),其余的 token 不通信。这天然带来了 T /(T ⋅ k) 的压缩 all 比。
- 激活值量化:在 All-to-All 之前将 FP16 激活值压缩到 INT8: token − min tokenquantized = round ( )
scale 3. 基于 Token 重要性的选择性传输:只对高权重 token 使用 FP16 全精度,低权重 token 使用 INT4。这是一种实验性方 向(DeepSeek-V3 实际采用的是对所有 token 统一的 FP8 tile-wise 块量化,而非基于权重阈值的选择性精度切换)。
8.7.9 路由与部署优化
从通信角度优化路由:
- Expert 分配 Aware 路由:让路由选择优先分配到同一节点的 expert(减少跨节点通信): Routing Loss = − ∑ log pexpert + λ ⋅ 1[expert is on different node] t
- 容量感知路由:对即将达到 capacity 上限的 expert 降低路由概率,分布式地平衡负载。 容量感知路由的实现示例:
def capacity_aware_router(logits, expert_loads, capacity):
# Reduce logits for experts that are already at capacity
penalty = (expert_loads > 0.9 * capacity).float() * 1e9
return torch.softmax(logits - penalty, dim=-1)DeepEP 论文报告的性能对比(EP=64, 8 nodes × 8 GPUs)如表8-10所示。 表8-10 DeepEP性能对比 方案 All-to-All 延迟 (ms) 吞吐 (tokens/s) 通信利用率 NCCL All-to-All 4.2 12,800 38% NCCL + 层次化 3.1 17,500 52% DeepEP (NVLink only) 0.8 68,400 92% DeepEP (混合路径) 1.5 36,200 78% 节点内 DeepEP 接近 NVLink 的理论上限(92% 利用率);跨节点时由于 IB 带宽限制,利用率约 78%。 实际部署配置示例:
DeepEP configuration example
deepep_config = { "num_sms_for_communication": 12, # A100: 108 SMs, allocate 12 for communication "enable_quantization": True, "quantization_bits": 8, "token_dispatch_algorithm": "hierarchical", "use_nvlink_proxy": True, "proxy_gpu_indices": [0, 4], # GPU0 and GPU4 as NVLink-RDMA proxies } 这些高级通信优化使得 DeepSeek-V3(671B, 256 experts)能够在 2048 GPUs 上高效训练,总体 MFU 达到约 40%(考 虑到 MoE 稀疏计算的固有开销,这已经是极高的效率)。
8.7.10 延迟扩展规律
MoE All-to-All 的延迟随专家数和 token 数的扩展呈现不同的瓶颈模式。不同配置下的实测趋势如表8-11所示(8×H100 节点,每 token 维度 h = 4096,FP16)。 表8-11 MoE All-to-All延迟扩展 Token 数 (T) 专家数 (E) All-to-All 延迟 瓶颈 2048 8 0.12 ms Kernel launch overhead 2048 64 0.85 ms NVSwitch latency dominated 8192 64 2.1 ms Bandwidth dominated 8192 256 5.8 ms Multi-hop NVSwitch + bandwidth 32768 256 18.3 ms IB inter-node bandwidth limited 关键观察: •小 T 大 E 场景(如推理):延迟受 NVSwitch 多跳开销主导,节点内 All-to-All 的跳数为 log (E ) 2 per-node •大 T 场景(如训练):带宽成为瓶颈,延迟与 T ⋅ h ⋅ 2/B 线性增长 eff •跨节点:IB 带宽(约 50 GB/s)远低于 NVLink,成为主要瓶颈。层次化 All-to-All 通过节点内预处理可降低约 60-70% 的跨节点通信量 在 DeepSeek-V3 的 256 专家 × 2048 GPU 配置中,每步 All-to-All 通信时间约占训练步时的 15-25%,是仅次于 expert FFN 计算的第二大耗时组件。 参考文献:He et al., “DeepEP: Communication Library for Mixture-of-Experts Models”, 2024。Lepikhin et al., “GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding”, ICLR 2021。 Rajbhandari et al., “DeepSpeed-MoE”, ICML 2022。
8.8 NCCL 性能调试与调优
本节提供 NCCL 性能调试的完整实践指南,覆盖基准测试、环境变量调优与生产问题排查。
8.8.1 基准测试工具
首先安装并使用 nccl-tests 获取系统通信性能基线:
Install nccl-tests
git clone https://github.com/NVIDIA/nccl-tests.git cd nccl-tests && make MPI=1 CUDA_HOME=/usr/local/cuda
# Run AllReduce performance test
mpirun -np 8 ./build/all_reduce_perf -b 8 -e 2G -f 2 -g 1
# Parameter description:
# -b 8: start message size 8
# -e 2G: end message
# -f 2: double message size
# -g 1: 1 GPU per nodenccl-tests 输出的关键字段解读:
# out-of-place in-place
# size count type redop time algbw busbw error time algbw busbw error
# (B) (elements) (us) (GB/s) (GB/s) (us) (GB/s) (GB/s)1048576 262144 float sum 153.2 6.84 11.97 0.00 152.1 6.89 12.06 0.00 134217728 33554432 float sum 3184.2 42.15 73.67 0.00 3180.8 42.20 73.75 0.00 1073741824 268435456 float sum 17145 62.66 109.63 0.00 17125 62.70 109.72 0.00 •algbw:算法带宽(algorithm bandwidth)= 消息大小 / 时间。对小消息偏低正常 •busbw:总线带宽(bus bandwidth)= algbw × 2(P − 1)/P ,表示网络链路上实际传输的比特率。应接近理论值: A100 NVLink 约 600 GB/s,IB HDR 约 200 Gb/s(25 GB/s) All-to-All 基准测试:
8.8.2 环境变量调优
mpirun -np 8 ./build/alltoall_perf -b 8 -e 128M -f 2 -g 1 在生产环境中,以下环境变量是最常用的调优参数:
=== Network interface configuration ===
Specify the network interfaces to use
export NCCL_SOCKET_IFNAME=ib0,ib1,ib2,ib3 # Multiple IB interfaces export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3
=== RoCE-specific configuration
export NCCL_IB_GID_INDEX=3 # RoCEv2 uses GID index 3
Query available GIDs: show_gids
export NCCL_IB_TC=160 # Traffic Class = DSCP 40 (AI training traffic) export NCCL_IB_SL=0 # Service Level (IB only) export NCCL_IB_TIMEOUT=22 # IB timeout (default 22, increase occasionally)
=== GDR level ===
export NCCL_NET_GDR_LEVEL=SYS # SYS (5) = most permissive: allow GDR across any topology
Use lower levels (LOC/PIX/PXB/PHB) to restrict GDR for debugging.
=== Channel and communication
export NCCL_MIN_NCHANNELS=4 # Minimum number of channels export NCCL_MAX_NCHANNELS=32 # Maximum number of channels (auto-selected by NCCL) export NCCL_IB_QPS_PER_CONNECTION=4 # QPs per connection (improves bandwidth) export NCCL_BUFFSIZE=8388608 # Comm buffer size in bytes (larger improves big-message bandwidth)
=== Debugging and logging ===
export NCCL_DEBUG=INFO export NCCL_DEBUG_SUBSYS=INIT,GRAPH,NET
Generate topology dump
export NCCL_TOPO_DUMP_FILE=/tmp/nccl_topo.xml
=== Quick diagnostic switches ===
export NCCL_IB_DISABLE=0 # 0=enable IB, 1=Socket only (slow) export NCCL_P2P_DISABLE=0 # 0=enable P2P, 1=disable GPU direct export NCCL_SHM_DISABLE=0 # 0=enable shared memory, 1=disable
8.8.3 拓扑与问题诊断
# 1. View GPU topology matrix
nvidia-smi topo -m
# 2. View detailed GPU-NIC
nvidia-smi topo -mp
# 3. Generate NCCL topology XMLexport NCCL_TOPO_DUMP_FILE=./topo.xml
python -c "import torch; torch.distributed.init_process_group('nccl')"
# 4. View PCIe topology (GPU to NIC links)
lspci -tv | grep -E "NVIDIA|Mellanox"
# 5. View NUMA topology
numactl --hardware
# 6. Verify GPU-NIC affinity
for i in $(seq 0 7); do
cat /sys/class/infiniband/mlx5_${i}/device/numa_nodedone
8.8.4 常见性能问题
NCCL 调试中的常见性能问题、症状与修复方案如表8-12所示。 表8-12 常见NCCL性能问题与修复 问题 症状 诊断命令 修复方案 NCCL_DEBUG=INFO 查看 QP 创 QP 数量不足 busbw 远低于理论值 建日志 增大 NCCL_IB_QPS_PER_CONNECTION=8 问题 症状 诊断命令 修复方案 GID Index 错 NCCL init 失败(RoCE show_gids 查看正确 GID NCCL_IB_GID_INDEX=3 (RoCEv2) 误 环境) PKey 错误 IB 连接拒绝 ibstat 查看 PKey 联系管理员设置正确 PKey 跨 NUMA 通 AllReduce 性能不对称 限制 GPU 到同一 NUMA: 信 nvidia-smi topo -m CUDA_VISIBLE_DEVICES=0,1,2,3 网卡中断风暴 延迟抖动大 查看中断 mpstat -I CPU 调优 irqbalance, 网卡 RSS IB 速率协商 busbw 固定在某较低值 ibstat 查看速率 检查 IB 线缆和端口配置 错误 共享内存冲突 P2P 通信退化 NCCL_P2P_DISABLE=1 测试 增大共享内存: mount -o remount,size=16G
8.8.5 诊断脚本模板
/dev/shm
#!/bin/bash
# NCCL diagnostic script echo "=== GPU Topology ==="
nvidia-smi topo -m
echo "=== IB Device Status ==="
ibstat 2>/dev/null || echo "No IB devices"
echo "=== RoCE GIDs ==="
show_gids 2>/dev/null || echo "Not RoCE"
echo "=== NCCL Test (Quick) ==="
NCCL_DEBUG=WARN mpirun -np 8
./all_reduce_perf -b 1M -e 256M -f 2 -g 1 2>&1 | tail -5
echo "=== NCCL Detailed Log ==="
8.8.6 生产配置模板
NCCL_DEBUG=INFO NCCL_DEBUG_SUBSYS=INIT \
mpirun -np 2 ./all_reduce_perf -b 1M -e 1M -g 1 2>&1 | \
grep -E "(Channel|Ring|Tree|NET/.*Connected)"
#!/bin/bash
# Production NCCL configuration (8×H100 DGX + 8×ConnectX-7)
# Network configurationexport NCCL_SOCKET_IFNAME=ib0 export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 export NCCL_IB_GID_INDEX=3 export NCCL_IB_TC=160
Performance optimization
export NCCL_NET_GDR_LEVEL=SYS export NCCL_IB_QPS_PER_CONNECTION=4 export NCCL_IB_TIMEOUT=22 export NCCL_MIN_NCHANNELS=8 export NCCL_MAX_NCHANNELS=32
CUDA optimization
export CUDA_DEVICE_MAX_CONNECTIONS=8
# Debugging
# export NCCL_DEBUG=WARN
# Temporarily enable for troubleshooting:
# Async error handlingexport NCCL_ASYNC_ERROR_HANDLING=1
8.8.7 性能数据分析
# Timeout settings (configured in torch.distributed.init_process_group, not NCCL env vars)
# dist.init_process_group(timeout=datetime.timedelta(seconds=3600))
# See also: TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC, TORCH_NCCL_BLOCKING_WAIT在 8×A100 DGX(NVLink 600 GB/s)+ 8×IB HDR 环境下的典型数据如表8-13所示。 表8-13 消息大小与带宽效率 消息大小 busbw (NVLink) busbw (IB HDR) 效率 1 MB 10.2 GB/s 3.1 GB/s Low (latency dominated) 64 MB 350 GB/s 15 GB/s Medium 256 MB 520 GB/s 22 GB/s High (near bandwidth limit) 1 GB 570 GB/s 23 GB/s Very high NVLink 理论 600 GB/s,实测 570 GB/s(95%);IB HDR 理论 25 GB/s,实测 23 GB/s(92%)。
8.8.8 并行策略调优
不同并行策略的关键 NCCL 参数建议如表8-14所示。 表8-14 并行策略NCCL参数建议 并行策略 关键 NCCL 参数 建议值 TP (节点内) NCCL_MIN_NCHANNELS 8-16 (NVSwitch 全连接) DP (跨节点) NCCL_IB_QPS_PER_CONNECTION 4-8 (大消息 AllReduce) PP (P2P) NCCL_IB_DISABLE=0 确保 IB 启用 EP (All-to-All) NCCL_MAX_NCHANNELS 32 (All-to-All 多通道并行) 并行策略 关键 NCCL 参数 建议值 FSDP (AllGather) NCCL_NET_GDR_LEVEL SYS (GDR 高带宽路径) 参考文献:NCCL 官方调试指南: https://docs.nvidia.com/deeplearning/nccl/user- guide/docs/troubleshooting.html。nccl-tests GitHub 仓库。AWS, “Scalable distributed training with NCCL on Amazon EKS”。