下面按在 Ubuntu 上配置 PyTorch的常见场景,给你一份清晰、可操作的指南(以 Ubuntu 20.04 / 22.04 为例,其他版本类似)。
sudo apt update
sudo apt upgrade -y
Ubuntu 一般自带 Python3:
python3 --version
pip3 --version
如未安装:
sudo apt install python3 python3-pip python3-venv -y
避免污染系统 Python:
python3 -m venv pytorch_env
source pytorch_env/bin/activate
激活后命令行前面会出现 (pytorch_env)
pip install torch torchvision torchaudio
nvidia-smi
能看到 CUDA Version 说明驱动正常。
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
官方选择地址(强烈推荐): https://pytorch.org/get-started/locally/
python
import torch
print(torch.__version__)
print(torch.cuda.is_available()) # GPU 应为 True
使用国内镜像:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install jupyter
jupyter notebook
import torch
x = torch.rand(3, 3)
print(x)
print("CUDA:", torch.cuda.is_available())
如果你愿意,可以告诉我:
我可以给你完全定制化的安装命令。