【Pytorch】pytorch使用多张GPU进行训练以及测试调用模型

本文介绍了如何在PyTorch中利用多个GPU进行模型训练的代码实现,包括设置CUDA环境变量、创建DataParallel模型以及调整设备。同时,强调了在使用多GPU时batch_size的重要性。在模型测试阶段,展示了加载预训练模型到GPU上的步骤,确保模型能够在多GPU环境中正确运行。
摘要由CSDN通过智能技术生成

使用多张GPU进行训练的代码

os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

model = getModel(args)

if torch.cuda.device_count() > 1:
	print("Let's use", torch.cuda.device_count(), "GPUs!")
	model = nn.DataParallel(model, device_ids=[0, 1, 2, 3])   # device_ids=[0, 1, 2, 3]      
model.to(device)

注意事项

1.当需要改变主GPU时,只需要修改如下:
os.environ["CUDA_VISIBLE_DEVICES"] = "1,2,3"
device_ids=[0, 1, 2]  # 此时的GPU从GPU1开始,使用三张GPU
2.使用多张GPU时,batch_size大于1才能使得多张GPU都工作。

测试调用模型

    G_model, _ = getModel(args)
    if torch.cuda.device_count() > 1:
        G_model = nn.DataParallel(G_model)
        checkpoint = torch.load(r'./Gmodel.pth', map_location='cuda')
        G_model.load_state_dict(checkpoint)
        if isinstance(G_model, torch.nn.DataParallel):
            G_model = G_model.module
    else:
        checkpoint = torch.load(r'./Gmodel.pth', map_location='cuda')
        G_model.load_state_dict(checkpoint)
    G_model = G_model.to(device)
PyTorch支持使用多张显卡进行并行训练,可以使用`torch.nn.DataParallel`或`torch.nn.parallel.DistributedDataParallel`来实现。以下是使用`torch.nn.DataParallel`的示例代码: ```python import torch import torch.nn as nn from torch.utils.data import DataLoader # 定义模型 class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 1) def forward(self, x): x = self.fc1(x) x = torch.relu(x) x = self.fc2(x) return x # 定义数据集 class MyDataset(torch.utils.data.Dataset): def __init__(self): self.data = torch.randn(100, 10) self.targets = torch.randn(100, 1) def __getitem__(self, index): return self.data[index], self.targets[index] def __len__(self): return len(self.data) # 定义训练函数 def train(model, dataloader, optimizer, criterion): model.train() for i, (inputs, targets) in enumerate(dataloader): optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() # 创建模型、数据集、数据加载器、优化器、损失函数 model = MyModel() dataset = MyDataset() dataloader = DataLoader(dataset, batch_size=8, shuffle=True) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) criterion = nn.MSELoss() # 使用DataParallel进行GPU并行训练 model = nn.DataParallel(model) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) for epoch in range(10): train(model, dataloader, optimizer, criterion) ``` 在上面的代码中,我们首先定义了一个模型`MyModel`和一个数据集`MyDataset`。然后,我们使用`DataLoader`将数据集加载到内存中。接下来,我们创建了一个优化器和一个损失函数。最后,我们将模型移到GPU上,并使用`DataParallel`对其进行并行处理。在训练循环中,我们调用`train`函数来训练模型。`train`函数的参数分别是模型、数据加载器、优化器和损失函数。由于我们在模型调用了`DataParallel`,因此在训练循环中,我们不需要手动处理多个GPU的并行计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只搬烫手的砖

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值