import torch
from torch.autograd import Variable
a = Variable(torch.Tensor([1, 2]))
if torch.cuda.is_available():
b = a.cuda()
b_data = b.data
b_grad = b.grad
b_grad_data = b.grad.data
如果.data
和.grad
是类属性,则.cuda()
可以保留为属性,以便执行b = a.cuda
。 我提出建议认为它会增加 API 的一致性,因为.cuda()
、 .data
和.grad
是torch.Tensor
所以 cuda() 可以更改为属性. 通过这样做,可以通过model.cuda
访问 GPU 驻留模型
cuda
是一种方法,因为它是一项相对昂贵的操作,涉及将数据从 CPU 复制到 GPU。 而grad
和data
是廉价操作( O(1)
),它们只检索对相应张量的引用。 我认为使cuda
成为一种方法是合理的。
.cuda() 将 CPU 数据复制到 GPU。 您可能不想一直将数据保存在 GPU 中。 这意味着,您仅在真正需要时才将数据存储在 GPU 中。
正如上述两条评论所提到的,将.cuda
设为属性是不合适的。 我们在引用.cuda()
时返回新对象,并且发生了很多事情。
最有用的评论
cuda
是一种方法,因为它是一项相对昂贵的操作,涉及将数据从 CPU 复制到 GPU。 而grad
和data
是廉价操作(O(1)
),它们只检索对相应张量的引用。 我认为使cuda
成为一种方法是合理的。