c10::CUDAOutOfMemoryError怎么解决

学习libtorch 调用pt模型时

运行语句module.forward()时

c10::CUDAOutOfMemoryError怎么解决

参考这篇文章:https://blog.csdn.net/junmuzi/article/details/97812964

分析分析:

这是典型的gpu显存不足的问题

解决方案:

(1) 最简单的方法,将训练的batch_size改小。

(2) 最直接的方式,更换显存更大的显卡

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