Dan*_*ris 5 python cpu gpu pytorch
迁移指南建议采取以下措施,使代码与CPU / GPU无关:
> # at beginning of the script
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
...
# then whenever you get a new Tensor or Module
# this won't copy if they are already on the desired device
input = data.to(device)
model = MyModule(...).to(device)
Run Code Online (Sandbox Code Playgroud)
我这样做并在仅CPU的设备上运行了代码,但是当输入一个输入数组时,我的模型崩溃了,因为它说期望的是CPU张量而不是GPU张量。我的模型以某种方式自动将CPU输入阵列转换为GPU阵列。最后,我在代码中将其追溯到此命令:
model = torch.nn.DataParallel(model).to(device)
Run Code Online (Sandbox Code Playgroud)
即使我将模型转换为“ cpu”,但nn.DataParallel仍将其覆盖。我想出的最好的解决方案是有条件的:
if device.type=='cpu':
model = model.to(device)
else:
model = torch.nn.DataParallel(model).to(device)
Run Code Online (Sandbox Code Playgroud)
这看起来并不优雅。有没有更好的办法?
怎么样
if torch.cuda.device_count() > 1:
model = torch.nn.DataParallel(model)
model = model.to(device)
Run Code Online (Sandbox Code Playgroud)
?
DataParallel如果您只有一个 GPU,则不需要。
| 归档时间: |
|
| 查看次数: |
455 次 |
| 最近记录: |