报错信息:
【Error】 one of the variables needed for gradient computation has been modified by an inplace operation
问题描述
计算梯度的时候检查出某个Variable
有被一个 inplace operation
修改。是反向传播的过程中出错的。
nplace operation
就是直接对tensor
的内容进行修改,而没有使用复制的副本
(An in-place operation is an operation that changes directly the content of a given Tensor without making a copy)。
在pytorch
中, inplace operation
可以是一些 .add_()
或 .scatter_()
导致的。对于.add_()
方法,是直接在tensor
上进行修改的,可以把x.add_(y
)改成x = x + y
。如果需要复制一个副本,可以使用.clone()
方法。
解决方案
在python
中, inplace operation
可以是一些 +=
或 *=
导致的。比如x += y
,需要改成x = x +y