在已安装cuda的前提下,如何在Anaconda指定环境中安装pytorch cuda
前提
- 电脑支持cuda并且之前已经安装过cuda以及cudnn等
- 电脑已经安装并配置好anaconda环境
- 已创建好anaconda指定虚拟环境
1. 查找PC已安装的cuda版本
打开终端cmd,输入指令:nvcc -V
C:\Users\emos>nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2022 NVIDIA Corporation
Built on Tue_Mar__8_18:36:24_Pacific_Standard_Time_2022
Cuda compilation tools, release 11.6, V11.6.124
Build cuda_11.6.r11.6/compiler.31057947_0
由最后一行可知,电脑中安装的cuda版本为cuda11.6
2. 在PyTorch官网查找指令
进入PyTorch官网,如图
图中,只有CUDA 11.7及以上,我们可以从 Previous PyTorch Version 中查找对应版本。但实测,可以直接复制 Run this Command
并将其中的cu117改为cu116即可,即:
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu116
3. 在Anaconda指定虚拟环境中运行指令
假设我们已经创建的虚拟环境名称为 cudatest
- 首先打开Anaconda Prompt
- 输入指令
conda activate cudatest
以激活环境 - 进入该虚拟环境后,输入第2个步骤中所查找的cuda下载指令,即
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu116
- 等待安装完成即可
4. 验证 pytorch cuda可用
在Anaconda Prompt激活虚拟环境后,输入 python
进入python控制台。
(cudatest) C:\Users\Users_Name>python
Python 3.10.9 | packaged by Anaconda, Inc. | (main, Mar 8 2023, 10:42:25) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
True
>>>
显示True
即代表cuda可用