解决Pytorch 训练与测试时爆显存(out of memory)的问题

(编辑:jimmy 日期: 2024/9/26 浏览:2)

Pytorch 训练时有时候会因为加载的东西过多而爆显存,有些时候这种情况还可以使用cuda的清理技术进行修整,当然如果模型实在太大,那也没办法。

使用torch.cuda.empty_cache()删除一些不需要的变量代码示例如下:

try:
  output = model(input)
except RuntimeError as exception:
  if "out of memory" in str(exception):
    print("WARNING: out of memory")
    if hasattr(torch.cuda, 'empty_cache'):
      torch.cuda.empty_cache()
  else:
    raise exception

测试的时候爆显存有可能是忘记设置no_grad, 示例代码如下:

  with torch.no_grad():
    for ii,(inputs,filelist) in tqdm(enumerate(test_loader), desc='predict'):
      if opt.use_gpu:
        inputs = inputs.cuda()
        if len(inputs.shape) < 4:
          inputs = inputs.unsqueeze(1)
 
      else:
        if len(inputs.shape) < 4:
          inputs = torch.transpose(inputs, 1, 2)
          inputs = inputs.unsqueeze(1)
 

以上这篇解决Pytorch 训练与测试时爆显存(out of memory)的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。