python - 使 pytorch 代码与在 CPU 或 GPU 上运行无关的更好方法?

标签 python gpu cpu pytorch

迁移 guide推荐以下内容以使代码与 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)

我这样做并在纯 CPU 设备上运行了我的代码,但是当输入数组时我的模型崩溃了,因为它说它期待的是 CPU 张量而不是 GPU 张量。我的模型以某种方式自动将 CPU 输入数组转换为 GPU 数组。最后我在我的代码中找到了这个命令:

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

即使我将模型转换为“cpu”,nn.DataParallel 也会覆盖它。我想到的最佳解决方案是有条件的:

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

这看起来并不优雅。有没有更好的办法?

最佳答案

怎么样

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

?

如果您只有一个 GPU,则不需要 DataParallel

关于python - 使 pytorch 代码与在 CPU 或 GPU 上运行无关的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613383/

相关文章:

memory-management - 独立内存 channel : What does it mean for a programmer

带有 sys.stdin 的 Python 程序出错 - Hadoop Streaming

google-chrome - 强制 headless (headless) Chrome / Chrome 使用实际的GPU,而不是Google SwiftShader

opencl - 同时在 ATI 和 Nvidia 上使用 OpenCl 进行开发

cuda - 在 "cheap"GPU 上为 CUDA 开发

c - 我是否使用位移正确地提取了这些字段? (标签、索引、偏移量)

python - 为 Pandas 设置差异

python - 内省(introspection)有什么用?

python - Sqlite 语法错误,即使没有语法错误。帮助?

java - Linux下使用 'ps'命令,如何查看实时数据?