蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行分支梯度、两输入模型和 CPU 优化步

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。observe-model-training.py
observe-model-training.py108 行
"""Observe dynamic differentiation and a small CPU model without using external data."""
import json
import math
import platform

import numpy as np
import torch
from torch import nn
from torch.nn import functional as F


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


class PairRegressor(nn.Module):
    def __init__(self):
        super().__init__()
        self.projection = nn.Linear(1, 1, bias=False)
        nn.init.zeros_(self.projection.weight)

    def forward(self, baseline, change):
        return self.projection(baseline + change)


def chosen_branch(value, square):
    if square:
        return value.square()
    return 4 * value


def examples(cases):
    x = torch.tensor(3.0, requires_grad=True)
    square = chosen_branch(x, True)
    square.backward()
    grad_after_square = x.grad.item()
    x.grad = None
    linear = chosen_branch(x, False)
    linear.backward()
    record(cases, "dynamic_branch_gradients", {"value":3, "branches":["square","times_four"]},
           "Floating leaf with requires_grad; clear the gradient between forwards",
           "Execute two Python branches and backpropagate the two independently constructed graphs",
           [9.0, 6.0, 12.0, 4.0, True], [square.item(), grad_after_square, linear.item(), x.grad.item(),
                                         type(square.grad_fn) is not type(linear.grad_fn)])
    with torch.no_grad():
        untracked = x.square()
    record(cases, "requires_grad_boundary", 3.0, "Leaf x records ordinary differentiable operations",
           "Switch off recording for one block, then compute outside it",
           [True, False, True], [x.requires_grad, untracked.requires_grad, x.square().requires_grad])
    array = np.array([[2, -1], [4, 3]], dtype=np.float32)
    sample = torch.from_numpy(array)
    added = sample + torch.tensor([3.0, 1.0])
    parity = np.array_equal(added.numpy(), array + np.array([3, 1], dtype=np.float32))
    as_double = sample.to(device="cpu", dtype=torch.float64)
    record(cases, "numpy_cpu_parity", array.tolist(), "Common float32 values on CPU",
           "Compare broadcast addition and copy to CPU float64",
           [[[5.0, 0.0], [7.0, 4.0]], True, "cpu", "torch.float64"],
           [added.tolist(), bool(parity), as_double.device.type, str(as_double.dtype)])

    model = PairRegressor()
    opt = torch.optim.SGD(model.parameters(), lr=0.1)
    first = torch.tensor([[1.0], [1.0]])
    second = torch.tensor([[0.0], [1.0]])
    target = torch.tensor([[2.0], [4.0]])
    opt.zero_grad(set_to_none=True)
    guess = model(first, second)
    loss = F.mse_loss(guess, target)
    loss.backward()
    gradient = model.projection.weight.grad.item()
    opt.step()
    record(cases, "module_optimizer_step", {"features":[1, 2], "target":[2, 4]},
           "nn.Module with built-in Linear; initial weight zero and lr=0.1",
           "Call the model, backpropagate, apply SGD, and run a second prediction",
           [[[0.0], [0.0]], 10.0, -10.0, 1.0, [[1.0], [2.0]]],
           [guess.detach().tolist(), loss.item(), gradient, model.projection.weight.item(),
            model(first, second).detach().tolist()])

    errors = torch.tensor([3.0, 4.0])
    mse = F.mse_loss(errors, torch.zeros_like(errors)).item()
    norm = torch.linalg.vector_norm(errors).item()
    logits = torch.tensor([[0.0, 1.0], [2.0, -1.0]])
    labels = torch.tensor([1, 0])
    nll = F.nll_loss(F.log_softmax(logits, dim=1), labels)
    both = F.cross_entropy(logits, labels)
    record(cases, "loss_functions", {"errors":[3, 4], "logits":logits.tolist(), "labels":labels.tolist()},
           "Classification target contains class indices; compare cross entropy on logits",
           "Distinguish MSE and Euclidean norm; compare cross entropy to log softmax plus NLL",
           [12.5, 5.0, True], [mse, norm, math.isclose(nll.item(), both.item(), rel_tol=1e-6)])
    artifact = torch.export.export(model, (first, second))
    exported = artifact.module()(first, second)
    record(cases, "export_graph", [first.tolist(), second.tolist()], "Export a traceable CPU forward with concrete shapes",
           "Check that the exported module reproduces the updated eager model outputs",
           [[[1.0], [2.0]], True], [exported.detach().tolist(),
                                   any(node.op=="call_function" for node in artifact.graph.nodes)])
    record(cases, "cpu_device_selection", "cpu", "CPU package on Windows",
           "Check separate CUDA and MPS backend availability and CPU tensor placement",
           ["cpu", False, False], [model.projection.weight.device.type,
                                    torch.cuda.is_available(), torch.backends.mps.is_available()])
    return cases


if __name__ == "__main__":
    torch.set_num_threads(1)
    print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__,
                          numpy=np.__version__, system=platform.system(), cases=examples([]))))
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-intro-lab/observe-model-training.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 observe-model-training.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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