【问题标题】:PyTorch: What is the difference between tensor.cuda() and tensor.to(torch.device("cuda:0"))?PyTorch:tensor.cuda() 和 tensor.to(torch.device("cuda:0")) 有什么区别?
【发布时间】:2023-04-05 09:03:01
【问题描述】:

在PyTorch中,以下两种发送张量(或模型)到GPU的方法有什么区别:

设置:

X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]]) # X = model()
X = torch.DoubleTensor(X)
Method 1 Method 2
X.cuda() device = torch.device("cuda:0")
X = X.to(device)

(我真的不需要详细解释后端发生的事情,只是想知道它们是否本质上都在做同样的事情)

【问题讨论】:

    标签: python pytorch gpu


    【解决方案1】:

    两者没有区别。
    pytorch 的早期版本有 .cuda().cpu() 方法将张量和模型从 cpu 移动到 gpu 并返回。但是,这使得代码编写有点麻烦:

    if cuda_available:
      x = x.cuda()
      model.cuda()
    else:
      x = x.cpu()
      model.cpu()
    

    后来的版本引入了.to(),它基本上以一种优雅的方式处理所有事情:

    device = torch.device('cuda') if cuda_available else torch.device('cpu')
    x = x.to(device)
    model = model.to(device)
    

    【讨论】:

      【解决方案2】:

      它们的语法略有不同,但they are equivalent:

      .to(name) .to(device) .cuda()
      CPU to('cpu') to(torch.device('cpu')) cpu()
      Current GPU to('cuda') to(torch.device('cuda')) cuda()
      Specific GPU to('cuda:1') to(torch.device('cuda:1')) cuda(device=1)

      注意:当前cuda设备默认为0,但可以用torch.cuda.set_device()设置。

      【讨论】:

        猜你喜欢
        • 2016-03-23
        • 2021-06-16
        • 2015-03-26
        • 2012-09-23
        • 2021-02-13
        • 2012-08-02
        • 1970-01-01
        相关资源
        最近更新 更多