Pytorch 训练与测试时爆显存(out of memory)的一个解决方案

本文分享了在Pytorch中遇到显存溢出问题时的解决策略,包括使用torch.cuda.empty_cache()清理缓存和确保在测试阶段正确使用torch.no_grad()避免不必要的内存消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Original url:

https://blog.youkuaiyun.com/xiaoxifei/article/details/84377204

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)
 
--------------------- 
作者:xiaoxifei 
来源:优快云 
原文:https://blog.youkuaiyun.com/xiaoxifei/article/details/84377204 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值