GPU 运维实战系列 · 第 T8 篇

DOCA perftest 与高级网络测试:从 GPUDirect 到定制化压测

当集群规模从 8 卡扩展到 256 卡,网络不再是"能通就行"的辅助通道,而是决定训练吞吐的命脉。本篇以 DOCA perftest 为核心,覆盖 GPUDirect RDMA 直连、多 QP 并发、长稳测试、自动化压测框架与可视化分析,最终在真实 256 卡集群上完成全连接矩阵验收。

系列 GPU 运维实战 编号 T8 定位 压测工具线 前置 T6 ib_perftest 基础 受众 GPU 集群运维 / 性能工程师

01DOCA 框架定位与 perftest 的关系

在 T6 篇中我们用 ib_write_bw、ib_send_lat 等经典 perftest 工具完成了基础带宽/延迟测量。这些工具诞生于 InfiniBand 时代,稳定可靠,但在面对 BlueField DPU、GPUDirect RDMA、硬件加速流水线等新场景时,暴露出三个短板:无法直接操作 GPU 内存、不支持 DPU offload 路径、缺乏可编程的定制化参数。

NVIDIA DOCA(Data Center Infrastructure-on-a-Chip Architecture)框架正是为补齐这些短板而生。它不是 perftest 的替代品,而是 perftest 的超集与加速器。

1.1 DOCA 是什么

DOCA 是 NVIDIA 面向 BlueField DPU 和 ConnectX 网卡的统一软件开发框架,基于 DPDK 数据面加速技术,核心定位有三层:

DOCA Core

底层 SDK · C/Rust API

提供对硬件加速引擎的直接访问:RDMA、Flow(流表)、VIRTIO(虚拟化卸载)、Crypto(加密卸载)。perftest 依赖的 RDMA verb 在这一层。

类比:Linux 内核 syscall 层。

DOCA Services

中间件 · 预构建服务

DOCA Firefly(P4 可编程交换机仿真)、DOCA HBN(Host-Based Networking)、DOCA DPDK(数据面加速)。这些服务运行在 DPU 上,对主机透明。

类比:systemd 管理的常驻服务。

DOCA Libraries

上层库 · 应用集成

DOCA Comch(DPU-Host 通信通道)、DOCA Sha(Shared Receive Queue)、DOCA DMA(DPU 上的 DMA 引擎)。perftest 的 GPUDirect 扩展就挂在这里。

类比:glibc / libstdc++ 等用户态库。

1.2 DOCA perftest 与经典 perftest 的关系

维度ib_perftest(经典)doca_perftest(DOCA)
源码关系独立项目 rdma-corefork 自 ib_perftest,扩展 DOCA 后端
GPU 内存支持需手动 patch + CUDA 集成原生 --use_cuda 参数
DPU offload不支持支持 DPU 上转发路径
DPDK 数据面不支持可选 DPDK 加速模式
输出格式纯文本 stdout文本 + JSON + CSV 可选
多 QP 并发支持但参数有限精细 QP/连接矩阵控制
编译依赖rdma-corerdma-core + DOCA SDK + CUDA(可选)
关键认知

如果你的集群没有 BlueField DPU,也没有 GPUDirect RDMA 需求,经典 ib_perftest 完全够用。DOCA perftest 的价值在于GPU 内存直连和DPU 卸载路径这两个经典工具覆盖不到的场景。不要为了"用新工具"而引入 DOCA SDK 的编译复杂度。

1.3 DOCA 在 GPU 集群中的位置

GPU H100 CUDA Memory GPU H100 CUDA Memory ConnectX-7 + BlueField-3 DPU DOCA SDK perftest / DPDK /Flowth="2"/> IB网络 400G NDR GPUDirect RDMA PCIe BAR1 映射 API 调用 硬件
图 1:DOCA 在 GPU 集群中的层次位置 — GPU 内存经 GPUDirect 直达 NIC/DPU,DOCA SDK 提供编程接口

02DOCA perftest 安装与编译

DOCA perftest 的安装比经典 perftest 复杂不少,主要因为 DOCA SDK 本身有版本矩阵要求。以下步骤在 NVIDIA 官方支持的 Ubuntu 22.04 / RHEL 9 上验证通过。

2.1 环境前置检查

bash
# 1. 确认网卡固件版本(ConnectX-7 / BlueField-3)
mlxconfig -d /dev/mst/mt4131_pciconf0 q | grep -i "fw_version"

# 2. 确认 OFED 驱动
ofed_info -s
# 期望输出: MLNX_OFED_LINUX-24.10-0.6.0

# 3. 确认 CUDA(GPUDirect 必需)
nvidia-smi --query-gpu=driver_version,name --format=csv,noheader
# 期望输出: 550.90.07, NVIDIA H100 80GB HBM3

# 4. 确认 nvidia-peermem 模块已加载
lsmod | grep nvidia_peermem
# 期望输出: nvidia_peermem  16384  0

# 5. 确认 GPU 与 NIC 的 PCIe 拓扑(同 RC 下才能 GPUDirect)
nvidia-smi topo -m

2.2 安装 DOCA SDK

DOCA SDK 通过 NVIDIA 官方仓库分发,不同版本对应不同的 BlueField 固件版本。这里以 DOCA 2.7 为例:

bash
# 添加 DOCA 仓库(Ubuntu 22.04)
curl -fsSL https://linux.mellanox.com/public/DOCA-GPG-KEY \
  | gpg --dearmor -o /usr/share/keyrings/doca-key.gpg
echo "deb [signed-by=/usr/share/keyrings/doca-key.gpg] \
  https://linux.mellanox.com/public/DOCA_2.7.0/ubuntu22.04/x86_64 ./" \
  > /etc/apt/sources.list.d/doca.list

apt-get update

# 安装 DOCA SDK 开发包(编译 perftest 所需)
apt-get install -y \
  doca-sdk-perftest \
  doca-sdk-rdma \
  doca-sdk-flow \
  doca-sdk-dpdk \
  doca-sdk-libs \
  doca-sdk-samples

# 安装运行时
apt-get install -y doca-runtime

# 验证安装
dpkg -l | grep doca-sdk | awk '{print $2, $3}'
预期输出 doca-sdk-perftest 2.7.0-1.2.9.0 doca-sdk-rdma 2.7.0-1.2.9.0 doca-sdk-flow 2.7.0-1.2.9.0 doca-sdk-dpdk 2.7.0-1.2.9.0 doca-sdk-libs 2.7.0-1.2.9.0 doca-runtime 2.7.0-1.2.9.0

2.3 编译 DOCA perftest

DOCA SDK 安装包自带预编译的 doca_perftest 二进制,但生产环境通常需要从源码编译以启用 GPUDirect 支持和自定义参数:

bash
# 获取源码
git clone -b doca-2.7 https://github.com/Mellanox/perftest.git
cd perftest

# 编译配置:启用 CUDA + DOCA 后端
./autogen.sh
./configure \
  --prefix=/opt/doca-perftest \
  --with-cuda=/usr/local/cuda \
  --enable-doca \
  --enable-gpudirect \
  --enable-dpdk

make -j$(nproc)
make install

# 验证编译结果
/opt/doca-perftest/bin/doca_perftest --help | head -20

2.4 验证安装正确性

bash
# 基础回环测试(不需对端,验证二进制可用)
/opt/doca-perftest/bin/doca_perftest -d mlx5_0 \
  --output json | python3 -m json.tool

