新老用户进群领券,100% 有券等你来冲!新老用户进群领券,100% 有券等你来冲! 体验按量付费开发机!立即领券
Skip to content
回到全部文章

使用国内镜像加速安装 PyTorch

在国内访问官方的 PyTorch 下载链接可能会遇到速度慢或无法访问的问题。为了解决这一问题,可以使用国内的镜像源来安装 PyTorch。本教程将介绍如何使用阿里云、上海交大和清华的镜像源。

错误的方法

部分用户参照阿里云 Pytorch Wheels 镜像站的指导,尝试将 PyTorch 安装指引中的 https://download.pytorch.org/whl 替换为 https://mirrors.aliyun.com/pytorch-wheels,但发现无法正常工作。错误信息如下:

shell
Looking in indexes: https://mirrors.aliyun.com/pytorch-wheels
ERROR: Could not find a version that satisfies the requirement torch (from versions: none)
ERROR: No matching distribution found for torch

如果遇到以上错误,下面的教程可以帮助您从其他国内镜像源安装 PyTorch。

NOTE

以下每个源均提供多种安装示例,择一即可,可按实际需求修改。

阿里云镜像

阿里云提供了 PyTorch 的镜像源,可以通过以下命令进行安装:

bash
pip3 install torch==2.4.1 torchvision torchaudio -f https://mirrors.aliyun.com/pytorch-wheels/cu121/

这里使用了 -f 选项,表示指定一个包含包文件的页面,而不是使用 --index-url,因为这些镜像不提供完整的索引服务。

如果需要信任主机,可以使用:

bash
pip3 --trusted-host mirrors.aliyun.com install torch torchvision torchaudio -f https://download.pytorch.org/whl/cu124

上海交通大学镜像

上海交大也提供了 PyTorch 镜像,可通过以下命令安装:

bash
pip3 install torch==2.4.1 torchvision torchaudio -f https://mirror.sjtu.edu.cn/pytorch-wheels/cu118

或者:

bash
pip3 install torch==2.4.1 torchvision torchaudio -f https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html

如需信任主机:

bash
pip3 --trusted-host mirror.sjtu.edu.cn install torch torchvision torchaudio -f https://download.pytorch.org/whl/cu124

清华大学镜像

清华大学提供的 PyPI 镜像可以加速安装:

bash
pip3 install torch==2.4.1 torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple

-i 选项用于指定 PyPI 的镜像源地址,这可以替代默认的官方仓库。

信任主机的安装方法:

bash
pip3 --trusted-host pypi.tuna.tsinghua.edu.cn install torch==2.4.1 torchvision torchaudio -f https://download.pytorch.org/whl/cu124

检查 PyTorch 是否支持 GPU

安装完成后,可以打开 Python interpreter,通过以下代码检查 PyTorch 是否能够使用 GPU:

python
import torch
print(torch.cuda.is_available())
print("CUDA Version:", torch.version.cuda)

如果输出为 True,则表示 GPU 可用。

通过以上步骤,您可以快速从国内镜像源下载并安装 PyTorch,以解决下载速度慢的问题。