前言:
在调试计算模型梯度的时候突然蹦出:<input>:1: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations.
(持续更新,)
1更:2022.08.30
一、问题分析
博主想得到loss计算环节某个变量的梯度,经过检查发现该变量的requires_grad()为True,但是在输出他的梯度的时候却出现上面的警告。
这个报错的大致翻译如下:
<input>:1:UserWarning:正在访问非叶张量的张量的.grad属性。在autograd.backward()期间不会填充其.grad属性。如果确实需要非叶张量的梯度,请在非叶张量上使用.retain_grad()。如果您错误地访问了非叶张量,请确保您访问了叶张量。
一句话总结是:
并不是 requires_grad()为True就可以输出对应的梯度,还要看is_leaf属性&