蓝色天空网mbsky.com · 知识 · 实践 · 创造PyTorch · 本地阅读预览
教程 / AI / 智能开发 / PyTorch

PyTorch 安装

复现 Windows 隔离环境安装,并用运行时数据确认 CPU 构建与随机张量。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先匹配平台、Python 和构建

安装前记录操作系统、架构、Python 与可选加速设备。Windows、macOS、Linux 由各发行包分别定义支持范围;旧系统、Python 3.7 与显卡算力数字不作为通用要求。本站实测 Windows x64、CPython 3.12.14 和 2.10.0 CPU 构建。下载空间、模型及依赖按实际项目估算。

准备隔离的解释器

Windows 可用系统版本工具检查版本,macOS 可用 sw_vers 与系统报告,Linux 可看 /etc/os-release。Python 用同一解释器查 --version。nvidia-smi 检查驱动可见设备,nvcc 检查本地编译工具链。各平台都可以先建独立环境。venv 在 Windows 和类 Unix 下的路径不同,亦可直接调用新环境的 Python。Miniconda 也可用于管理独立环境。

按官方版本配套安装

先在官方安装页选择平台、Python 和计算后端。仅运行本章时依赖 torch。Windows x64 下复现 CPU 实验的命令为 python -m pip install torch==2.10.0 --index-url https://download.pytorch.org/whl/cpu。需要视觉、音频库时按同一版本表选搭配。官方从 2.6 起不再发布自有 Conda 包,旧渠道的命令留作版本资料。Conda 仍可管理环境并在其中用 pip。

源码构建适合修改框架或兼顾特殊平台。固定 tag 及子模块,按该版仓库的开发说明安装构建器、编译器及依赖。早期直接运行 setup.py install 的命令有关联版本和环境要求,今天优先使用对应版本的构建文档。

识别 CUDA 与 Apple MPS 的前提

预编译 CUDA wheel 要与平台、驱动和运行时系列相容。pip 的 CUDA 索引族必须与选择的发行版本对应。需要编译 CUDA 扩展时再核对本地开发工具包。Apple Silicon 与 Intel Mac 的 wheel 架构分别核对;使用 MPS 前同时检查当前构建和设备经过实际可用性判定。

装完后执行可观察的运算

使用刚安装的解释器导入 torch,读取完整构建版本、torch.version.cuda、CUDA 与 MPS 的运行时检测,再分配 [5,3] 的均匀 float32 张量。验证范围 [0,1)、目标设备和传回 CPU 后的值。本站实际从本地 wheel 在新隔离环境安装,torch 显示 2.10.0+cpu,CUDA 与 MPS 可用性检测均为 False。

历史 CUDA 二进制选择

历史框架系列对应官方版本表应用边界
2.1.x旧 Linux/Windows 的 pip 版本组合中可见 CUDA 11.8 和 12.1。旧文偏向 12.1,须按驱动和目标构建选。
2.0.x旧版本表为该系列保留 CUDA 11.7 和 11.8 的对应构建。旧文以 11.8 举例。先核对具体补丁版本、平台与索引。
1.13.x旧版本表区分 CUDA 11.6 和 11.7。旧文以 11.7 举例。历史 CUDA 选择不直接套到 2.x。

实测版本、设备能力与均匀随机张量

python · 阅读源码
"""Verify an explicit backend with a small native tensor calculation."""
import argparse
import json
import platform
import sys

import torch


def probe(device_name):
    if device_name == "cuda" and not torch.cuda.is_available():
        raise SystemExit("This build and host cannot initialize CUDA.")
    if device_name == "mps" and not torch.backends.mps.is_available():
        raise SystemExit("This build and host cannot initialize MPS.")
    device = torch.device(device_name)
    rng = torch.Generator(device="cpu").manual_seed(105)
    values = torch.rand((5, 3), dtype=torch.float32, generator=rng)
    transferred = values.to(device)
    roundtrip = transferred.cpu()
    return dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(),
                platform_release=platform.release(), architecture=platform.machine(),
                venv=(sys.prefix != sys.base_prefix), cuda_compiled=torch.version.cuda,
                cuda_available=torch.cuda.is_available(), mps_available=torch.backends.mps.is_available(),
                backend=transferred.device.type, tensor_shape=list(transferred.shape),
                values=values.tolist(), minimum=values.min().item(), maximum=values.max().item(),
                same_values=bool(torch.equal(values, roundtrip)))


def record(name, data, action, expected, actual):
    assert expected == actual, (name, expected, actual)
    return dict(name=name, inputs=data, prerequisites="Installed matching PyTorch wheel in a separate CPython environment",
                action=action, expected=expected, actual=actual, passed=True)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--device", default="cpu", choices=("cpu","cuda","mps"))
    parser.add_argument("--assert-project-install", action="store_true")
    args = parser.parse_args()
    result = probe(args.device)
    if args.assert_project_install:
        result["cases"] = [
            record("windows_isolated_environment", "explicit current interpreter",
                   "Read system, architecture, Python version and virtual-environment identity",
                   ["Windows", "AMD64", "3.12.14", True],
                   [result["system"], result["architecture"], result["version"], result["venv"]]),
            record("cpu_install_probe", "torch==2.10.0 CPU",
                   "Import torch and inspect the build/runtime capability independently",
                   ["2.10.0+cpu", None, False, False],
                   [result["torch"], result["cuda_compiled"], result["cuda_available"], result["mps_available"]]),
            record("random_uniform_shape", {"seed":105, "shape":[5,3], "device":args.device},
                   "Allocate a uniform float32 tensor and send it through the selected backend",
                   [[5,3], args.device, True, True],
                   [result["tensor_shape"], result["backend"],
                    0 <= result["minimum"] <= result["maximum"] < 1, result["same_values"]]),
        ]
    print(json.dumps(result))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在隔离的 Windows CPU 环境读出构建版本,生成 5×3 个 [0,1) 的值,传回 CPU 后数值相同。
实测版本、设备能力与均匀随机张量

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

当前源码 SHA256:54ed6f1dd2781e8401850bde1073e9e05beabf9df4d966633cde5d59c54f49e9

下载本站示例源码

本地运行

解压后按 README 选择对应构建并运行脚本。

下载PyTorch 安装实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

ZIP SHA256:879efb8ea0c19b17825de607fb7c664e3553d509349712500e1eae342686e8da

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

能导入 torch 就能证明 CUDA 可用吗?

展开参考解答

还要检测当前构建和驱动,并在目标设备上分配张量、执行计算。

规范与官方依据