无法更改pytorch模型的设备

Cannot change device of pytorch model

我正在尝试将我的设备转移到 GPU 上。 运行函数后判断是否有可用的GPU,并判断有(见下文)

> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
> device
device(type='cuda', index=0)

当我调用 model.to(device) 时,模型属性没有变化?

> model.to(device)
S2SModel(
  (encoder): Encoder(
    (lstm): LSTM(5, 32, batch_first=True)
  )
  (decoder): Decoder(
    (lstm): LSTM(4, 32, batch_first=True)
  )
  (output_layer): Linear(in_features=32, out_features=1, bias=True)
)
> model.device
'cpu'

虽然我读到您不需要将 model.to() 调用分配回对象,但我也试过了。

> model = model.to(device)
> model.device
'cpu'

device 很可能是用户定义的属性,与模型所在的实际设备不同。这好像就是为什么 model.device returns 'cpu' 要检查你的模型是在 CPU 还是 GPU 上,你可以看它的第一个参数:

>>> next(model.parameters()).device