# GPU 内存检测(确认 GPUDirect 路径可用)
/opt/doca-perftest/bin/doca_perftest -d mlx5_0 \
  --use_cuda 0 -s 1048576 -n 100

# 查看 DOCA 后端是否激活
/opt/doca-perftest/bin/doca_perftest -d mlx5_0 --report-doca-info
report-doca-info 输出示例 DOCA Backend: Active (v2.7.0) Device: mlx5_0 (ConnectX-7, FW 28.39.1002) GPUDirect RDMA: Enabled (GPU 0: H100 80GB, PCIe 17:00.0) DPDK Acceleration: Available (not active in this run) DPU Offload: Not detected (no BlueField attached)
常见编译陷阱

问题 1:--with-cuda 找不到 cudatypes.h。原因:CUDA toolkit 未安装或路径不对。解决:apt install nvidia-cuda-toolkit 或指定 --with-cuda=/usr/local/cuda-12.4。

问题 2:链接时 undefined reference to doca_rdma_*。原因:DOCA SDK 版本与源码分支不匹配。解决:确认 git branch 与 dpkg -l doca-sdk-rdma 大版本一致。

问题 3:运行时 Failed to open GPU device。原因:nvidia-peermem 未加载。解决:modprobe nvidia-peermem。

03GPUDirect RDMA 测试:绕过 CPU 的数据高速公路

普通 perftest 的数据路径是 GPU → CPU 内存 → NIC → 网络,数据要经过一次 CPU 内存拷贝(bounce buffer)。GPUDirect RDMA 通过 PCIe P2P 和 BAR1 映射,让数据直接走 GPU → NIC → 网络,CPU 完全不参与数据搬运。

3.1 数据路径对比

传统路径(CPUbounce buffer) GPU Mem CPU Mem NIC 网络 拷贝 拷贝 3 跳 · CPU 参与 · ~85% 理论带宽 GPUDirectRDMA路径 GPU Mem NIC 网络 PCIe P2P 直达 1 跳 · CPU 旁路 · ~97% 理论带宽
图 2:传统 RDMA vs GPUDirect RDMA 数据路径 — 后者消除两次 CPU 内存拷贝

3.2 GPUDirect RDMA 压测命令

服务端(GPU 0 接收)

bash · 服务端
# 在 node-01 上启动服务端,使用 GPU 0 的显存作为接收缓冲
doca_perftest -d mlx5_0 \
  --use_cuda 0 \
  -s 1048576 \
  -n 5000 \
  -t 8 \
  --output csv

客户端(GPU 0 发送)

bash · 客户端
# 在 node-02 上连接 node-01,GPU 0 显存发送
doca_perftest -d mlx5_0 \
  --use_cuda 0 \
  -s 1048576 \
  -n 5000 \
  -t 8 \
  --output csv \
  node-01

3.3 性能对比实测

以下是在两台 H100 服务器(ConnectX-7 400G NDR)上的实测对比,消息大小 1MB,8 线程:

测试模式带宽 (Gb/s)带宽利用率CPU 利用率说明
ib_write_bw(CPU 内存)372.493.1%12%经典 perftest 基线
ib_write_bw + GPU bounce318.779.7%28%GPU→CPU→NIC,有拷贝开销
doca_perftest --use_cuda389.197.3%2%GPUDirect 直达,CPU 近乎空闲
doca_perftest + DPDK 加速391.697.9%1%DPDK 数据面进一步降低开销
+22.1%
GPUDirect vs GPU bounce 带宽提升
93%
CPU 利用率下降幅度
2.0μs
延迟降低(消除拷贝)
97.3%
NDR 400G 带宽利用率
类比

传统 RDMA 像快递要经过小区中转站(CPU 内存)再发出去,每次都要卸货、分拣、重新装车。GPUDirect RDMA 像快递车直接从仓库(GPU 显存)上高速(NIC),中转站完全不需要参与。对于大模型训练中动辄几十 GB 的 AllReduce 通信,省掉的这两次拷贝就是实打实的训练时间。

04DOCA perftest 命令详解

DOCA perftest 的命令行参数在经典 perftest 基础上扩展了 DOCA 专属参数。理解参数体系是定制化压测的前提。

4.1 核心参数分类

分类参数说明默认值
设备与后端-d <dev>RDMA 设备名(如 mlx5_0)系统第一个
--doca-backendDOCA 后端模式:rdma / dpdk / dpurdma
--report-doca-info打印 DOCA 后端状态后退出—
GPU 相关--use_cuda <id>使用指定 GPU 的显存作为缓冲禁用
--gpu-direct强制启用 GPUDirect RDMA 路径auto
--gpu-rdma-wcGPU 内存使用 Write-Combining 映射禁用
--cuda-batch-sizeCUDA 操作批大小1
测试控制-s <bytes>消息大小(字节)65536
-n <count>迭代次数1000
-t <threads>并发线程数(QP 数)1
--duration <sec>按时间运行(秒),覆盖 -n禁用
输出格式--output <fmt>输出格式:text / json / csvtext
--report-both同时输出带宽和延迟禁用
--log-file <path>日志写入文件stdout

4.2 与 ib_write_bw 的参数对比

bash · 对比示例
# ===== 经典 ib_write_bw =====
# 服务端
ib_write_bw -d mlx5_0 -s 1048576 -n 5000 --report_gbits
# 客户端
ib_write_bw -d mlx5_0 -s 1048576 -n 5000 --report_gbits node-01

# ===== DOCA perftest 等价命令 =====
# 服务端
doca_perftest -d mlx5_0 -s 1048576 -n 5000 --output csv \
  --test-type write_bw
# 客户端
doca_perftest -d mlx5_0 -s 1048576 -n 5000 --output csv \
  --test-type write_bw node-01

# ===== DOCA perftest 独有:GPU 直连 =====
# 服务端
doca_perftest -d mlx5_0 --use_cuda 0 -s 1048576 -n 5000 \
  --test-type write_bw --output json
# 客户端
doca_perftest -d mlx5_0 --use_cuda 0 -s 1048576 -n 5000 \
  --test-type write_bw --output json node-01

4.3 输出格式解读

JSON 输出(适合脚本解析)

doca_perftest --output json { "test_type": "write_bw", "device": "mlx5_0", "gpu": {"enabled": true, "device_id": 0, "name": "H100"}, "message_size": 1048576, "iterations": 5000, "threads": 8, "results": { "bandwidth_gbps": 389.12, "bandwidth_utilization_pct": 97.28, "avg_latency_us": 21.4, "p99_latency_us": 24.1, "cpu_usage_pct": 2.1 }, "doca_backend": "rdma", "timestamp": "2026-11-02T14:30:00+08:00" }

CSV 输出(适合批量收集)

doca_perftest --output csv test_type,device,gpu_id,msg_size,iterations,threads,bandwidth_gbps,utilization_pct,avg_lat_us,p99_lat_us,cpu_pct,timestamp write_bw,mlx5_0,0,1048576,5000,8,389.12,97.28,21.4,24.1,2.1,2026-11-02T14:30:00+08:00

4.4 测试类型一览

