无法在 GPU 中训练 PyTorch 模型。不断收到张量不在同一设备上的错误

xiaoxingxing pytorch 491

原文标题Unable to train PyTorch model in GPU. Keep getting errors that tensors are not on same device

我一直试图在 GPU 中训练我的 PyTorch 模型。该模型在 CPU 中完美运行。我一直在使用 Google Colab 的 GPU 资源来使用 cuda。

我知道为了在 GPU 中运行模型,“模型”、“输入特征”和“目标”需要在“cuda”设备中。

但是,无论我在代码中做什么,我都会不断收到错误消息:

RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and hidden tensor at cpu

要么

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

这是我的笔记本:

https://colab.research.google.com/drive/1rviS_4hmdzPQUncZyi8FsRH7y3jL0isQ

如果有人可以让我准确地使用哪些变量来移动,那将非常有帮助.to('cuda')

此外,我们将高度赞赏确保这种情况不会在未来再次发生的解释/建议。谢谢 !

原文链接:https://stackoverflow.com//questions/71467398/unable-to-train-pytorch-model-in-gpu-keep-getting-errors-that-tensors-are-not-o

回复

我来回复
  • Shai的头像
    Shai 评论

    你的self.hiddentorch.tensors的元组。当在您的模型上调用.to(device)时,PyTorch 不会自动将这些张量移动到 GPU。

    您可以:

    1. 为您的 BiLSTM_CRF 类实现您自己的 to(self, type, device) 方法。 (不建议)。
    2. 使 self.hidden 成为注册的缓冲区。这样 nn.Module 的所有方法,例如 .to() 、 .float() 等也将应用于 self.hidden 。
    2年前 0条评论