解决”one of the variables needed for gradient computation has been modified by an inplace operation”报错问题

 one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [16, 64, 256, 256]], which is output 0 of LeakyReluBackward1, is at version 1; 

最近跑代码遇到了这样的一个问题,在网上找了很多方法都没有很好的解决,今天就在这个博客里面将所有的解决办法整理记录一下。

解决方法1:

去查看所有的loss反串的代码区域:

需要将这种loss反串的代码修改为:

即都应该在计算loss后再进行反传和优化器的优化。

解决办法2:

有很多人在写代码的时候遇到了反传过程中设置了retain_grah为True的问题,需要将这部分设置为False或者直接把这个给去掉。

   

解决办法3:

即问题中所描述的inplace operation的问题,这种问题常常是某些变量还没有保存就已经被替换掉了,一般在报错的过程中会显示错误变量的shape,这时最好是看一下代码中关于这个shape的所有变量,加上clone(),试试!我就是这个问题,试完我的问题就解决了。

 

 问题4:

在pytorch中, inplace operation 可以是一些 .add_() 或 .scatter_() 导致的。对于.add_()方法,是直接在tensor上进行修改的,可以把x.add_(y)改成x = x + y。如果需要复制一个副本话,参照第二个帖子的方法,可以使用.clone()方法。

在python中, inplace operation 可以是一些 += 或 *= 导致的。比如 x += y,需要改成 x = x +y
 

 

 

 

 

物联沃分享整理
物联沃-IOTWORD物联网 » 解决”one of the variables needed for gradient computation has been modified by an inplace operation”报错问题

发表评论