蓝色天空.知识 · 实践 · 创造
我的收藏
PyTorch 教程目录 39章
PyTorch / LEARN BY DOING

PyTorch 安装

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

学完这一章,你能够

  • 复现 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。

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

含完整源码 · 62 行
展开查看收起
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 后数值相同。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a409.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a424.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

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

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习