深度学习网络训练时,出现这个错误:
one of the variables needed for gradient computation has been modified by an inplace operation
原因:某个变量在前向计算时是一个值,在求梯度时变成了另一个值(inplace 操作导致),使得pytorch在反向梯度求导时产生了错误
可能由两种情况导致(目前我遇到两种情况),解决方案:
1、替换所有的in-place操作:
(1)x += 1 改成 x = x + 1
(2)x[:, :, 0:3] = x[:, :, 0:3] + 1 改成 x[:, :, 0:3] = x[:, :, 0:3].clone() + 1
注意:tranceback报错时只提示loss.backward()这一行产生了错误,并没有给出具体是哪个语句的问题。导致很难debug,用torch.autograd.set_detect_anomaly(True) 可回溯问题语句。
2、将网络中inplace=True的地方改为inplace=False