0
点赞
收藏
分享

微信扫一扫

Runtime Error CUDA error out of memory

小磊z 2022-02-27 阅读 85

Runtime Error CUDA error out of memory

问题描述

出错描述:在训练模型python train.py 的时候,出现 RuntimeErrorCUDA error out of memory 错误

出错原因:字面意思,out of memory

问题处理(三种常见的解决方式)

1、查看GPU的使用情况,切换(多GPU的情况)

在服务器上输入 :

nvidia-smi

查看GPU的使用情况:
在这里插入图片描述

可以看到第0个GPU 使用占了,可以用空闲的第1GPU来跑你的程序,修改CUDA_VISIBLE_DEVICES 的值,默认是 0

import os
os.environ["CUDA_VISIBLE_DEVICES"] = '1'

2、释放缓存

在报错的代码中加上异常捕捉的代码,清除空的缓存

try:
    trainer.train(30)
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

3、torch.no_grad()

对于tensor的计算操作,默认是要进行计算图的构建的,我们可以使用 with torch.no_grad():

让其不进行计算图构建,这样可以缓解GPU计算压力

with torch.no_grad():
    trainer.train(30)
举报

相关推荐

0 条评论