requires_grad=True
会导致将其转移到GPU时失去叶片状态?例如(在Google Colab笔记本中测试):
b = torch.rand(10).cuda()
b.is_leaf # True
和
b = torch.rand(10, requires_grad=True)
b.is_leaf # True
But
b = torch.rand(10, requires_grad=True).cuda()
b.is_leaf # False
我意识到,b = torch.rand(10, requires_grad=True, device='cuda')
导致
b
在被转移到GPU后保留其叶子状态,这是一个非常出色的解决方法。但是,我对上述行为感到非常困惑。
的张量,如果用户创建的,它们将是叶子张量。这意味着它们不是操作的结果,因此False
没有。 在您的第一个示例中:True
具有,因此被认为是叶子张量。 您的第二个示例:grad_fn
b = torch.rand(10).cuda() b.is_leaf # True
b
requires_grad=False
,因此是叶子张量。
您的第三个示例:
b = torch.rand(10, requires_grad=True)
b.is_leaf # True
它在此返回false,因为创建张量并将张量移至GPU是两个单独的操作。叶子张量是原始张量。调用b
是一个单独的操作,返回新张量。
从Pytorch文档中:requires_grad=True
可以通过检查其他张量属性来更明确地看到这一点:
b = torch.rand(10, requires_grad=True).cuda()
b.is_leaf # False
中以上,由用户创建并具有torch.rand(10, requires_grad=True)
.cuda()
是>>> a = torch.rand(10, requires_grad=True)
>>> a.is_leaf
True
>>> b = torch.rand(10, requires_grad=True).cuda()
>>> b.is_leaf
False
# b was created by the operation that cast a cpu Tensor into a cuda Tensor
。我们创建
b = torch.rand(10, requires_grad=True)
b.data_ptr()
> 1934898880
b.grad_fn
> None
b.is_leaf
> True
c = b.cuda()
c.data_ptr()
> 140481214283776 # different data pointer
c.grad_fn
> <ToCopyBackward0 at 0x7fc5f44839a0> # has grad function
c.is_leaf # is no longer a leaf tensor
> False
创建一个新的张量对象。我们可以通过看到它具有不同的b
来验证这一点。
requires_grad=True
有
b
,这是Pytorch通过设备开关操作向后向后的方式。
最终,当您使用grad_fn
时,您是在单个操作中直接在GPU上创建None
,因此它是叶子张量。