我是深度学习领域的新手。现在我正在复制一篇论文的代码。由于它们使用多个GPU,因此代码中有一个命令torch.nn.DataParallel(model, device_ids= args.gpus).cuda()
。但是我只有一个GPU,什么 我应该更改此代码以匹配我的 GPU 吗?
谢谢!
>DataParallel
也应该在单个GPU上运行,但您应该检查args.gpus
是否仅包含要使用的设备的id(应为0(或None
。 选择None
将使模块使用所有可用设备。
您也可以删除DataParallel
,因为您不需要它,并且仅通过调用model.cuda()
或我更喜欢model.to(device)
device
是设备名称来将模型移动到 GPU。
例:
此示例说明如何在单个 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)
如果你想使用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)