linux

Linux版PyTorch的性能测试方法是什么

小樊
41
2025-12-04 17:05:50
栏目: 智能运维

Linux版 PyTorch 性能测试方法

一 环境与基线检查

示例基线脚本

import torch, time

print("PyTorch:", torch.__version__, "CUDA available:", torch.cuda.is_available())
if torch.cuda.is_available():
    print("Device:", torch.cuda.get_device_name(0))

# 最小化 GPU 基准
N, iters = 10_000_000, 100
x = torch.ones(N, device="cuda")
torch.cuda.synchronize()
t0 = time.time()
for _ in range(iters):
    x += 1
torch.cuda.synchronize()
print(f"GPU add {iters} iters: {time.time()-t0:.3f} s")

上述步骤中的环境检查与线程设置、最小化 GPU 样例可直接用于验证安装与设备可用性,并作为后续测试的基线参考。

二 微基准测试 GPU 与 CPU 算子

示例 GPU 微基准

def gpu_bench(N=10_000_000, iters=100, device="cuda"):
    x = torch.ones(N, device=device)
    torch.cuda.synchronize()
    t0 = time.time()
    for _ in range(iters):
        x = x + 1
    torch.cuda.synchronize()
    return (time.time() - t0) / iters  # s/iter

print("GPU add:", gpu_bench(), "s/iter")

该模式适合定位算子/内核级别的性能瓶颈,并为模型层或自定义内核提供对照数据。

三 模型级基准测试与 Profiling

示例 Profiling 训练循环

import torch, torch.nn as nn
from torch.profiler import profile, record_function, ProfilerActivity

model = nn.Linear(1024, 1024).cuda()
x = torch.randn(256, 1024, device="cuda")
opt = torch.optim.SGD(model.parameters(), lr=1e-3)

with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1),
    on_trace_ready=lambda prof: prof.export_chrome_trace("trace.json"),
    record_shapes=True, profile_memory=True
) as prof:
    for _ in range(5):
        with record_function("forward"):
            y = model(x)
        with record_function("backward"):
            y.sum().backward()
        with record_function("optim"):
            opt.step(); opt.zero_grad()
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))

示例运行 PyTorch Benchmark(需先安装并进入项目目录)

# pip install -e .
python run.py -d cuda -t train --model resnet50
tensorboard --logdir=./logs

上述方法覆盖模型级吞吐与瓶颈定位,适合做版本升级、参数变化与硬件迁移的对比实验。

四 系统与多卡分布式测试

示例 DDP 启动

# 方式一:旧接口
python -m torch.distributed.launch --nproc_per_node=2 train_ddp.py

# 方式二:新接口
torchrun --nproc_per_node=2 train_ddp.py

系统监控与 DDP 测试可帮助识别通信瓶颈、负载不均与数据管道问题,是规模化训练前的必要验证。

五 结果记录与对比建议

0
看了该问题的人还看了