【PyTorch】常见错误: RuntimeError:one of the variables needed for gradient computation has been modified

【PyTorch】常见错误


 
错误:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation.


       
问题原因:

pytorch版本导致的,0.3.0版本不会报错,0.4.0就报错;由于后者版本将Variable和Tensor合并为Tensor,但是inplace操作对Tensor不能用,因此报错。


       
解决方法:

查阅网上资料,可执行方案有以下几点:

  • 找到网络模型中的 inplace 操作,将inplace=True改成 inplace=False
  • 将网络结构中的+=操作进行修改,如下所示:
out = out + res    	# not inplace
out += res			# inplace

若网络结构很大,那就需要慢慢调试,加一句out.backward(),观察是否报错,若没有,则之前没错。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章