【程序错误-显存不足】RuntimeError: CUDA out of memory. Tried to allocate 4.00 GiB

发布于:2024-05-08 ⋅ 阅读:(25) ⋅ 点赞:(0)

1. 问题

RuntimeError: CUDA out of memory. Tried to allocate 4.00 GiB
(GPU 0: 23.65 GiB total capacity: 19.43 GiB already allocated:2.41 GiB free;19.49 GiB reserved in total by PyTorch) If reserved memory is allocated memory setting max_split_size_mb to avoid fragmentation.See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

2. 解决方法

2.1 租服务器(试过有用)

在这里插入图片描述

2.2 减小batchsize

减少每次训练或推理时的批次大小,以降低显存的需求。较小的批次大小可能会增加训练时间,但可以减少显存压力。假设,B=1了,那就得想其他方法了。

2.3 减少模型大小

如果你使用的是大型模型,可以尝试减少模型的大小,以减少显存使用量。这可以通过减少网络层数、减少隐藏单元数量或使用更小的嵌入向量等方式实现。

使用更低精度的数据类型:将模型参数和激活值从32位浮点数(float32)转换为16位浮点数(float16),可以减少显存的使用。在PyTorch中,你可以使用.half()方法将模型转换为使用半精度浮点数。

2.3 检查模型本身没有发现错误,最终确认是验证集评估阶段的张量计算非常占用空间。

参考:pytorch运行错误:CUDA out of memory. [已解决]

2.3.1 可以对利用torch.tensor().detach().cpu().numpy()转为numpy,在cpu上进行loss和acc的计算

2.3.2 直接对评估阶段使用with torch.no_grad():

2.4 释放内存

在报错的哪一行代码的上面,加上下面两行代码,释放无关的内存。

if hasattr(torch.cuda, 'empty_cache'):
	torch.cuda.empty_cache()

2.5 使用多卡训练

如果你有多个GPU可用,可以尝试使用多卡训练。这样可以将模型的不同部分分配到不同的GPU上,从而减少单个GPU上的显存需求。

参考

[1] 解决:RuntimeError: CUDA out of memory. Tried to allocate 2.00 MiB
[2] RuntimeError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 4.00 GiB total capacity; 2.44
[3] 爆显存:RuntimeError: CUDA out of memory. Tried to allocate 5.66 GiB (GPU 0; 12.00 GiB total capacity; 2