修復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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM