【问题标题】:Expected object of backend CPU but got backend CUDA for argument #2 'source'后端 CPU 的预期对象,但获得了参数 #2 'source' 的后端 CUDA
【发布时间】:2019-06-21 19:57:47
【问题描述】:

我尝试了其他答案,但错误没有被删除。与我得到的另一个问题的不同之处在于,错误使用的最后一个术语是“source”,我在任何问题中都没有找到。如果可能,还请解释错误的术语“来源”。并且在没有 CPU 的情况下运行代码也可以正常工作。

我正在使用启用了 GPU 的 Google Colab。

import torch
from torch import nn
import syft as sy

hook = sy.TorchHook(torch)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model = nn.Sequential(nn.Linear(784,256),
                     nn.ReLU(),
                     nn.Linear(256,128),
                     nn.ReLU(),
                     nn.Linear(128,64),
                     nn.ReLU(),
                     nn.Linear(64,10),
                     nn.LogSoftmax(dim = 1))

model = model.to(device)

输出:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-42-136ec343040a> in <module>()
      8                      nn.LogSoftmax(dim = 1))
      9 
---> 10 model = model.to(device)

3 frames
/usr/local/lib/python3.6/dist-packages/syft/frameworks/torch/hook/hook.py in data(self, new_data)
    368 
    369                 with torch.no_grad():
--> 370                     self.set_(new_data)
    371             return self
    372 

RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'source'

【问题讨论】:

    标签: python python-3.x pytorch


    【解决方案1】:

    此问题与PySyft 有关。正如你在这个Issue#1893 中看到的,当前的workaround 是要设置的:

    import torch
    torch.set_default_tensor_type(torch.cuda.FloatTensor)
    

    就在import torch之后。

    代码:

    import torch
    from torch import nn
    torch.set_default_tensor_type(torch.cuda.FloatTensor)  # <-- workaround
    
    import syft as sy
    hook = sy.TorchHook(torch)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print(device)
    
    model = nn.Sequential(nn.Linear(784,256),
                         nn.ReLU(),
                         nn.Linear(256,128),
                         nn.ReLU(),
                         nn.Linear(128,64),
                         nn.ReLU(),
                         nn.Linear(64,10),
                         nn.LogSoftmax(dim = 1))
    
    model = model.to(device)
    print(model)
    

    输出:

    cuda
    Sequential(
      (0): Linear(in_features=784, out_features=256, bias=True)
      (1): ReLU()
      (2): Linear(in_features=256, out_features=128, bias=True)
      (3): ReLU()
      (4): Linear(in_features=128, out_features=64, bias=True)
      (5): ReLU()
      (6): Linear(in_features=64, out_features=10, bias=True)
      (7): LogSoftmax()
    )
    

    【讨论】:

    • 非常感谢!现在它正在工作。花了 4 个小时在我的代码中查找问题。
    • @RavikantSingh 它发生在我们所有人身上:)
    猜你喜欢
    • 2019-09-22
    • 2019-12-23
    • 2019-10-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2020-03-07
    • 2020-11-22
    相关资源
    最近更新 更多