外观
pip 安装 PyTorch / transformers 慢?换源加速
搭 AI 环境时,pip install torch 经常卡在下载几百 MB 的 CUDA 版 wheel,或 transformers、vllm 装到一半超时。核心是换国内源,CUDA 版 torch 还要单独处理。
一、普通依赖:换 PyPI 国内源
transformers、accelerate、datasets 等纯 Python 包,换源即可:
bash
pip install transformers accelerate -i https://pypi.tuna.tsinghua.edu.cn/simple永久配置见 👉 pip 国内镜像详解。
二、PyTorch(CPU 版):直接走清华源
CPU 版 torch 在 PyPI 镜像上就有:
bash
pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple三、PyTorch(CUDA 版):关键在选对 whl
CUDA 版 torch 默认从 download.pytorch.org 下载(境外、慢)。有两种加速办法。
办法 A:用国内的 PyTorch wheel 镜像
一些高校镜像同步了 PyTorch 官方 wheel(如上海交大 SJTU 镜像)。以 CUDA 12.1 为例:
bash
pip install torch torchvision torchaudio \
--index-url https://mirror.sjtu.edu.cn/pytorch-wheels/cu121把
cu121换成你需要的 CUDA 版本(如cu118、cu124)。镜像地址可能调整,失效时搜索"pytorch wheel 镜像"获取当前可用地址。
办法 B:走代理装官方源
bash
pip install torch torchvision torchaudio \
--index-url https://download.pytorch.org/whl/cu121 \
--proxy http://127.0.0.1:7890四、conda 装 PyTorch
用 conda 的话,给 conda 换国内源后再装:
bash
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia五、vLLM / flash-attn 等重型包
这类包体积大、常需编译或下预编译 whl:
- 先确保 torch、CUDA 版本匹配,再装(版本不匹配会触发重新编译,极慢)。
- 优先找官方发布的预编译 wheel,避免本地从源码编译。
- 从 GitHub Release 下 whl 慢的,参考 Release 下载加速。
常见坑
| 现象 | 原因 | 解决 |
|---|---|---|
| 装了 CPU 版 torch,GPU 用不了 | 没指定 CUDA index | 用办法三的 --index-url cuXXX |
| flash-attn 编译半小时 | 没匹配预编译 whl | 找对应 torch/cuda 的预编译版 |
| 换源后还是慢 | CUDA whl 不在 PyPI 镜像 | 用 PyTorch wheel 镜像(办法 A) |
| SSL / trusted-host 警告 | 镜像证书 | 加 --trusted-host |
小结
- 纯 Python 包(transformers 等):换清华源即可。
- CUDA 版 torch:关键是用 PyTorch wheel 镜像或代理,别只换 PyPI 源。
- 版本对齐(torch ↔ CUDA ↔ flash-attn)能避免最耗时的本地编译。
本文仅供技术学习与研究,请遵守所在国家/地区法律法规。