pytorch 的 inplace 的问题

背景:

最近将一个模型训练代码从caffe平台移植到pytorch平台过程中遇到了一个诡异的inplace坑,特别记录一下防止大家掉坑。

relu等激活函数的inplace:

看到官方的relu入参是中nn.ReLU(inplace=True)是inplace操作,我一想这不是能节省我的资源占用,毫不犹豫的选择了True。搭好模型运行,结果是在backward计算导数的时候。表示inplace操作导致求导结果有问题。改为**nn.ReLU(inplace=False)**问题在pytorch1.3和pytorch1.8解决了。

“+=”操作的默认inplace:

后来因为换了pytorch1.10版本后又报错了。报错形式和上面一样。后来查了一下“+=”也是inplace操作,将工程中网络的前向传播方式中:x += feature16改为:“x = x + feature16” 。问题就消失了。

报错形式

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.HalfTensor [×,×,×,×]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

最后说两句

pytorch1.8版本有个问题偶发大家多加小心:https://github.com/pytorch/pytorch/issues/54752 尤其训练数据较多的时候

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值