如何解决报错one of the variables needed for gradient computation has been modified by an inplace operation?

  参考资料:

  https://discuss.pytorch.org/t/what-is-in-place-operation/16244

  https://blog.csdn.net/qq_35056292/article/details/116695219

  参考资料二已经说明了问题,对我的情况是使用了+=运算符从而导致了报错。

  比如:cost是ReLU函数的运算结果,按照正常的发展来看,cost会参与其他变量的计算,比如 f = cost + value,然后对f进行反向传播。

  但是如果使用了这种计算方式:cost += A,pytorch会认为这是一个inplace的操作,从而cost的值就发生了变化(在原来的内存空间里,所谓inplace)

  这样在反向传播的时候pytorch就会检测出cost发生了变化,就会报错。

  解决方案是使用其他的方式,比如result = cost + A,后文再用result参与运算就好了。

 
posted @ 2022-07-17 00:18  思念殇千寻  阅读(909)  评论(0编辑  收藏  举报