pytorch:在执行loss.backward()时out of memory报错

在自己编写SurfNet网络的过程中,出现了这个问题,查阅资料后,将得到的解决方法汇总如下
可试用的方法:

  1. reduce batch size, all the way down to 1
  2. remove everything to CPU leaving only the network on the GPU
  3. remove validation code, and only executing the training code
  4. reduce the size of the network (I reduced it significantly: details below)
  5. I tried scaling the magnitude of the loss that is backpropagating as well to a much smaller value
  6. 在训练时,在每一个step后面加上:
torch.cuda.empty_cache()
  1. 在每一个验证时的step之后加上代码:
   with torch.no_grad()
  1. 不要在循环训练中累积历史记录
total_loss = 0
for i in range(10000):
    optimizer.zero_grad()
    output = model(input)
    loss = criterion(output)
    loss.backward()
    optimizer.step()
    total_loss += loss

total_loss在循环中进行了累计,因为loss是一个具有autograd历史的可微变量。你可以通过编写total_loss += float(loss)来解决这个问题。

本人遇到这个问题的原因是,自己构建的模型输入到全连接层中的特征图拉伸为1维向量时太大导致的,加入pool层或者其他方法将最后的卷积层输出的特征图尺寸减小即可。

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值