一文解决 RuntimeError: CUDA out of memory. 全网最全

本文详细介绍了如何解决在使用PyTorch时遇到的CUDA Out of Memory问题,包括调整batch_size、清理缓存、使用`no_grad()`、调整pin_memory设置及环境变量配置等实用技巧。

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

Pytorch解决 RuntimeError: CUDA out of memory.

一、问题:

RuntimeError: CUDA out of memory. Tried to allocate 50.00 MiB (GPU 0; 4.00 GiB total capacity; 682.90 MiB already allocated; 1.62 GiB free; 768.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

二、分析

这是GPU内存不足引起的

三、解决

方法一:调整batch_size 一般为2的n次方,一般为4,如果不行,则pass

方法二:清除pytorch无用缓存,在代码总加入如下代码,亲测有效

import torch, gc

gc.collect()
torch.cuda.empty_cache()

方法三:在测试阶段和验证阶段前插入代码 with torch.no_grad()(目的是该段程序不计算参数梯度),如下:

评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值