Ubuntu下PyTorch性能测试的综合方法
在Ubuntu系统中,对PyTorch模型进行全面性能测试需覆盖硬件资源监控、工具链使用、指标量化及优化验证等多个环节。以下是具体的测试流程与关键方法:
环境验证:确保CUDA Toolkit、cuDNN、PyTorch版本兼容(如PyTorch 2.3.0+cu122对应CUDA 12.2),通过以下命令检查GPU可用性:
import torch
print(f"CUDA available: {torch.cuda.is_available()}")
print(f"GPU count: {torch.cuda.device_count()}")
print(f"Current device: {torch.cuda.get_device_name(0)}")
预期输出应显示CUDA可用、GPU数量及型号(如"NVIDIA GeForce RTX 4090")。
数据准备:使用与训练集格式一致的测试集(如ImageFolder、GLUE数据集),并通过torch.utils.data.DataLoader加载(设置shuffle=False、batch_size适配GPU显存)。
性能测试需围绕效率与效果两大核心,重点关注以下指标:
nvidia-smi监控),高利用率表示计算资源充分利用。torch.cuda.max_memory_allocated())及CPU内存(free -h)的使用量,避免内存瓶颈。PyTorch内置的性能分析工具,可记录CPU/GPU操作时间、内存分配、计算图执行流程。使用步骤:
torch.autograd.profiler.profile:with torch.autograd.profiler.profile(use_cuda=True, schedule=torch.profiler.schedule(wait=1, warmup=1, active=3)) as prof:
for i, (inputs, labels) in enumerate(test_loader):
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
# ...(后续推理/训练步骤)
torch-tb-profiler将结果导出至TensorBoard,查看各阶段的耗时占比(如数据加载、前向传播、反向传播)。watch -n 1 nvidia-smi
perf record -g python train.py
perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > flamegraph.svg
transformers.pipeline加载模型,通过benchmark函数计算延迟与吞吐量:from transformers import pipeline
import time
import numpy as np
def benchmark(pipeline, data, iterations=1000):
# 预热
for _ in range(100):
_ = pipeline(data)
times = []
for _ in range(iterations):
tick = time.time()
_ = pipeline(data)
tock = time.time()
times.append(tock - tick)
return f"{np.mean(times)*1000:.2f}ms", f"{np.percentile(times, 99)*1000:.2f}ms"
pipe = pipeline("text-generation", model="deepseek-ai/DeepSeek-R1-0528", device="cuda:0")
short_sentence = "DeepSeek-R1-0528 performance"
mean_latency, p99_latency = benchmark(pipe, short_sentence)
print(f"Mean Latency: {mean_latency}, P99 Latency: {p99_latency}")
torch.nn.DataParallel或DeepSpeed库,将模型分布到多块GPU上,测试批量推理的吞吐量提升。DataLoader的num_workers参数(设置为CPU核心数的2-4倍)启用多线程数据加载,减少数据加载时间。torch.cuda.amp自动混合精度(AMP),在保持模型精度的前提下,减少显存占用并加速训练:from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
with autocast():
outputs = model(inputs)
loss = criterion(outputs, labels)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
torch.cuda.reset_peak_memory_stats()
# 运行模型推理
peak_memory = torch.cuda.max_memory_allocated() / 1024**3 # 转换为GB
print(f"Peak GPU Memory Usage: {peak_memory:.2f}GB")
torch.cuda.memory_summary()定期打印显存分配情况,观察是否有持续增长的内存占用。num_workers、使用更高效的模型架构)。通过上述方法,可全面评估PyTorch在Ubuntu系统上的性能表现,并快速定位与解决性能瓶颈。