根本原因是pip默认超时仅15秒,而pytorch的whl包超800mb,在网络波动时极易中断;需同时设置--timeout 600、--retries 5、--trusted-host及--extra-index-url官方cuda镜像,并推荐使用带自动重试的批处理脚本。

直接用清华源安装 PyTorch 时掉包(下载中断、ConnectionResetError、ReadTimeout),根本原因是 pip 默认超时太短(15 秒),而 PyTorch 的 torch-*.whl 文件普遍 800MB+,在校园网或带宽波动时极易失败;清华源本身没问题,但 pip 不重试、不续传、不调大超时,就只能反复重下整个包。
清华源配置必须加 --trusted-host 才生效
清华源是 HTTPS,但某些旧版 pip 或代理环境会校验证书失败。只加 -i https://pypi.tuna.tsinghua.edu.cn/simple/ 不够,必须显式信任:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118/
注意最后的 --index-url 指向 PyTorch 官方 CUDA 镜像(按需替换为 cu121 或 cpu),它和清华源不冲突——pip 会先从清华源找依赖(如 numpy),再从官方镜像拉 PyTorch 主包。
必须手动加大 --timeout 和 --retries
默认 timeout 是 15 秒,对 >800MB 的 wheel 来说完全不够。实测至少设为 600(10 分钟)才稳:
使用位于 ci-tools.xrow.de 的 CI Tools 组件目录构建和维护 GitLab CI/CD 流水线,适用于创建或修复 .gitlab-ci.yml 文件,选择合适的组件。
-
--timeout 600:单次 HTTP 连接/读取最长等待时间(秒) -
--retries 5:连接失败后重试次数(不是断点续传,但能覆盖瞬时网络抖动) - 二者必须同时加,缺一不可
完整命令示例(CUDA 11.8 + Windows + Python 3.9):
pip install --timeout 600 --retries 5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118 --extra-index-url https://download.pytorch.org/whl/cu118/
写个批处理脚本自动重试,避免手敲十几次
把上面逻辑封装成 install_torch.bat,每次失败自动等 10 秒后重试,最多 3 轮:
@echo off
setlocal enabledelayedexpansion
set RETRY=0
set MAX_RETRY=3
:retry
echo [Attempt !RETRY!/!MAX_RETRY!] Installing PyTorch...
pip install --timeout 600 --retries 5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn torch==2.1.2+cu118 torchvision==0.16.2+cu118 torchaudio==2.1.2+cu118 --extra-index-url https://download.pytorch.org/whl/cu118/
if %errorlevel% == 0 (
echo ✅ Install succeeded.
exit /b 0
)
set /a RETRY+=1
if !RETRY! leq !MAX_RETRY! (
echo ⏳ Network failed, waiting 10s before retry...
timeout /t 10 >nul
goto retry
)
echo ❌ All retries failed. Check your network or try CPU version.
exit /b 1
关键点:
- 不用
pip config set全局改源——那会影响其他项目,临时命令更安全 - 脚本里写死版本号(如
torch==2.1.2+cu118)比torch更可靠,避免 pip 自行解依赖卡死 - 如果 GPU 驱动老旧,优先换
cpu版本:https://download.pytorch.org/whl/cpu/
真正卡住的往往不是源,而是 pip 对大文件下载的原始支持太弱——超时、无重试、无进度条、不续传。加参数、写脚本、锁版本,这三步做完,掉包率基本归零。清华源只是加速器,不是万能胶。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










