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

文章讲述了在使用PyTorch编写训练代码时遇到的RuntimeError,问题源于inplace操作。解决方法是避免使用`-=`和`/=`,改为创建新变量。作者推测可能是由于临时变量或运算符兼容性导致的,建议在训练代码中使用完整语句以确保正确性。
摘要由CSDN通过智能技术生成

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [256, 5]], which is output 0 of SubBackward0, 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).

今天用pytorch写训练代码的时候出现该错误。
在这里插入图片描述
发现问题出现在下面两个语句:

            x -= torch.mean(x,dim=1).reshape(-1,1)
            x /= torch.std(x,dim=1).reshape(-1,1)

将其改为:

            x = x-torch.mean(x,dim=1).reshape(-1,1)
            x = x/torch.std(x,dim=1).reshape(-1,1)

就能正确运行了。笔者猜测可能是临时变量的原因?或者是pytorch-=,/=相关的运算符兼容性没弄好,总之以后写训练代码的时候不要用-=,/=相关的简写,一律老老实实的写完整。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值