Pytorch报错:one of the variables needed for gradient computation has been modified by an inplace opera

时间:2019-02-16
本文章向大家介绍Pytorch报错:one of the variables needed for gradient computation has been modified by an inplace opera,主要包括Pytorch报错:one of the variables needed for gradient computation has been modified by an inplace opera使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用一个pytorch写的模型时,训练到45epoch时,报错:RuntimeError:one of the variables needed for gradient computation has been modified by an inplace operation

But this error just appears in some places. Why it occurs?

Because the inplace op overwrites some data that’s needed by some Function to compute the gradient. It has no way of doing that after you overwrite it. Just remove inplace=True in these places.

  • 错误分析:由于pytorch升级到pytorch0.4之后,与之前pytorch0.3的用法发生来了一些变化,比如最重要的在pytorch0.4中将Tensor与Variance都组合成了同一个东西,pytorch0.4不再支持inplace操作。
  • 解决方法:基本网上我能看到的所有资料,可执行的方案主要有以下几点:
  • 解决方案1:把所有的inplace=True改成inplace=False
  • 解决方案2:将out+=residual这样所有的+=操作,改成out=out+residual
  • 解决方案3: 将pytorch版本回退到0.3,或者添加一个pytorch0.3的conda环境。

此类问题的一点总结:以上的方案1与方案2其实都是在解决pytorch0.4不能处理inplace操作的问题。但是其实都不全。

举个简单的例子来理解一下inplace=True与inplace=False,就像所有的博客里给出的+=这个操作。x+=1是在x的基础上直接做加法操作的,这个就属于在原来的x上做扩展,是inplace=True的情况。而x=x+1就是先做加法,然后重新赋值,就是inplace=False。

但是我们要注意到+=只是inplace的一种操作,并不是把所有的+=替换掉就可以解决问题的。在这篇博客pytorch 学习笔记(二十二):关于 inplace operation中给出了完整的说明,非常建议看看。

总结一下:如果你的程序比较简短,情况比较简单,那么就直接改里面的+=这样的inplace操作。另外在修改的时候可以用variance.backward()来试试这个variance之前的代码是不是都已经正确了。 如果代码量比较大,那还是建议用conda再创建一个环境,用来安装pytorch0.3,简单省事。

  1. 创建一个名为pytoch0.3的conda环境:conda create -n pytorch0.3 python=3.6;
  2. 激活pytorch0.3环境:source activate pytorch0.3,这时中断提示符前面会多一个pytorch0.3标记;
  3. 要关闭pytorch0.3环境,就用: source deactivate;
  4. 在里面用conda安装0.3版本的pytorch:先在官网下载对应的版本torch-0.3.1-cp36-cp36m-linux_x86_64.whl,进入目录用pip install torch-0.3.1-cp36-cp36m-linux_x86_64.whl命令安装pytorch,然后再用pip install torchvision安装torchvision。