关于torch.nn.DataParallel的问题

Jia*_*ang 3 python pytorch

我是深度学习领域的新手。现在我正在复制论文的代码。由于他们使用多个 GPU,因此torch.nn.DataParallel(model, device_ids= args.gpus).cuda()代码中有一个命令。但是我只有一个 GPU,我应该如何更改此代码以匹配我的 GPU?

谢谢!

M. *_*ers 5

DataParallel也应该在单个 GPU 上工作,但您应该检查是否args.gpus只包含要使用的设备的 id(应该是 0)或None. 选择None将使模块使用所有可用设备。

您也可以删除,DataParallel因为您不需要它并仅通过调用model.cuda()或,如我所愿,设备名称model.to(device)在哪里将模型移动到 GPU device

例子:

此示例展示了如何在单个 GPU 上使用模型,设置设备使用.to()而不是.cuda().

from torch import nn
import torch

# Set device to cuda if cuda is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Create model
model = nn.Sequential(
  nn.Conv2d(1,20,5),
  nn.ReLU(),
  nn.Conv2d(20,64,5),
  nn.ReLU()
)

# moving model to GPU
model.to(device)
Run Code Online (Sandbox Code Playgroud)

如果你想使用DataParallel你可以这样做

# Optional DataParallel, not needed for single GPU usage
model1 = torch.nn.DataParallel(model, device_ids=[0]).to(device)
# Or, using default 'device_ids=None'
model1 = torch.nn.DataParallel(model).to(device)
Run Code Online (Sandbox Code Playgroud)