ARTICLE · 1142684
PyTorch 安装避坑指南:CPU/GPU、镜像加速、缓存清理一篇搞定
很多人学 PyTorch,第一步卡在环境安装。
这篇文章把常用包安装、GPU/CPU 版本选择、下载体积与耗时、断点清理、国内镜像加速,一次性整理清楚。
一、常用机器学习包,一条命令搞定
最常用的基础包:
NumPy:数值计算 Pandas:数据处理 Matplotlib / Seaborn:数据可视化 Scikit-learn:传统机器学习 PyTorch:深度学习
最简 pip 安装:
python -m pip install numpy pandas matplotlib seaborn scikit-learn注意两个容易搞错的包名:
安装名是 scikit-learn,导入名是sklearnPyTorch 的安装名是 torch,不是pytorch
PyTorch 安装示例:
# CPU 版python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu# GPU 版,CUDA 12.1python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
二、GPU 版 torch 能在 CPU 上跑吗?
可以。GPU 版 PyTorch 仍然包含 CPU 支持。
默认情况下,张量和模型还是在 CPU 上。只有你显式写:
.cuda().to("cuda")device="cuda"
才会使用 GPU。
但要注意:
如果 GPU 不可用,PyTorch 不会自动回退到 CPU。
是否报错,取决于你的代码。
如果代码强制使用 GPU,而机器没有可用 GPU,可能会报:
RuntimeError: No CUDA GPUs are availableRuntimeError: CUDA error: no CUDA-capable device is detectedRuntimeError: CUDA driver version is insufficient for CUDA runtime version
如果你装的是 CPU 版 torch,却写 .cuda(),会报:
AssertionError: Torch not compiled with CUDA enabled
推荐写法:自动选择设备。
import torchdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")print("使用设备:", device)model = model.to(device)data = data.to(device)
如果加载 GPU 上保存的模型,在无 GPU 机器上最好加:
torch.load("model.pth", map_location="cpu")总结:
GPU 版 torch 可以在 CPU 上跑; 不强制用 GPU,一般不会出错; 不会自动回退 CPU,需要自己判断; 确定不用 GPU,装 CPU 版更轻量。
三、GPU 版和 CPU 版,下载多大?要多久?
文件大小
GPU 版体积大,主要因为包含:
nvidia_cudnn_cu12:约 664.8 MBnvidia_cublas_cu12:约 410.6 MBnvidia_cusolver_cu12:约 267.5 MBnvidia_cusparse_cu12:约 196.0 MB
下载时间估算
如果下载慢,可以使用国内镜像源或代理加速。
四、下载到一半,怎么删除已经下载的文件?
如果在 Jupyter 里下载中断,按下面步骤清理。
1. 先中断当前安装
点击 Jupyter 的停止/中断按钮,或菜单 Kernel -> Interrupt。最好重启 Kernel,避免残留锁。
2. 卸载可能已安装的包
%pip uninstall -y torch torchvision torchaudio没装上也没关系,会提示跳过。
3. 清理 pip 缓存
%pip cache purge如果不行,用:
!pip cache purge这会删除 pip 下载缓存,包括下载到一半的临时文件。不会影响已经安装好的其他包,只是下次安装需要重新下载。
4. 重新安装
%pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
五、CPU 版 PyTorch 用国内镜像源安装,要多久?
如果你不需要 GPU,只想装 CPU 版,用国内镜像源会快很多。
推荐命令:清华源
pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple也可以永久设置清华源:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple之后正常安装即可。
备用:阿里云源
pip install torch torchvision torchaudio -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com安装耗时
CPU 版安装包大约200 MB,国内镜像速度通常很快:
有实测显示,使用清华源安装 PyTorch 相关包,总耗时可以缩短到42 秒或2 分钟以内。
如果安装中断,可以加 --timeout 600 延长超时时间:
pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple --timeout 600注意:如果你必须严格安装CPU-only 官方版本,优先使用官方 CPU 索引:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu国内镜像适合加速一般安装,具体版本以镜像同步情况为准。
以上就是 PyTorch 安装过程中最常遇到的几个问题。