PyTorch Bug 记录:one of the variables needed for gradient computation has been modified by an inplace

有一段代码在 pytorch 1.2 上没有问题,但是移植到 pytorch 1.8 就会报如下错误:

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [3136, 10]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

经过检查,代码里并没有用到 inplace 操作。
后来发现这是 pytorch 版本更新造成的,对于 pytorch 1.4 之前的版本,如下代码是不会出错的:

opt1.zero_grad()
loss1.backward()
opt1.step()

opt2.zero_grad()
loss2.backward()
opt2.step()

但是更新到 pytorch 1.5 之后,这种操作就会报错,应该用下面代码代替:

opt1.zero_grad()
loss1.backward()

opt2.zero_grad()
loss2.backward()

opt1.step()
opt2.step()

这个BUG难了我一下午,特此记录一下。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大指挥官

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值