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()(目的是该段程序不计算参数梯度),如下: