Pytorch:未使用 to() 函数在 GPU 上传输层

乘风 pytorch 203

原文标题Pytorch: layer not transferred on GPU with to() function

在下面的代码中,我期望张量 x 和层 l 都在 GPU 上,而不是只有张量 x 结果在 GPU 上,而不是层 l 。实际上,使用这种方法会导致 RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu 和 cuda:0!在学习阶段。

import torch
x = torch.zeros(1)
x = x.to('cuda')
try:
    x.get_device()
    print('x: gpu')
except:
    print('x:','cpu')

l = torch.nn.Linear(1,1)
l = l.to('cuda')
try:
    l.get_device()
    print('l: gpu')
except:
    print('l:','cpu')

输出是:

x: gpu
l: cpu

而不是两个gpu。为什么会这样?

火炬版本:1.10.2+cu113

原文链接:https://stackoverflow.com//questions/71426005/pytorch-layer-not-transferred-on-gpu-with-to-function

回复

我来回复
  • Theodor Peifer的头像
    Theodor Peifer 评论

    您不能在nn.Linear对象上调用.get_device(),因此您的第二个尝试块失败,它会在异常部分打印代码。为了检查您的模块所在的设备,您可以执行以下操作:

    print(next(l.parameters()).device)
    

    输出:

    >> device(type='cuda', index=0)
    
    2年前 0条评论