Skip to content
官方QQ交流群
技术交流1:87208295   点此加入
技术交流2:787747122   点此加入
官网
云控制台
开放平台
关注微信公众号
代码仓库: 码云

安装 pytorch

环境前提

  • 基于 Ubuntu 22.04.2 LTS

  • 安装了 anaconda3

  • 找到合适的 pytorch 版本

sh
# 我们可以通过以下命令查看自己的cuda及cuda驱动版本

nvidia-smi
# 我们可以通过以下命令查看自己的cuda及cuda驱动版本

nvidia-smi

下载地址:
conda网站:https://conda.anaconda.org/pytorch/linux-64/
官网https://pytorch.org/
或者 https://github.com/pytorch/vision#installation

1、创建环境

添加环境,创建环境,等待下载完

sh
conda create -n pytorch python=3.9.0
conda create -n pytorch python=3.9.0

2、激活环境

  • 激活环境方式1
sh
conda activate pytorch
conda activate pytorch
  • 如果方式1不行,linux下执行这个(一般情况下,是用了exit退出了)
sh
source activate pytorch
source activate pytorch

3、conda 方式下载依赖

  • 安装conda的时候,需要配置镜像源

  • 到官网https://pytorch.org/get-started/locally/确认脚本 images

sh
# 执行下载
# conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# 将-c pytorch去掉了。主要原因是加-c pytorch后还会使用默认的conda镜像源而不是清华镜像源。
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c nvidia
conda install pytorch torchvision torchaudio cudatoolkit=11.8 -c pytorch
# 执行下载
# conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# 将-c pytorch去掉了。主要原因是加-c pytorch后还会使用默认的conda镜像源而不是清华镜像源。
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c nvidia
conda install pytorch torchvision torchaudio cudatoolkit=11.8 -c pytorch

3、pip 方式下载依赖

  • 配置镜像源
sh
# https://pypi.douban.com/simple
mkdir -p ~/.pip/
tee ~/.pip/pip.conf << EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
EOF
# https://pypi.douban.com/simple
mkdir -p ~/.pip/
tee ~/.pip/pip.conf << EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
EOF
  • 下载依赖
sh
# 镜像地址下载(推荐)
pip3 install torch torchvision torchaudio --index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 或者官方下载
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# 镜像地址下载(推荐)
pip3 install torch torchvision torchaudio --index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 或者官方下载
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

4、测试

sh
# 进入python 环境
python  
# 导入安装的 pytorch 包 ,检查cuda是否可以使用
import torch
print(torch.__version__)
print(torch.cuda.is_available())
# 进入python 环境
python  
# 导入安装的 pytorch 包 ,检查cuda是否可以使用
import torch
print(torch.__version__)
print(torch.cuda.is_available())

输出应该类似于以下内容:

2.0.0
True
2.0.0
True

如果 torch.cuda.is_available() 输出是True,表示成功;
如果输出 False,那就表示前面的驱动或者cuda的安装有问题,最可能的就是驱动,直接卸载重新安装显卡驱动即可解决问题。

5、退出

sh
# 退出python
exit();
# 退出环境
conda deactivate
# 退出python
exit();
# 退出环境
conda deactivate

参考

慢的原因 https://blog.csdn.net/damadashen/article/details/127677963

Copyright © 2017 10yun.com | 十云提供计算服务-IPV6 | ctocode组开发