gpu - 为 GPU 设置参数 is_leaf 为 false

标签 gpu pytorch autograd

如果我在 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/

相关文章:

python - Numpy:更快地计算涉及求和的三重嵌套循环

python - PyTorch 加载 "\lib\site-packages\torch\lib\shm.dll"或其依赖项之一时出错

python - 更新 PyTorch 中的 register_buffer?

python - 使用自动微分库计算任意张量的偏导数

c++ - OpenGL:在帧中回收帧缓冲区会影响性能吗?

c - 为什么 cuda 中的 in-kernel-printf 在显示在显示器上之前将字符串输出到主机?

python - PyTorch torch.no_grad() 与 requires_grad=False

python - torch 。当最终张量中有多个值时,可以使用 autograd 吗?

Pytorch 的 autograd 问题与 joblib

ubuntu - 在 ubuntu 14.04 上找不到 libsiftgpu.so