多卡测试pytorch
时间: 2025-05-05 09:45:33 浏览: 20
### PyTorch多GPU测试的方法
在PyTorch中,进行多GPU测试可以通过多种方式实现。最常见的方式是利用`torch.nn.DataParallel`或更高级别的分布式训练工具如`torch.nn.parallel.DistributedDataParallel`。下面详细介绍这两种方法及其代码示例。
#### 使用 `DataParallel` 进行多GPU测试
`DataParallel` 是一种简单的并行化机制,它会自动将输入数据分发到多个GPU上,并收集各个GPU上的输出结果。需要注意的是,在测试阶段通常不需要梯度计算,因此可以关闭梯度跟踪以节省内存。
```python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
# 定义一个简单的模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)
model = SimpleModel()
# 将模型移动到GPU并启用 DataParallel
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model) # 启用多GPU支持
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# 创建一些虚拟数据用于测试
inputs = torch.randn(32, 10).to(device) # 假设有32个样本,每个样本有10个特征
labels = torch.randn(32, 1).to(device)
# 关闭梯度计算以减少内存消耗
with torch.no_grad():
outputs = model(inputs)
print(outputs[:5]) # 打印前5个预测值
```
上述代码展示了如何通过`nn.DataParallel`在多GPU环境下执行推理操作[^1]。
---
#### 使用 `DistributedDataParallel` (DDP) 进行多GPU测试
对于更大规模的应用场景,推荐使用`DistributedDataParallel`(简称DDP),因为它提供了更好的性能优化和支持更多的功能(例如同步批量归一化)。下面是基于DDP的一个简单测试流程:
```python
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '12355'
# 初始化进程组
dist.init_process_group("nccl", rank=rank, world_size=world_size)
def cleanup():
dist.destroy_process_group()
def test_model(rank, world_size):
setup(rank, world_size)
# 加载模型并分配给特定的GPU
device_id = rank % torch.cuda.device_count()
model = SimpleModel().to(device_id)
ddp_model = DDP(model, device_ids=[device_id])
# 准备测试数据集
inputs = torch.randn(32, 10).to(device_id)
with torch.no_grad(): # 禁用梯度计算
output = ddp_model(inputs)
print(f"Rank {rank}: Output shape={output.shape}")
cleanup()
def main(world_size):
mp.spawn(test_model, args=(world_size,), nprocs=world_size, join=True)
if __name__ == "__main__":
num_gpus = torch.cuda.device_count()
if num_gpus > 1:
main(num_gpus)
```
此代码片段演示了如何初始化分布式环境以及如何在不同进程中加载相同的模型实例[^4]。
---
#### 验证 GPU 支持状态
为了确保当前环境中已经正确配置好GPU支持,可以在脚本开头加入如下验证逻辑:
```python
assert torch.cuda.is_available(), "CUDA is not available on this machine."
print(f"CUDA version: {torch.version.cuda}")
print(f"Number of GPUs detected: {torch.cuda.device_count()}")
for i in range(torch.cuda.device_count()):
print(f"Device {i}: {torch.cuda.get_device_name(i)}")
```
这段代码可以帮助确认是否有可用的GPU设备以及它们的具体名称和数量[^3]。
---
#### 注意事项
- 如果模型中有`BatchNorm`层,则建议将其替换为`SyncBatchNorm`以便更好地处理跨GPU的数据分布情况。
- 对于大规模部署或者集群环境下的应用,请务必仔细阅读官方文档关于环境变量设置的部分。
---
阅读全文
相关推荐

















