修复torch.cuda.is_available()返回False问题

学习官方60分钟教程时,尝试把张量移到GPU

tensor = torch.rand(3, 4)

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to('cuda')

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

失败

Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

解决办法是按照规定的版本来配置环境。我的环境:

Win10

显卡:NVIDIA GeForce GTX 1060,驱动版本 457.30

pytorch:1.8.1+cu111

torchvision:0.9.1+cu111

torchaudio:0.8.1

CUDA:11.0

步骤:

  1. 查看显卡支持哪些CUDA版本,我的显卡驱动最高可以升到466.47,最高支持CUDA 11.3。
  2. 查看PyTorch官网,最高支持CUDA 11.1。对应显卡驱动要小于460.82,理论最高能用版本460.79。比我的版本新一个月,我就不更新驱动了。
  3. 安装pytorch。

pip安装pytorch

pip install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html

接近3GB

终于成功了

参考

安装gpu版pytorch后torch.cuda.is_available() 是 False - SegmentFault 思否
https://segmentfault.com/a/1190000023355171

Release Notes :: CUDA Toolkit Documentation
https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html

Start Locally | PyTorch
https://pytorch.org/get-started/locally/

一些错误原因

  • MacBook用不了CUDA

原因:MacBook不带显卡,CUDA 是 Nvidia专用的。

pytorch - AssertionError:Torch 未在启用 CUDA 的情况下编译 - VoidCC
https://stackoverflow.com/questions/54014220/assertionerror-torch-not-compiled-with-cuda-enabled

  • 切换到台式机做训练。台式机也用不了GPU?

查看cuda版本,

nvcc -V

检查显卡驱动版本。如果找不到命令,那就要添加环境路径。

nvidia-smi

原因:两个CUDA版本不同。

解:安装11.1版本CUDA。如果torch.cuda.is_available()返回Ture,但查看cuda版本还是10.1,那么要修改nvcc的环境变量。

  • 升级一下显卡驱动,对应的CUDA版本变成11.3了

原因:显卡驱动版本太高。

解:

重新安装历史版本的显卡驱动

NVIDIA 驱动程序下载 - 高级搜索
https://www.nvidia.cn/Download/Find.aspx?lang=cn#

  • 换回457.30,还是不行。

一查,更新完pytorch,版本变得更旧了?

>>> print(torch.__version__)
1.6.0

原因:用了这个命令安装pytorch

conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c conda-forge

解:换pip安装

pip install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html

参考

pytorch与torchvision的更新,卸载和秒安装(看这一篇就够了)_lyj223061的博客-CSDN博客_卸载torchvision
https://blog.csdn.net/lyj223061/article/details/108604500

conda和pip如何切换为清华镜像源_lyj223061的博客-CSDN博客_anaconda如何切换清华镜像源
https://blog.csdn.net/lyj223061/article/details/108639378

  • 原因:pytorch最高支持CUDA11.1

  • 原因:pytorch版本不对

查看pytorch版本

>>> print(torch.__version__)
1.8.1+cpu
原文地址:https://www.cnblogs.com/obarong/p/14833845.html