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

PyTorch 基础

把张量、自动微分和优化器连接成一次可验证的训练,并保留设备与内存边界。

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

学完这一章,你能够

从张量接口到原生后端

torch 管理张量,nn 管理模型及参数,optim 根据梯度更新,torch.utils.data 组织输入。原生层通过 ATen 与分发机制选择设备对应的实现,Autograd 引擎负责反向。Lua Torch 时期的 TH、THNN、THC、THCUNN 是历史名称,许多实现已迁入 ATen。TorchScript/JIT 属于历史图工具,现行项目按用途评估 torch.compile 或 torch.export。扩展包在核心张量层之上提供视觉、音频等能力。

创建张量并读出形状

标量、向量、矩阵的秩分别是 0、1、2。形状给出各轴长度,dtype 决定元素编码和字节数。zeros 与 ones 初始化全部元素,randn 采样标准正态。本站固定种子并指定 dtype,实测 int8、int32、float32、float64、bool 每个元素的字节数分别为 1、4、4、8、1。

逐项相加和相乘可按广播规则扩展相容轴,矩阵转置可交换两个轴。CPU NumPy 数组通过 from_numpy 可能与张量共享存储。clone 创建独立存储并保留可微关系,detach 断开梯度关系但共享原存储,同设备同类型的 to 可返回原张量。

用链式法则检查实际梯度

eager 每次前向记录当次的可微运算,图执行则按各自的签名和追踪方式运行。输入 [1,2] 时,3×mean((x+2)²) 的值为 37.5,回传得到 [9,12],再次回传独立的 3×sum(x) 会累加成 [12,15]。把 grad 设为 None 可显式清理下一步的起点。no_grad 临时关闭大多数操作的记录,张量本身仍可保留 requires_grad。

四个框展示输入、第一次梯度、第二次新增梯度与累积结果。
本站实测 3×mean((x+2)²) 后再反传独立的线性目标得到的梯度。

建立可训练的回归模型

继承 nn.Module 或组合 Sequential 都能建立模型。前馈层适合固定特征,CNN 通常处理空间维度,RNN/LSTM 处理序列。实验用两层 Linear 与 ReLU 比较原生 MSE 和逐项平方均值。每轮先清梯度,再前向、算损失、backward、optimizer.step。Adam 维护估计状态,SGD 另有自己的配置。

用独立数据验证训练与部署

把合成数据先拆为训练 64 行、验证 16 行、测试 16 行。只用训练部分拟合标准化,再对三组数据应用相同变换。训练损失记录优化过程,验证集可用于选超参数,最终测试只作独立评估。本站运行 100 次 Adam 更新并保存每十步的观测。上线还需复核预测接口与预处理,合成结果不能表明生产误差。

向 CPU 或 GPU 移动模型和批次时检查两侧的设备。先根据 torch.cuda.is_available 探测环境,再选择设备。本站在 CPU wheel 完成实际推理,CUDA 计算和计时待匹配环境。

检查存储与梯度,并完成一次回归训练

python · 阅读源码
"""Check tensor constructors, storage, dtype, transposition and graph boundaries."""
import json
import platform

import numpy as np
import torch


def record(cases, name, data, condition, action, expected, actual):
    assert actual == expected, (name, expected, actual)
    cases.append(dict(name=name, inputs=data, prerequisites=condition, action=action,
                      expected=expected, actual=actual, passed=True))