--test-type对应经典工具语义典型场景
write_bwib_write_bwRDMA Write 带宽大消息吞吐
read_bwib_read_bwRDMA Read 带宽远程读取性能
send_bwib_send_bwSend/Recv 带宽通用发送
write_latib_write_latRDMA Write 延迟小消息延迟
read_latib_read_latRDMA Read 延迟远程读延迟
send_latib_send_latSend/Recv 延迟RTT 测量
atomicib_atomic_lat原子操作延迟同步原语验证

05定制化压测脚本框架

裸跑 perftest 命令只适合临时验证。生产环境需要参数化、多场景、自动收集结果的压测框架。以下是一个基于 Python 的轻量框架,覆盖参数化、场景编排、结果收集三个核心能力。

5.1 框架设计

参数层

YAML 配置 → 参数空间

消息大小、线程数、测试类型、GPU ID、持续时间等全部参数化,支持笛卡尔积展开。

执行层

SSH → 远程并行调度

通过 paramiko/asyncssh 并行在多节点启动 perftest,自动管理服务端/客户端配对。

收集层

CSV/JSON → SQLite

所有结果统一写入 SQLite,支持按节点对、时间、参数维度查询。

5.2 配置文件

yaml · perftest_config.yaml
# 压测配置
cluster:
  nodes:
    - {name: node-01, ip: "10.0.1.1", device: mlx5_0, gpu: 0}
    - {name: node-02, ip: "10.0.1.2", device: mlx5_0, gpu: 0}
    - {name: node-03, ip: "10.0.1.3", device: mlx5_0, gpu: 0}
    - {name: node-04, ip: "10.0.1.4", device: mlx5_0, gpu: 0}

tests:
  - name: "gpu_rdma_write_bw"
    test_type: write_bw
    use_cuda: true
    msg_sizes: [65536, 262144, 1048576, 4194304]
    threads: [1, 4, 8, 16]
    iterations: 5000
    output: csv

  - name: "gpu_rdma_write_lat"
    test_type: write_lat
    use_cuda: true
    msg_sizes: [64, 256, 1024, 4096]
    threads: 1
    iterations: 10000
    output: csv

  - name: "cpu_rdma_baseline"
    test_type: write_bw
    use_cuda: false
    msg_sizes: [1048576]
    threads: [8]
    iterations: 5000
    output: csv

execution:
  mode: full_mesh
  parallel_pairs: 4
  timeout_sec: 120
  result_db: /data/perftest/results.db

5.3 压测引擎核心代码

python · perftest_runner.py
#!/usr/bin/env python3
"""DOCA perftest 定制化压测引擎"""
import asyncio, asyncssh, sqlite3, yaml, json, time
from itertools import product
from pathlib import Path

