简体   繁体   English

使pytorch代码与CPU或GPU上运行无关的更好方法是什么?

[英]A better way to make pytorch code agnostic to running on a CPU or GPU?

The Migration guide recommends the following to make code CPU/GPU agnostic: 迁移指南建议以下内容使代码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)

I did this and ran my code on a CPU-only device, but my model crashed when fed an input array, as saying it was expecting a CPU tensor not a GPU one. 我做了这个并在仅CPU设备上运行我的代码,但我的模型在输入一个输入数组时崩溃了,因为它说它期望CPU张量不是GPU。 Somehow my model was automatically converting the a CPU-input array to a GPU array. 不知何故,我的模型自动将CPU输入数组转换为GPU数组。 Finally I traced it down to this command in my code: 最后,我在我的代码中追溯到这个命令:

model = torch.nn.DataParallel(model).to(device)

Even though I convert the model to 'cpu', the nn.DataParallel overrides this. 即使我将模型转换为'cpu',nn.DataParallel也会覆盖它。 The best solution I came up with was a conditional: 我想出的最佳解决方案是有条件的:

if device.type=='cpu':
    model = model.to(device)
else:
    model = torch.nn.DataParallel(model).to(device)

This does not seem elegant. 这似乎并不优雅。 Is there a better way? 有没有更好的办法?

How about 怎么样

if torch.cuda.device_count() > 1:
    model = torch.nn.DataParallel(model)
model = model.to(device)

?

You don't need DataParallel if you have only one GPU. 如果只有一个GPU,则不需要DataParallel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM