AssertionError CUDA unavailable, invalid device 0 requested

发布时间 2023-06-05 20:32:22作者: hkwJsxl

报错信息

UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling warnings.warn('User provided device_type of \'cuda\', but CUDA is not available. Disabling')

AssertionError: CUDA unavailable, invalid device 0 requested

image-20230519112623478

报错原因

原因是运行的环境与 torch 的版本不匹配

报错解决

查看硬件信息

nvidia-smi

# 我这里的CUDA是11.1

image-20230519112358613

在Pytorch官网找到合适CUDA的版本。

也可以重新下载CUDA,再安装匹配的包(11.7版本示例:https://developer.nvidia.com/cuda-11-7-0-download-archive)

官网:https://pytorch.org/get-started/previous-versions/

在网页中搜索CUDA 11.1(我这里电脑是11.1版本),执行查找到的命令

# 先卸载之前的包
pip uninstall torch torchvision torchaudio

# 找到的命令
pip install torch==1.10.1+cu111 torchvision==0.11.2 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu111/torch_stable.html

image-20230519112902409

检测

import torch

print(torch.__version__)
print(torch.cuda.is_available())  # 返回True则表示安装成功

"""
1.10.1+cu111
True
"""

注意

一定要找到合适版本的CUDAtorch,建议最好在虚拟环境中操作,以免造成其他影响。

扩展

解决报错

D:\Virtualenvs\gesture_recognition\lib\site-packages\torch\functional.py:445: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ..\aten\src\ATen\native\TensorShape.cpp:2157.)
	return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]

点进去源码,修改

# return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]
# 改为
return _VF.meshgrid(tensors, **kwargs, indexing = "ij") # type: ignore[attr-defined]