def check():
    cases = []
    cpu = "CPU build, floating tensor unless specified"
    sample = [[2.0, 3.0], [-1.0, 4.0]]
    a = torch.tensor(sample)
    fixed = torch.Generator(device="cpu").manual_seed(121)
    noise = torch.randn((2,3), generator=fixed)
    zeros = torch.zeros((2,3),dtype=torch.int32)
    ones = torch.ones((2,3),dtype=torch.float64)
    values = [torch.tensor(f, dtype=kind) for f,kind in [(3,torch.int8),(3,torch.int32),(3,torch.float32),
                                                         (3,torch.float64),(True,torch.bool)]]
    record(cases,"tensor_constructors",{"shape":[2,3],"seed":121},cpu,
        "Allocate zeros, ones and random data; compare dtypes, byte widths and dimensions",
        [0,6.0,[2,3],[0,1,2],[1,4,4,8,1],"cpu"],
        [zeros.sum().item(),ones.sum().item(),list(noise.shape),[a[0,0].ndim,a[0].ndim,a.ndim],
         [x.element_size() for x in values],noise.device.type])
    offset = torch.tensor([1.0,-2.0])
    transpose = a.transpose(0,1)
    record(cases,"broadcast_and_transpose",sample,cpu,
        "Apply broadcast addition, elementwise multiplication and transposition",
        [[[3.0,1.0],[0.0,2.0]],[[2.0,-6.0],[-1.0,-8.0]],[[2.0,-1.0],[3.0,4.0]],True],
        [(a+offset).tolist(),(a*offset).tolist(),transpose.tolist(),bool(torch.equal(a.t(),transpose))])
    source = np.array([2.0,-1.0],dtype=np.float32)
    alias = torch.from_numpy(source)
    alias[1] = 4
    source[0] = 7
    record(cases,"numpy_shared_storage",[2.0,-1.0],"Writable C-contiguous NumPy array",
        "Mutate through each view and read the values on both sides",
        [[7.0,4.0],[7.0,4.0]],[alias.tolist(),source.tolist()])
    leaf = torch.tensor([1.0,2.0],requires_grad=True)
    copied = leaf.clone()
    detached = leaf.detach()
    same = leaf.to("cpu")
    as_double = leaf.to(dtype=torch.float64)
    with torch.no_grad():
        leaf[0] = 3
    record(cases,"clone_detach_and_to",[1.0,2.0],cpu,
        "Edit the leaf outside grad mode then check detach shares storage, clone copies and to follows options",
        [[1.0,2.0],[3.0,2.0],True,False,True,True,"torch.float64"],
        [copied.tolist(),detached.tolist(),copied.requires_grad,detached.requires_grad,same is leaf,
         as_double is not leaf,str(as_double.dtype)])
    x = torch.tensor([1.0,2.0],requires_grad=True)
    linear = (x*3).sum()
    linear.backward()
    observed = x.grad.tolist()
    x.grad = None
    loss = 3*(x+2).square().mean()
    loss.backward()
    chain = x.grad.tolist()
    (x*3).sum().backward()
    accumulated = x.grad.tolist()
    with torch.no_grad():
        detached_forward = x*2
    record(cases,"autograd_and_accumulation",[1.0,2.0],"Differentiable CPU leaf and independent forwards",
        "Observe a linear gradient, clear it, apply the chain rule and add one more gradient",
        [[3.0,3.0],37.5,[9.0,12.0],[12.0,15.0],False],
        [observed,loss.item(),chain,accumulated,detached_forward.requires_grad])
    torch.set_num_threads(1)
    torch.manual_seed(121)
    rng = torch.Generator().manual_seed(166)
    features = torch.randn((96, 2), generator=rng)
    labels = (2*features[:, :1] - features[:, 1:] + 0.5)
    training, validation, heldout = (slice(0, 64), slice(64, 80), slice(80, 96))
    center = features[training].mean(0)
    scale = features[training].std(0, unbiased=False)
    normalized = (features - center) / scale
    model = torch.nn.Sequential(torch.nn.Linear(2, 8), torch.nn.ReLU(), torch.nn.Linear(8, 1))
    objective = torch.nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.035)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)
    normalized, labels = normalized.to(device), labels.to(device)

    def evaluate(rows):
        model.eval()
        with torch.no_grad():
            value = objective(model(normalized[rows]), labels[rows])
        return value.item()

    initial = [evaluate(training), evaluate(validation)]
    model.train()
    first_prediction = model(normalized[training])
    loss = objective(first_prediction, labels[training])
    manual_loss = (first_prediction-labels[training]).square().mean()
    record(cases,"registered_model_and_mse","64 training rows, 2 features",
        "Two registered linear layers separated by ReLU",
        "Run forward, inspect parameter sizes and compare MSE with a direct mean",
        [[[8,2],[8],[1,8],[1]],[64,1],True],
        [[list(param.shape) for param in model.parameters()],list(first_prediction.shape),
         bool(torch.allclose(loss,manual_loss))])

    start_weight = model[0].weight.detach().clone()
    history = []
    for step in range(1, 101):
        optimizer.zero_grad(set_to_none=True)
        loss = objective(model(normalized[training]), labels[training])
        loss.backward()
        optimizer.step()
        if step % 10 == 0:
            history.append([step,loss.item()])
    train_loss = evaluate(training)
    val_loss = evaluate(validation)
    final_loss = evaluate(heldout)
    record(cases,"train_validate_test",{"sizes":[64,16,16],"steps":100,"lr":0.035},
        "Split before fitting standardization; no held-out feedback during training",
        "Train with Adam and assess validation and held-out errors independently",
        [True,True,True,True,list(range(10,101,10))],
        [not torch.equal(start_weight,model[0].weight),train_loss < initial[0]*0.05,
         val_loss < initial[1]*0.05,final_loss < 0.13,[step for step,_ in history]])
    cases[-1]["metrics"] = dict(first_train=initial[0],first_validation=initial[1],train=train_loss,
        validation=val_loss,heldout=final_loss,history=history)
    record(cases,"selected_device",[torch.cuda.is_available(),str(device)],
        "Installed CPU wheel; CUDA condition is false",
        "Move model and inputs and verify a fresh prediction and its device",
        ["cpu","cpu","cpu",False],
        [next(model.parameters()).device.type,normalized.device.type,
         model(normalized[heldout]).device.type,torch.cuda.is_available()])
    return cases


if __name__=="__main__":
    print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),
                          numpy=np.__version__,cases=check())))

预期结果 · 待实际运行核验
  • 同样的张量可以共享存储或独立复制。回归实验核对权重更新和分开的验证、测试误差。
检查存储与梯度,并完成一次回归训练

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

当前源码 SHA256:f7dad261eb44cb78bc2480317be0915d729df6092372447af0d702c817865caa

下载本站示例源码

本地运行

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

下载PyTorch 基础实验

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

ZIP SHA256:c2a682b00577eb756266ae53e222ae2514fb1ebb18cad83393c4aeab4df5c63e

常见错误与边界

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

练习与解答

三个分组中哪一组可以拟合标准化参数?

展开参考解答

只使用训练组,随后将同一变换应用到验证和测试组。

规范与官方依据