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

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

相关推荐

  1. GPU

    2024-04-30 02:24:03       42 阅读
  2. tensorflow中分配

    2024-04-30 02:24:03       37 阅读
  3. pytorch 优化训练方式

    2024-04-30 02:24:03       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-30 02:24:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-30 02:24:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-30 02:24:03       82 阅读
  4. Python语言-面向对象

    2024-04-30 02:24:03       91 阅读

热门阅读

  1. 【Pyhton爬虫实战】爬取京东商城的商品信息

    2024-04-30 02:24:03       34 阅读
  2. Rest开发

    2024-04-30 02:24:03       26 阅读
  3. R语言 数据整理篇之结构重塑

    2024-04-30 02:24:03       31 阅读
  4. JVM内存参数调优大展神威

    2024-04-30 02:24:03       31 阅读
  5. less和scss循环生成margin和padding

    2024-04-30 02:24:03       27 阅读
  6. 【Spring AI】01. 概述

    2024-04-30 02:24:03       29 阅读
  7. 001 springCloudAlibaba 负载均衡

    2024-04-30 02:24:03       24 阅读
  8. SpringBoot整合Mybatis实现多数据源配置

    2024-04-30 02:24:03       32 阅读