为 GPU 分配参数将 is_leaf 设置为 false

问题描述 投票:0回答:2

如果我在 PyTorch 中创建一个

Parameter
,那么它会自动分配为叶变量:

x = torch.nn.Parameter(torch.Tensor([0.1]))
print(x.is_leaf)

打印出

True
。据我了解,如果
x
是叶变量,那么它将由优化器更新。

但是如果我随后将

x
分配给 GPU:

x = torch.nn.Parameter(torch.Tensor([0.1]))
x = x.cuda()
print(x.is_leaf)

打印出

False
。所以现在我无法将
x
分配给 GPU 并将其保留为叶节点。

为什么会出现这种情况?

pytorch cuda gpu autograd
2个回答
2
投票

答案在

is_leaf
文档中,这是您的确切情况:

>>> 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

进一步引用文档:

对于具有

requires_grad
为 True 的张量,它们将是叶子 张量(如果它们是由用户创建的)。这意味着他们不是 运算的结果,因此 grad_fn 为 None。

在你的例子中,

Tensor
不是由你创建的,而是由PyTorch的cuda()
操作创建的(leaf是预cuda
b
)。


0
投票
修复该示例的一种方法是将

.cuda()

 移至参数构造函数内:

torch.nn.Parameter(torch.Tensor([0.1]).cuda()) print(x.is_leaf)
打印出来

True

© www.soinside.com 2019 - 2024. All rights reserved.