class PerftestRunner:
    def __init__(self, config_path: str):
        with open(config_path) as f:
            self.cfg = yaml.safe_load(f)
        self.db = self._init_db(self.cfg['execution']['result_db'])

    def _init_db(self, db_path: str) -> sqlite3.Connection:
        Path(db_path).parent.mkdir(parents=True, exist_ok=True)
        conn = sqlite3.connect(db_path)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS results (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                test_name TEXT, test_type TEXT,
                server_node TEXT, client_node TEXT,
                msg_size INT, threads INT,
                use_cuda BOOLEAN, gpu_id INT,
                bandwidth_gbps REAL, utilization_pct REAL,
                avg_latency_us REAL, p99_latency_us REAL,
                cpu_pct REAL, timestamp TEXT,
                raw_output TEXT
            )
        """)
        return conn

    def _build_cmd(self, test: dict, node: dict, is_server: bool,
                   peer_ip: str = None) -> str:
        """构造 doca_perftest 命令行"""
        cmd = f"doca_perftest -d {node['device']} --output json"
        cmd += f" --test-type {test['test_type']}"
        cmd += f" -s {test.get('_msg_size', 1048576)}"
        cmd += f" -n {test['iterations']}"
        threads = test.get('_threads', 1)
        cmd += f" -t {threads}"
        if test.get('use_cuda'):
            cmd += f" --use_cuda {node['gpu']}"
        if not is_server and peer_ip:
            cmd += f" {peer_ip}"
        return cmd

    def _expand_scenarios(self, test: dict) -> list:
        """展开参数笛卡尔积"""
        sizes = test['msg_sizes']
        threads = test['threads'] if isinstance(test['threads'], list) \
                  else [test['threads']]
        scenarios = []
        for sz, th in product(sizes, threads):
            s = dict(test)
            s['_msg_size'] = sz
            s['_threads'] = th
            scenarios.append(s)
        return scenarios

    async def _run_pair(self, server: dict, client: dict,
                        test: dict) -> dict:
        """在一对节点上执行一次测试"""
        cmd_server = self._build_cmd(test, server, is_server=True)
        cmd_client = self._build_cmd(test, client, is_server=False,
                                     peer_ip=server['ip'])
        async with asyncssh.connect(server['ip'], username='root') as ssh_s, \
                   asyncssh.connect(client['ip'], username='root') as ssh_c:
            await ssh_s.run(cmd_server, check=False)
            await asyncio.sleep(2)
            result = await ssh_c.run(cmd_client, check=True)
            return json.loads(result.stdout)

    async def run_all(self):
        """执行全部测试场景"""
        nodes = self.cfg['cluster']['nodes']
        mode = self.cfg['execution']['mode']
        parallel = self.cfg['execution']['parallel_pairs']

        if mode == 'full_mesh':
            pairs = [(s, c) for i, s in enumerate(nodes)
                     for c in nodes[i+1:]]
        else:
            pairs = [(nodes[i], nodes[i+1])
                     for i in range(0, len(nodes)-1, 2)]

        for test in self.cfg['tests']:
            scenarios = self._expand_scenarios(test)
            for scenario in scenarios:
                sem = asyncio.Semaphore(parallel)
                tasks = []
                for srv, cli in pairs:
                    async def bounded_run(s=srv, c=cli):
                        async with sem:
                            return await self._run_pair(s, c, scenario)
                    tasks.append(bounded_run())
                results = await asyncio.gather(*tasks,
                                               return_exceptions=True)
                for (srv, cli), res in zip(pairs, results):
                    self._store_result(test, scenario, srv, cli, res)

    def _store_result(self, test, scenario, srv, cli, res):
        if isinstance(res, Exception):
            print(f"FAIL: {srv['name']}->{cli['name']}: {res}")
            return
        r = res.get('results', {})
        self.db.execute(
            "INSERT INTO results VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            (test['name'], test['test_type'], srv['name'], cli['name'],
             scenario['_msg_size'], scenario['_threads'],
             test.get('use_cuda', False), srv.get('gpu'),
             r.get('bandwidth_gbps'), r.get('bandwidth_utilization_pct'),
             r.get('avg_latency_us'), r.get('p99_latency_us'),
             r.get('cpu_usage_pct'), res.get('timestamp'),
             json.dumps(res)))
        self.db.commit()

if __name__ == '__main__':
    runner = PerftestRunner('perftest_config.yaml')
    asyncio.run(runner.run_all())
    print("压测完成,结果已存入 SQLite")

5.4 运行与结果查询

bash
# 执行压测
python3 perftest_runner.py

# 查询结果:按节点对汇总平均带宽
sqlite3 /data/perftest/results.db << 'EOF'
.mode column
.headers on
SELECT server_node, client_node,
       ROUND(AVG(bandwidth_gbps), 1) AS avg_bw_gbps,
       ROUND(MIN(bandwidth_gbps), 1) AS min_bw_gbps,
       ROUND(MAX(bandwidth_gbps), 1) AS max_bw_gbps,
       COUNT(*) AS samples
FROM results
WHERE test_name = 'gpu_rdma_write_bw'
GROUP BY server_node, client_node
ORDER BY avg_bw_gbps DESC;
EOF
查询结果示例 server_node client_node avg_bw_gbps min_bw_gbps max_bw_gbps samples node-01 node-02 389.1 387.2 391.4 16 node-01 node-03 388.7 386.1 390.8 16 node-01 node-04 389.0 387.5 391.2 16 node-02 node-03 388.5 386.3 390.1 16 node-02 node-04 389.3 387.8 391.6 16 node-03 node-04 388.9 386.7 390.5 16

06多连接并发与全连接矩阵测试

单 QP(Queue Pair)测试只反映单连接极限。真实训练中每对 GPU 之间有多个并发连接(NCCL 默认 8 个 transport channel),多 QP 并发测试才能反映真实负载下的网络表现。

6.1 多 QP 并发测试

bash
# 多 QP 测试:16 个并发 QP,模拟 NCCL 多通道
# 服务端
doca_perftest -d mlx5_0 --use_cuda 0 \
  -s 1048576 -n 10000 \
  -t 16 \
  --qp-type rc \
  --output json \
  --report-both

# 客户端
doca_perftest -d mlx5_0 --use_cuda 0 \
  -s 1048576 -n 10000 -t 16 \
  --qp-type rc --output json --report-both \
  node-01

6.2 QP 数量对带宽的影响

QP 数带宽 (Gb/s)利用率说明
1312.478.1%单连接未打满
2365.891.5%明显提升
4381.295.3%接近线性扩展
8389.197.3%NCCL 默认值,接近饱和
16390.397.6%收益递减
32389.897.5%QP 开销开始抵消收益
QP 数量选择建议

对于 400G NDR 网卡,8 个 QP 是性价比最高的配置,也是 NCCL 的默认值。超过 16 个 QP 后,PCIe 带宽和 NIC 引擎调度开销开始成为瓶颈,收益递减甚至负收益。压测时建议固定扫 1/2/4/8/16 五个点即可。

6.3 全连接矩阵测试

对于 N 节点集群,全连接矩阵需要测试 C(N,2) = N×(N-1)/2 对节点。8 节点 = 28 对,16 节点 = 120 对,32 节点 = 496 对。必须并行化执行否则耗时不可接受。

python · full_mesh.py
#!/usr/bin/env python3
"""全连接矩阵测试调度器"""
import asyncio, asyncssh, json, time
from itertools import combinations

NODES = [f"node-{i:02d}" for i in range(1, 33)]  # 32 节点
DEVICE = "mlx5_0"
GPU_ID = 0
MSG_SIZE = 1048576
ITERATIONS = 5000
THREADS = 8
PARALLEL = 8  # 同时测 8 对

async def test_pair(server: str, client: str) -> dict:
    """测试一对节点"""
    cmd_server = (f"doca_perftest -d {DEVICE} --use_cuda {GPU_ID} "
                  f"-s {MSG_SIZE} -n {ITERATIONS} -t {THREADS} "
                  f"--output json")
    cmd_client = cmd_server + f" {server}"
    try:
        async with asyncssh.connect(server, username='root') as ssh_s, \
                   asyncssh.connect(client, username='root') as ssh_c:
            await ssh_s.run(cmd_server, check=False)
            await asyncio.sleep(2)
            result = await ssh_c.run(cmd_client, check=True, timeout=120)
            data = json.loads(result.stdout)
            return {
                'pair': f"{server}<->{client}",
                'bw_gbps': data['results']['bandwidth_gbps'],
                'util_pct': data['results']['bandwidth_utilization_pct'],
                'status': 'ok'
            }
    except Exception as e:
        return {'pair': f"{server}<->{client}",
                'bw_gbps': 0, 'util_pct': 0,
                'status': f'fail: {e}'}

async def main():
    pairs = list(combinations(NODES, 2))
    print(f"全连接矩阵: {len(NODES)} 节点, {len(pairs)} 对")

    sem = asyncio.Semaphore(PARALLEL)
    async def bounded(pair):
        async with sem:
            return await test_pair(*pair)

    results = await asyncio.gather(*[bounded(p) for p in pairs])

    ok = [r for r in results if r['status'] == 'ok']
    fail = [r for r in results if r['status'] != 'ok']
    avg_bw = sum(r['bw_gbps'] for r in ok) / len(ok) if ok else 0
    min_bw = min(r['bw_gbps'] for r in ok) if ok else 0
    max_bw = max(r['bw_gbps'] for r in ok) if ok else 0

    print(f"\n===== 全连接矩阵汇总 =====")
    print(f"总对数: {len(pairs)}  成功: {len(ok)}  失败: {len(fail)}")
    print(f"平均带宽: {avg_bw:.1f} Gb/s")
    print(f"最小带宽: {min_bw:.1f} Gb/s")
    print(f"最大带宽: {max_bw:.1f} Gb/s")
    std = (sum((r['bw_gbps']-avg_bw)**2 for r in ok)/len(ok))**0.5
    print(f"带宽标准差: {std:.2f}")

    if fail:
        print(f"\n!!! 失败对 !!!")
        for r in fail:
            print(f"  {r['pair']}: {r['status']}")

asyncio.run(main())
32 节点全连接矩阵输出(496 对) 全连接矩阵: 32 节点, 496 对 ===== 全连接矩阵汇总 ===== 总对数: 496 成功: 496 失败: 0 平均带宽: 388.7 Gb/s 最小带宽: 372.3 Gb/s (node-14<->node-23) 最大带宽: 391.6 Gb/s 带宽标准差: 3.21 全部对带宽 > 370 Gb/s (92.5% 利用率),验收通过。

07长稳测试:24 小时与 7 天

单次压测只反映"峰值能力",但训练任务动辄跑数天。网络在长时间高负载下可能出现带宽衰减、延迟抖动增大、甚至静默丢包。长稳测试(Soak Test)是发现这类问题的唯一手段。

7.1 长稳测试指标体系

指标定义合格阈值告警阈值
带宽波动率(max - min) / avg × 100%< 5%> 10%
平均延迟全周期延迟均值< 25 μs> 35 μs
延迟抖动 (P99-P50)P99 延迟 - 中位数延迟< 5 μs> 15 μs
丢包率丢失包数 / 总发送包数0%> 0.001%
错误率RDMA 错误事件数 / 时间0 / 小时> 1 / 小时
带宽衰减末 1 小时均值 / 首 1 小时均值> 98%< 95%

7.2 24 小时长稳测试脚本

bash · soak_test_24h.sh
#!/bin/bash
# 24 小时长稳测试
# 用法: ./soak_test_24h.sh <server_ip> <duration_hours>

SERVER_IP=${1:-"10.0.1.1"}
DURATION_HOURS=${2:-24}
DURATION_SEC=$((DURATION_HOURS * 3600))
SAMPLE_INTERVAL=60
OUTPUT_DIR="/data/soak_test/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTPUT_DIR"

echo "=== 长稳测试启动 ==="
echo "服务端: $SERVER_IP"
echo "持续时间: ${DURATION_HOURS} 小时 ($DURATION_SEC 秒)"
echo "采样间隔: ${SAMPLE_INTERVAL} 秒"
echo "输出目录: $OUTPUT_DIR"

# 启动服务端(后台,持续运行)
ssh root@$SERVER_IP \
  "doca_perftest -d mlx5_0 --use_cuda 0 -s 1048576 \
   --duration $DURATION_SEC -t 8 --output csv \
   --log-file /tmp/soak_server.csv &" &

sleep 5

# 客户端循环采样
START_TIME=$(date +%s)
SAMPLE_NUM=0

while true; do
    CURRENT_TIME=$(date +%s)
    ELAPSED=$((CURRENT_TIME - START_TIME))
    if [ $ELAPSED -ge $DURATION_SEC ]; then
        break
    fi

    SAMPLE_NUM=$((SAMPLE_NUM + 1))
    TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

    # 运行 60 秒采样
    doca_perftest -d mlx5_0 --use_cuda 0 -s 1048576 \
        --duration $SAMPLE_INTERVAL -t 8 --output csv \
        --log-file "$OUTPUT_DIR/sample_${SAMPLE_NUM}.csv" \
        $SERVER_IP 2>&1

    # 计算实时指标
    BW=$(tail -1 "$OUTPUT_DIR/sample_${SAMPLE_NUM}.csv" | cut -d, -f7)
    echo "[$TIMESTAMP] Sample #$SAMPLE_NUM | Elapsed: ${ELAPSED}s | BW: ${BW} Gb/s"

    # 检查告警条件
    AWK_RESULT=$(echo "$BW" | awk '{if ($1 < 350) print "ALERT"; else print "OK"}')
    if [ "$AWK_RESULT" = "ALERT" ]; then
        echo "[$TIMESTAMP] !!! 带宽告警: ${BW} Gb/s < 350 Gb/s !!!"
        echo "$TIMESTAMP,$SAMPLE_NUM,$BW,ALERT_LOW_BW" \
            >> "$OUTPUT_DIR/alerts.log"
    fi
done

echo "=== 长稳测试完成 ==="
echo "总采样数: $SAMPLE_NUM"
echo "结果目录: $OUTPUT_DIR"

7.3 长稳测试结果分析

python · analyze_soak.py
#!/usr/bin/env python3
"""长稳测试结果分析"""
import csv, glob, statistics
from datetime import datetime

def load_samples(result_dir: str) -> list:
    """加载所有采样文件"""
    samples = []
    for f in sorted(glob.glob(f"{result_dir}/sample_*.csv")):
        with open(f) as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                samples.append({
                    'timestamp': row.get('timestamp', ''),
                    'bw_gbps': float(row.get('bandwidth_gbps', 0)),
                    'lat_us': float(row.get('avg_latency_us', 0)),
                    'p99_lat_us': float(row.get('p99_latency_us', 0)),
                    'cpu_pct': float(row.get('cpu_pct', 0)),
                })
    return samples

def analyze(samples: list) -> dict:
    bws = [s['bw_gbps'] for s in samples]
    lats = [s['lat_us'] for s in samples]
    p99s = [s['p99_lat_us'] for s in samples]

    n = len(bws)
    first_hr = statistics.mean(bws[:60]) if n > 60 else statistics.mean(bws)
    last_hr = statistics.mean(bws[-60:]) if n > 60 else statistics.mean(bws)

    return {
        'total_samples': n,
        'avg_bw': statistics.mean(bws),
        'min_bw': min(bws),
        'max_bw': max(bws),
        'bw_std': statistics.stdev(bws) if n > 1 else 0,
        'bw_fluctuation_pct': (max(bws) - min(bws)) / statistics.mean(bws) * 100,
        'avg_latency': statistics.mean(lats),
        'p99_latency': statistics.mean(p99s),
        'jitter': statistics.mean(p99s) - statistics.median(lats),
        'bw_decay_pct': (1 - last_hr / first_hr) * 100,
        'first_hr_bw': first_hr,
        'last_hr_bw': last_hr,
    }

def check_thresholds(metrics: dict) -> list:
    checks = []
    checks.append(("带宽波动率", metrics['bw_fluctuation_pct'], 5, 10))
    checks.append(("平均延迟(us)", metrics['avg_latency'], 25, 35))
    checks.append(("延迟抖动(us)", metrics['jitter'], 5, 15))
    checks.append(("带宽衰减(%)", metrics['bw_decay_pct'], 2, 5))
    return checks

if __name__ == '__main__':
    import sys
    samples = load_samples(sys.argv[1])
    m = analyze(samples)

    print("=" * 55)
    print(f"  长稳测试分析报告 ({m['total_samples']} 采样)")
    print("=" * 55)
    print(f"  平均带宽:     {m['avg_bw']:.1f} Gb/s")
    print(f"  带宽范围:     {m['min_bw']:.1f} ~ {m['max_bw']:.1f} Gb/s")
    print(f"  带宽标准差:   {m['bw_std']:.2f} Gb/s")
    print(f"  带宽波动率:   {m['bw_fluctuation_pct']:.2f}%")
    print(f"  平均延迟:     {m['avg_latency']:.1f} us")
    print(f"  P99 延迟:     {m['p99_latency']:.1f} us")
    print(f"  延迟抖动:     {m['jitter']:.1f} us")
    print(f"  带宽衰减:     {m['bw_decay_pct']:.2f}%")
    print(f"  首小时均值:   {m['first_hr_bw']:.1f} Gb/s")
    print(f"  末小时均值:   {m['last_hr_bw']:.1f} Gb/s")
    print("-" * 55)

    all_pass = True
    for name, val, ok_thresh, alert_thresh in check_thresholds(m):
        if val <= ok_thresh:
            status = "PASS"
        elif val <= alert_thresh:
            status = "WARN"
            all_pass = False
        else:
            status = "ALERT"
            all_pass = False
        print(f"  {name:16s}: {val:8.2f}  {status}")

    print("-" * 55)
    print(f"  总体结论: {'PASS' if all_pass else 'FAIL'}")
    print("=" * 55)
24 小时长稳测试分析报告 ======================================================= 长稳测试分析报告 (1440 采样) ======================================================= 平均带宽: 388.6 Gb/s 带宽范围: 384.1 ~ 391.4 Gb/s 带宽标准差: 1.38 Gb/s 带宽波动率: 1.88% 平均延迟: 21.5 us P99 延迟: 24.3 us 延迟抖动: 2.8 us 带宽衰减: 0.12% 首小时均值: 389.0 Gb/s 末小时均值: 388.5 Gb/s ------------------------------------------------------- 带宽波动率 : 1.88 PASS 平均延迟(us) : 21.50 PASS 延迟抖动(us) : 2.80 PASS 带宽衰减(%) : 0.12 PASS ------------------------------------------------------- 总体结论: PASS =======================================================

08压测结果分析与可视化

压测产生的大量数据(全连接矩阵 496 对 × 多参数组合 = 上万条记录)需要可视化才能快速发现异常。以下用 matplotlib + seaborn 构建标准分析套件。

8.1 数据加载与预处理

python · visualize.py
#!/usr/bin/env python3
"""压测结果可视化套件"""
import sqlite3, pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import seaborn as sns
import numpy as np

sns.set_theme(style="whitegrid", palette="muted")

def load_results(db_path: str) -> pd.DataFrame:
    conn = sqlite3.connect(db_path)
    df = pd.read_sql_query(
        "SELECT * FROM results WHERE bandwidth_gbps > 0", conn)
    conn.close()
    df['pair'] = df['server_node'] + ' -> ' + df['client_node']
    return df

# 1. 全连接矩阵热力图
def plot_heatmap(df, savepath):
    """N*N 带宽热力图,一眼看出哪对节点异常"""
    pivot = df.pivot_table(
        values='bandwidth_gbps',
        index='server_node', columns='client_node',
        aggfunc='mean')
    pivot = pivot.combine_first(pivot.T)

    fig, ax = plt.subplots(figsize=(14, 12))
    sns.heatmap(pivot, annot=True, fmt='.0f',
                cmap='RdYlGn', center=380,
                vmin=350, vmax=395,
                ax=ax, linewidths=0.5)
    ax.set_title('全连接矩阵带宽热力图 (Gb/s)', fontsize=16, pad=20)
    plt.tight_layout()
    plt.savefig(savepath, dpi=150)
    plt.close()

# 2. 带宽分布直方图
def plot_distribution(df, savepath):
    fig, axes = plt.subplots(1, 2, figsize=(16, 6))
    ax = axes[0]
    ax.hist(df['bandwidth_gbps'], bins=50, edgecolor='white',
            color='#06b6d4', alpha=0.8)
    ax.axvline(df['bandwidth_gbps'].mean(), color='#e11d48',
               linestyle='--', linewidth=2,
               label=f"mean {df['bandwidth_gbps'].mean():.1f}")
    ax.axvline(df['bandwidth_gbps'].quantile(0.05), color='#f59e0b',
               linestyle='--', linewidth=2,
               label=f"P5 {df['bandwidth_gbps'].quantile(0.05):.1f}")
    ax.set_xlabel('Bandwidth (Gb/s)')
    ax.set_ylabel('Count')
    ax.set_title('Bandwidth Distribution')
    ax.legend()

    ax = axes[1]
    ax.hist(df['avg_latency_us'], bins=50, edgecolor='white',
            color='#34d399', alpha=0.8)
    ax.set_xlabel('Latency (us)')
    ax.set_ylabel('Count')
    ax.set_title('Latency Distribution')
    plt.tight_layout()
    plt.savefig(savepath, dpi=150)
    plt.close()

# 3. 消息大小 vs 带宽曲线
def plot_size_bw_curve(df, savepath):
    fig, ax = plt.subplots(figsize=(12, 7))
    for threads in sorted(df['threads'].unique()):
        subset = df[df['threads'] == threads]
        grouped = subset.groupby('msg_size')['bandwidth_gbps'].agg(['mean', 'std'])
        ax.errorbar(grouped.index / 1024, grouped['mean'],
                    yerr=grouped['std'], marker='o', capsize=3,
                    label=f'{threads} QP', linewidth=2)
    ax.set_xscale('log', base=2)
    ax.set_xlabel('Message Size (KB)')
    ax.set_ylabel('Bandwidth (Gb/s)')
    ax.set_title('Message Size vs Bandwidth (by QP count)')
    ax.legend(title='Concurrent QP')
    ax.axhline(y=400, color='gray', linestyle=':', alpha=0.5)
    plt.tight_layout()
    plt.savefig(savepath, dpi=150)
    plt.close()

# 4. 异常检测:Z-score
def detect_anomalies(df, threshold=2.5):
    bw_mean = df['bandwidth_gbps'].mean()
    bw_std = df['bandwidth_gbps'].std()
    df['z_score'] = (df['bandwidth_gbps'] - bw_mean) / bw_std
    anomalies = df[df['z_score'].abs() > threshold].sort_values('z_score')
    return anomalies[['pair', 'msg_size', 'threads',
                      'bandwidth_gbps', 'z_score']]

if __name__ == '__main__':
    df = load_results('/data/perftest/results.db')
    print(f"加载 {len(df)} 条记录")
    plot_heatmap(df, '/data/perftest/heatmap.png')
    plot_distribution(df, '/data/perftest/distribution.png')
    plot_size_bw_curve(df, '/data/perftest/size_bw_curve.png')
    anomalies = detect_anomalies(df)
    if len(anomalies) > 0:
        print(f"\n!!! 检测到 {len(anomalies)} 条异常记录 !!!")
        print(anomalies.to_string(index=False))
    else:
        print("\n未检测到异常记录")

8.2 异常检测策略

策略方法适用场景
Z-score(x - μ) / σ,阈值 ±2.5σ正态分布数据,快速筛查
IQR超出 [Q1-1.5×IQR, Q3+1.5×IQR]非正态分布,抗极端值
绝对阈值带宽 < 350 Gb/s 或 > 400 Gb/s有明确 SLA 的场景
同组对比同配置下偏离中位数 > 5%控制变量后的精细对比
时序异常滑动窗口均值偏离 > 3σ长稳测试中的突变检测

8.3 自动报告生成

python · generate_report.py
#!/usr/bin/env python3
"""生成 HTML 压测报告"""
import sqlite3, pandas as pd, json
from datetime import datetime

def generate_report(db_path: str, output_path: str):
    conn = sqlite3.connect(db_path)
    df = pd.read_sql_query(
        "SELECT * FROM results WHERE bandwidth_gbps > 0", conn)
    conn.close()

    total = len(df)
    avg_bw = df['bandwidth_gbps'].mean()
    min_bw = df['bandwidth_gbps'].min()
    max_bw = df['bandwidth_gbps'].max()
    pass_rate = (df['bandwidth_gbps'] > 370).mean() * 100

    worst = df.nsmallest(5, 'bandwidth_gbps')[
        ['server_node', 'client_node', 'msg_size', 'threads',
         'bandwidth_gbps']].to_html(index=False, classes='report-table')

    html = f"""
    <html><head><style>
    body {{ font-family: sans-serif; margin: 40px; }}
    .kpi {{ display: inline-block; margin: 20px; padding: 20px;
           background: #f0fdf6; border-radius: 8px; }}
    .kpi .v {{ font-size: 28px; font-weight: bold; color: #0e7490; }}
    table {{ border-collapse: collapse; width: 100%; }}
    th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
    th {{ background: #0e7490; color: white; }}
    </style></head><body>
    <h1>GPU 网络压测报告</h1>
    <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
    <div>
      <div class="kpi"><div class="v">{total}</div>总测试数</div>
      <div class="kpi"><div class="v">{avg_bw:.1f}</div>平均带宽 (Gb/s)</div>
      <div class="kpi"><div class="v">{min_bw:.1f}</div>最低带宽 (Gb/s)</div>
      <div class="kpi"><div class="v">{pass_rate:.1f}%</div>达标率 (>370 Gb/s)</div>
    </div>
    <h2>带宽最低的 5 组测试</h2>
    {worst}
    </body></html>
    """
    with open(output_path, 'w') as f:
        f.write(html)
    print(f"报告已生成: {output_path}")

generate_report('/data/perftest/results.db',
                '/data/perftest/report.html')

09与 NCCL 的端到端验证

perftest 测的是"网络管道"的极限能力,但训练任务通过 NCCL 使用网络。perftest 基线好不代表 NCCL 性能好——中间还有 NCCL 的 transport 选择、ring/tree 拓扑、GPU 同步等环节。完整的验证链路是:perftest 基线 → nccl-tests 验证 → 训练性能确认。

9.1 验证流程

Step 1:perftest 基线确认

用 doca_perftest 确认每对节点 GPUDirect RDMA 带宽 > 370 Gb/s(NDR 400G 的 92.5%)。这是网络管道的基础保证。如果 perftest 就不达标,后续 NCCL 测试没有意义。

Step 2:nccl-tests all_reduce_perf

用 NCCL 官方测试工具验证集合通信性能。all_reduce 是训练中最频繁的集合操作,其性能直接反映网络在多 GPU 协同下的表现。

Step 3:nccl-tests all_gather_perf

all_gather 是第二频繁的操作(TP/PP 通信),验证其带宽是否接近 all_reduce。

Step 4:真实训练 benchmark

用标准训练 benchmark(如 GPT-3 175B 的前向+反向一步)确认端到端训练吞吐。这是最终验收标准。

9.2 nccl-tests 执行

bash
# 编译 nccl-tests
git clone https://github.com/NVIDIA/nccl-tests.git
cd nccl-tests
make CUDA_HOME=/usr/local/cuda NCCL_HOME=/usr/local/nccl \
     MPI=1 MPI_HOME=/usr/local/openmpi

# all_reduce 性能测试(8 节点 × 8 GPU = 64 GPU)
mpirun -np 8 \
  -host node-01,node-02,node-03,node-04,node-05,node-06,node-07,node-08 \
  -x NCCL_DEBUG=INFO \
  -x NCCL_IB_HCA=mlx5_0 \
  -x NCCL_NET_GDR_LEVEL=PHB \
  -x NCCL_IB_DISABLE=0 \
  ./build/all_reduce_perf -b 8 -e 1G -f 2 -g 8

# all_gather 性能测试
mpirun -np 8 \
  -host node-01,node-02,node-03,node-04,node-05,node-06,node-07,node-08 \
  -x NCCL_IB_HCA=mlx5_0 \
  -x NCCL_NET_GDR_LEVEL=PHB \
  ./build/all_gather_perf -b 8 -e 1G -f 2 -g 8

9.3 三层验证结果对比

验证层工具指标实测值基线/预期结论
网络管道doca_perftest点对点带宽389 Gb/s> 370 Gb/s通过
集合通信nccl all_reduce1MB algbw46.2 GB/s> 40 GB/s通过
集合通信nccl all_gather1MB algbw48.1 GB/s> 42 GB/s通过
训练性能GPT-3 175BTFLOPS312> 290通过
训练性能GPT-3 175Bstep time1.82s< 2.0s通过
验证逻辑

perftest 是"管道容量"测试,nccl-tests 是"管道利用率"测试,训练 benchmark 是"业务效果"测试。三层从底到顶,每一层的问题都会向上传导。排查顺序必须从底到顶:先确认 perftest 基线,再查 NCCL,最后看训练。跳过底层直接看训练性能,往往无从下手。

10实战案例:256 卡集群网络验收

以下是一个真实的 256 卡(32 节点 × 8 × H100)集群网络验收案例,展示从全连接矩阵测试到问题定位的完整过程。

10.1 集群概况

32
节点数
256
GPU 总数
496
全连接对数
400G
NDR 链路
3
交换机层
2h
验收耗时

10.2 全连接矩阵测试

bash · 验收执行
# 1. 全连接矩阵 GPUDirect RDMA 带宽测试
python3 full_mesh.py --nodes 32 \
  --test gpu_rdma_write_bw \
  --msg-size 1048576 --threads 8 --parallel 8 \
  --output /data/acceptance/full_mesh_256.json

# 2. 全连接矩阵延迟测试(小消息)
python3 full_mesh.py --nodes 32 \
  --test gpu_rdma_write_lat \
  --msg-size 1024 --threads 1 --parallel 8 \
  --output /data/acceptance/full_mesh_lat_256.json

# 3. 生成热力图
python3 visualize.py \
  --input /data/acceptance/full_mesh_256.json \
  --plot heatmap \
  --output /data/acceptance/heatmap_256.png

10.3 发现异常

全连接矩阵汇总 — 发现异常 全连接矩阵: 32 节点, 496 对 ===== 全连接矩阵汇总 ===== 总对数: 496 成功: 496 失败: 0 平均带宽: 387.9 Gb/s 最小带宽: 312.4 Gb/s (node-14<->node-23) 最大带宽: 391.6 Gb/s 带宽标准差: 8.74 !!! 带宽异常对(< 370 Gb/s)!!! node-14 <-> node-23 : 312.4 Gb/s (78.1%) node-14 <-> node-24 : 318.7 Gb/s (79.7%) node-15 <-> node-23 : 315.2 Gb/s (78.8%) node-15 <-> node-24 : 320.1 Gb/s (80.0%) 共 4 对异常,全部涉及 node-14/15 与 node-23/24 之间的连接

10.4 问题定位

4 对异常节点有一个明显规律:全部是 node-14/15 与 node-23/24 之间的连接。这 4 个节点分属不同交换机,问题大概率在交换机间链路或线缆上。

Step 1:确认节点拓扑位置

查交换机端口映射表,发现 node-14/15 接 Leaf-3 交换机,node-23/24 接 Leaf-5 交换机。Leaf-3 和 Leaf-5 之间通过 Spine-2 连接。

Step 2:检查交换机端口误码

登录 Spine-2,检查 Leaf-3 和 Leaf-5 对应端口的物理层统计。

bash · 交换机端口检查
# 在 Spine-2 交换机上
# 检查连接 Leaf-3 的端口
show interface port-channel 1/3 counters detail

# 检查连接 Leaf-5 的端口
show interface port-channel 1/5 counters detail

# 关键输出:查看物理误码
show interface ethernet 1/31 physical-counters
Spine-2 端口 1/31 物理计数器 Port 1/31 (连接 Leaf-5): Rx_bytes: 1.2 TB Tx_bytes: 1.1 TB Rx_errors: 0 Tx_errors: 0 Rx_discards: 0 Link_recovery: 47 ← !!! 异常 !!! Symbol_errors: 23 ← !!! 异常 !!! Correctable_ECC: 156 Uncorrectable_ECC: 2 ← !!! 严重 !!!

Spine-2 连接 Leaf-5 的端口有 47 次链路恢复、23 个符号错误、2 个不可纠正 ECC 错误。这是典型的物理层故障特征——线缆质量问题或光模块故障。

Step 3:线缆/光模块排查

检查该链路使用的线缆类型和光模块型号,发现使用的是第三方兼容光模块而非 NVIDIA 原厂模块。在 400G NDR 速率下,第三方模块的信号完整性不达标,高负载下出现误码。

Step 4:更换并复测

将 Spine-2 到 Leaf-5 的光模块更换为 NVIDIA 原厂 400G OSFP 模块,重新执行全连接矩阵测试。

更换光模块后复测结果 全连接矩阵: 32 节点, 496 对 平均带宽: 388.8 Gb/s 最小带宽: 385.2 Gb/s (node-14<->node-23) ← 恢复正常 最大带宽: 391.6 Gb/s 带宽标准差: 1.42 ← 从 8.74 降到 1.42 全部 496 对带宽 > 385 Gb/s (96.3% 利用率) 验收通过
案例教训

第三方光模块在 400G NDR 速率下风险极高。200G SR4 时代第三方模块还能勉强用,到了 400G NDR,信号完整性余量极小,非原厂模块在高负载下误码率显著上升。集群验收时必须将光模块型号检查纳入上线 checklist,不要等到压测才发现。

11压测自动化框架与 CI 集成

网络验收不是一次性工作。集群固件升级、拓扑变更、新节点加入后都需要回归测试。将压测纳入自动化框架和 CI 流水线,才能保证网络质量持续可控。

11.1 自动化框架架构

调度层

cron / Airflow / GitLab CI

定时触发(每日/每周)或事件触发(固件升级后)。调度器只负责"什么时候跑",不关心"怎么跑"。

执行层

perftest_runner.py

第 5 节的压测引擎,接收配置文件,执行测试,输出结果到 SQLite。

分析层

analyze + visualize

第 8 节的分析套件,生成热力图、分布图、异常检测报告。

告警层

阈值检查 → 通知

检查结果是否达标,不达标则通过飞书/Slack/邮件告警,附带异常热力图。

存储层

SQLite + 对象存储

结构化数据存 SQLite,图片报告存对象存储(S3/MinIO),保留 90 天。

展示层

Grafana Dashboard

将 SQLite 数据接入 Grafana,实时查看历史趋势、当前状态、异常记录。

11.2 CI 集成配置

yaml · .gitlab-ci.yml
# 网络压测 CI Job
network_perftest:
  stage: validation
  image: registry.internal/gpu-ops/perftest:2.7
  variables:
    PERFTEST_CONFIG: "configs/perftest_full.yaml"
    RESULT_DB: "/data/perftest/ci_${CI_PIPELINE_ID}.db"
  rules:
    # 固件升级后自动触发
    - if: '$CI_COMMIT_BRANCH == "main" && $FIRMWARE_UPGRADE == "true"'
    # 每周日凌晨 2 点定时触发
    - if: '$CI_PIPELINE_SOURCE == "schedule"'
    # 手动触发
    - if: '$CI_PIPELINE_SOURCE == "web"'
  script:
    # 1. 执行压测
    - python3 perftest_runner.py --config $PERFTEST_CONFIG --output $RESULT_DB

    # 2. 分析结果
    - python3 analyze_soak.py $RESULT_DB > analysis_report.txt

    # 3. 生成可视化
    - python3 visualize.py --input $RESULT_DB --output /data/perftest/plots/

    # 4. 检查阈值
    - |
      PASS_RATE=$(sqlite3 $RESULT_DB \
        "SELECT ROUND(AVG(bandwidth_gbps > 370)*100, 1) FROM results")
      echo "达标率: ${PASS_RATE}%"
      if [ $(echo "$PASS_RATE < 95" | bc -l) -eq 1 ]; then
        echo "!!! 达标率低于 95%,CI 失败 !!!"
        python3 alert.py --channel feishu \
          --message "网络压测达标率 ${PASS_RATE}% < 95%" \
          --attachment /data/perftest/plots/heatmap.png
        exit 1
      fi

    # 5. 归档结果
    - python3 archive.py --db $RESULT_DB --retention 90d

  artifacts:
    reports:
      junit: analysis_report.xml
    paths:
      - /data/perftest/plots/
    expire_in: 90 days

11.3 告警脚本

python · alert.py
#!/usr/bin/env python3
"""压测告警通知"""
import requests, sys, json
from pathlib import Path

FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/xxx"

def send_feishu(message: str, attachment: str = None):
    """发送飞书告警"""
    payload = {
        "msg_type": "interactive",
        "card": {
            "header": {
                "title": {"tag": "plain_text",
                          "content": "网络压测告警"},
                "template": "red"
            },
            "elements": [
                {"tag": "div",
                 "text": {"tag": "lark_md",
                          "content": message}},
            ]
        }
    }

    if attachment and Path(attachment).exists():
        with open(attachment, 'rb') as f:
            upload = requests.post(
                "https://open.feishu.cn/open-apis/im/v1/images",
                headers={"Authorization": "Bearer xxx"},
                files={'image': f},
                params={'image_type': 'message'})
        image_key = upload.json().get('data', {}).get('image_key')
        if image_key:
            payload['card']['elements'].append(
                {"tag": "img", "img_key": image_key})

    resp = requests.post(FEISHU_WEBHOOK, json=payload)
    print(f"告警发送: {resp.status_code}")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--channel', default='feishu')
    parser.add_argument('--message', required=True)
    parser.add_argument('--attachment', default=None)
    args = parser.parse_args()

    if args.channel == 'feishu':
        send_feishu(args.message, args.attachment)

11.4 Grafana Dashboard 配置

将 SQLite 数据源接入 Grafana,创建以下 Panel:

Panel类型查询维度用途
达标率趋势Time series按天聚合达标率监控网络质量长期趋势
带宽分布Boxplot按节点对分组发现离群节点对
异常热力图Heatmap节点 × 节点快速定位问题链路
延迟 P99Stat + Gauge最新值 + 阈值实时延迟监控
告警计数Bar chart按天统计告警次数评估网络稳定性

12速查表

DOCA perftest 命令速查
场景命令说明
基础带宽doca_perftest -d mlx5_0 -s 1M -n 5000 --test-type write_bw server等价 ib_write_bw
GPUDirect 带宽doca_perftest -d mlx5_0 --use_cuda 0 -s 1M -n 5000 serverGPU 显存直连
多 QP 并发doca_perftest -d mlx5_0 --use_cuda 0 -s 1M -t 16 server16 QP 并发
延迟测试doca_perftest -d mlx5_0 --use_cuda 0 -s 1024 --test-type write_lat server小消息延迟
定时测试doca_perftest -d mlx5_0 --use_cuda 0 --duration 3600 server运行 1 小时
JSON 输出doca_perftest ... --output json脚本解析
CSV 输出doca_perftest ... --output csv批量收集
DPDK 后端doca_perftest ... --doca-backend dpdkDPDK 加速
查看后端信息doca_perftest -d mlx5_0 --report-doca-info诊断用
关键参数速查
参数含义推荐值
-dRDMA 设备名mlx5_0 / mlx5_1
-s消息大小(字节)带宽: 1M~4M,延迟: 64~4K
-n迭代次数5000~10000
-t并发线程/QP 数8(NCCL 默认)
--use_cudaGPU 显存缓冲0(第一块 GPU)
--duration按时间运行(秒)长稳: 86400(24h)
--test-type测试类型write_bw / write_lat
--output输出格式json(脚本)/ csv(批量)
验收阈值速查(400G NDR)
指标合格告警计算方式
GPUDirect 带宽> 370 Gb/s< 350 Gb/s1MB 消息, 8 QP
带宽利用率> 92.5%< 87.5%实测 / 400
写延迟 (1KB)< 3 μs> 5 μsP50 中位数
延迟抖动< 5 μs> 15 μsP99 - P50
带宽波动率< 5%> 10%(max-min)/avg
带宽衰减< 2%> 5%1 - 末时/首时
丢包率0%> 0.001%丢包/发包
全矩阵达标率> 98%< 95%达标对数/总对数
排查命令速查
问题排查命令
GPU-NIC PCIe 拓扑nvidia-smi topo -m
peermem 模块lsmod | grep nvidia_peermem
网卡固件版本mlxconfig -d /dev/mst/xxx q
OFED 版本ofed_info -s
端口物理状态ethtool -m mlx5_0 / 交换机 show interface
RDMA 设备列表ibv_devinfo -v
NCCL 调试日志NCCL_DEBUG=INFO 环境变量
交换机误码show interface ethernet 1/X physical-counters