报错:RuntimeError: CUDA error: no kernel image is available for execution on the device
提醒:安装pytorch时,除了要注意pytorch与torchvision版本的匹配,也要注意pytorch与cuda的版本兼容。不然……,安装环境会让你想吐~
1.报错原因
利用anaconda安装好了适配项目的pytorch虚拟环境,运行程序时,报错RuntimeError: CUDA error: no kernel image is available for execution on the device
在出现这个报错原因之前,如下图所示,有一行提示写着3090显卡所装的cuda版本与当前安装的pytorch版本不适配。
2.查看系统的cuda版本
命令:
nvcc -V
可看到,系统的cuda版本为v11.2.67
命令:
nvidia-smi
此命令查看到的是与NVIDIA驱动相匹配所需的cuda版本,但实际安装的cuda版本可以略低于驱动版本,所以系统实际安装的cuda版本为11.2。
有可能是之前适配paddlepaddle框架,系统安装了11.2的cuda版本。
3.查看与cuda匹配的pytorch版本
参考官网链接:https://pytorch.org/get-started/previous-versions/
查看pytorch各版本和cuda版本对应关系
目前的cuda版本 V11.2.67
Pytorch 版本需要 torch==1.8.0
Torchvision 版本需要 0.9.0
4.重新安装pytorch
网上搜了一堆方法,首先走了个弯路,卸载了旧版本,使用以下命令,安装了适配cuda11.2版本的pytorch
conda install torch==1.8.0 torchvision==0.9.0 cudatoolkit==11.2 -c pytorch -c conda-forge
但是……
报错,在anaconda官网 https://anaconda.org 找不到torch==1.8.0的资源
再看上面表格,发现没有cuda11.2版本对应的pytorch
又发现高版本的pytorch一般能兼容低版本cuda,所以不一定非要下载cuda11.2对应的torch版本,或许低于这个版本就可以。所以选择下载cuda11.1版本的torch。
可以参照以下网址下载pytorch对应的稳定版
https://blog.csdn.net/wangmengmeng99/article/details/128318248
最终使用pip安装了cuda11.1版本的torch和torchvision
# CUDA 11.1
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html
终于安装成功!
测试是否安装成功:
import torch
torch.cuda.is_available() # cuda是否可用
torch.cuda.current_device() # 返回当前设备索引
torch.cuda.device_count() # 返回GPU的数量
torch.cuda.get_device_name(0) # 返回gpu名字,设备索