欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-02-16 10:40:22|栏目:Python代码|点击:

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)
 

上一篇:Python中的MongoDB基本操作:连接、查询实例

栏    目:Python代码

下一篇:关于不懂Chromedriver如何配置环境变量问题解决方法

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

本文地址:http://www.codeinn.net/misctech/63826.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有