pytorch与cuda版本不对应导致RuntimeError: CUDA error: out of memory

问题描述:

在重现github代码MhLiao/DB时,我遇到了错误:RuntimeError: CUDA error: out of memory


情况一:程序batch_size过大,超过了显存。

排查:

使用命令watch -n 0.2 nvidia-smi监控显卡使用情况,然后运行代码。如果显存情况一直变大,然后突然掉为0,则是情况一所述。

解决:

适当调小batch_size的值


情况二:pytorch和cuda版本不对应

由于我无法使用程序要求的pytorch1.2+cuda10.0,所以我只能安装其他版本的环境。这时候反复确认pytorch、cuda、python版本的对应情况就尤为重要
版本对应情况参考:pytorch、python、cuda版本对应参考

排查

运行下列代码检测cuda和pytorch版本是否对应

import torch
a=torch.Tensor([1,2])
a=a.cuda()
print(a)

不报错则说明版本对应正确。输出仍然报错RuntimeError即可能是版本不对

解决

根据版本对应参考,调整到对应的pytorch、python、cuda版本
附上:pytorch官网cuda官网

注意

根据上诉版本对应情况,我调整环境为pytorch1.8+cuda11.3。反复确认我的环境没问题,但依然报错RuntimeError。经过排查发现,我在安装pytorch1.8时,原本的命令为:
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html

由于安装速度过慢,我将原本的网页地址改为中国科学技术大学的镜像源,即:
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -i https://pypi.mirrors.ustc.edu.cn/simple/

这时报错torch版本里没有1.8.0+cu111:
报错
所以删除命令中的+cu111,调整为:
pip install torch==1.8.0 torchvision==0.9.0 torchaudio==0.8.0 -i https://pypi.mirrors.ustc.edu.cn/simple/

安装成功后,运行验证版本代码时依旧报错:RuntimeError:CUDA error: out of memory,这种命令安装的pytorch版本任然不符合cuda的要求。

正确的命令,一种是原命令(速度很慢),另一种(速度起飞)是在整个原命令后加镜像源地址,而不是使用镜像源地址替换原来的网址,正确的命令为:
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.htm -i https://pypi.mirrors.ustc.edu.cn/simple/

使用正确的命令安装的pytorch只要和cuda版本对应,就不会再报错RuntimeError。

附上:各个镜像源地址

猜你喜欢

转载自blog.csdn.net/Norton_Paige/article/details/129726857