pytorch out of memory

使用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)

参考:
https://www.v2ex.com/t/532315

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容