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

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

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。check-basic-tensors.py
check-basic-tensors.py139 行
"""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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/pytorch-basic-lab/check-basic-tensors.py

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

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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