如果我在 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 并将其保留为叶节点。
为什么会这样?
最佳答案
答案在 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
进一步引用文档:
For Tensors that have
requires_grad
which is True, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so grad_fn is None.
在你的例子中,Tensor
不是由你创建的,而是由 PyTorch 的 cuda()
操作创建的(叶子是预cuda b
).
关于gpu - 为 GPU 设置参数 is_leaf 为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188409/