错误:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
报错原因:
import torch
x = torch.FloatTensor([[1., 2.]])
w1 = torch.FloatTensor([[2.], [1.]])
w2 = torch.FloatTensor([3.])
w1.requires_grad = True
w2.requires_grad = True
d = torch.matmul(x, w1)
f = torch.matmul(d, w2)
d[:] = 1 # 因为这句, 代码报错了 RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
f.backward()
因为
对于
的导数是关于
的函数。
在计算的时候
是一个值,而在计算导数的时候
变为了另外一个值。这时候导数就出现了错误。
造成这个问题的主要原因是因为 在执行 f = torch.matmul(d, w2) 这句的时候, pytorch 的反向求导机制 保存了 d 的引用为了之后的 反向求导计算.
作者:ke1th
链接:https://zhuanlan.zhihu.com/p/38475183
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
---------------------------------------------------------------------------------------------------------------------------------------------------------
检查错误:
而在自己的代码中报这个错误时,只能知道是在batch_loss.backward()这一行出错,具体是在哪里报错并不清楚,这就给检查代码造成了一些困难。
然后通过知乎上的
这个回答,找到了灵感!
在自己代码中对矩阵操作确实有个赋值是a = ...a这种,然后就改了这几行代码,就能成功运行了!
之前用的feature = feature,可能会让pytorch的求导机制变得迷惑吧(^-^)V。
尤其是知乎上这篇文章讲的很详细!
关于 pytorch inplace operation, 需要知道的几件事 - ke1th的文章 - 知乎 https://zhuanlan.zhihu.com/p/38475183