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

运行 torch.nn 2.10 组件核对与四类网络前向实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。verify-torch-nn-reference.py
verify-torch-nn-reference.py196 行
"""Verify torch.nn 2.10.0+cpu modules, functional ops, hooks, init, pruning and 4 end-to-end model demos."""
import json
import platform

import torch
from torch import nn
import torch.nn.attention
import torch.nn.functional as F
import torch.nn.utils.prune as prune


class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(10, 20)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(20, 1)

    def forward(self, x):
        return self.fc2(self.relu(self.fc1(x)))


class DemoCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2, 2),
            nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2, 2),
            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2, 2),
        )
        self.head = nn.Sequential(nn.Flatten(1), nn.Linear(64 * 4 * 4, 64), nn.ReLU(), nn.Dropout(0.5), nn.Linear(64, 10))

    def forward(self, x):
        return self.head(self.features(x))


class BiLSTMClassifier(nn.Module):
    def __init__(self, vocab_size, embed_dim, hidden_dim, num_layers, out_dim):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
        self.lstm = nn.LSTM(embed_dim, hidden_dim, num_layers=num_layers, batch_first=True,
                            bidirectional=True, dropout=0.2)
        self.dropout = nn.Dropout(0.2)
        self.fc = nn.Linear(hidden_dim * 2, out_dim)

    def forward(self, tokens, lengths):
        embedded = self.embedding(tokens)
        packed = nn.utils.rnn.pack_padded_sequence(embedded, lengths.cpu(), batch_first=True, enforce_sorted=False)
        packed_out, (hidden, _) = self.lstm(packed)
        unpacked, out_lengths = nn.utils.rnn.pad_packed_sequence(packed_out, batch_first=True)
        merged = torch.cat((hidden[-2], hidden[-1]), dim=1)
        return self.fc(self.dropout(merged)), unpacked.shape, out_lengths.tolist()


class TransformerClassifier(nn.Module):
    def __init__(self, input_dim, d_model, nhead, num_layers, dim_ff, out_dim, dropout=0.1):
        super().__init__()
        self.proj = nn.Linear(input_dim, d_model)
        self.pos = nn.Parameter(torch.randn(1, 64, d_model) * 0.1)
        layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_ff,
                                           dropout=dropout, batch_first=True)
        self.encoder = nn.TransformerEncoder(layer, num_layers=num_layers)
        self.dropout = nn.Dropout(dropout)
        self.fc = nn.Linear(d_model, out_dim)

    def forward(self, x):
        h = self.proj(x) + self.pos[:, :x.size(1), :]
        h = self.encoder(h)
        return self.fc(self.dropout(h[:, 0, :]))


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


def main():
    torch.set_num_threads(1)
    torch.manual_seed(42)
    cases = []

    hook_hits = []
    handle = nn.modules.module.register_module_forward_pre_hook(lambda m, inp: hook_hits.append(type(m).__name__))
    try:
        seq = nn.Sequential(nn.Linear(4, 6), nn.Identity())
        lazy = nn.LazyLinear(3)
        out_seq = seq(torch.randn(2, 4))
        out_lazy = lazy(torch.randn(2, 5))
    finally:
        handle.remove()
    mlist = nn.ModuleList([nn.Linear(2, 2), nn.ReLU()])
    mdict = nn.ModuleDict({"a": nn.Linear(2, 3)})
    record(cases, "containers_hooks_and_linear", {"batch": 2},
           "Sequential, ModuleList, ModuleDict, LazyLinear and global forward pre-hook (cleaned up)",
           "Check output shapes, LazyLinear materialization and global hook invocation",
           [[2, 6], [2, 3], [3, 5], True, 2, ["a"]],
           [list(out_seq.shape), list(out_lazy.shape), list(lazy.weight.shape),
            "Linear" in hook_hits, len(mlist), list(mdict.keys())])

    img = torch.randn(1, 4, 8, 8)
    ps = nn.PixelShuffle(2)(img)
    cs = nn.ChannelShuffle(2)(img)
    pad = nn.ReflectionPad1d(1)(torch.tensor([[[1.0, 2.0, 3.0]]]))
    unfold = nn.Unfold(kernel_size=2)(torch.randn(1, 1, 4, 4))
    flat = nn.Flatten(1)(img)
    unflat = nn.Unflatten(1, (4, 8, 8))(flat)
    record(cases, "conv_pool_pad_and_vision", {"img_shape": [1, 4, 8, 8]},
           "PixelShuffle, ChannelShuffle, ReflectionPad1d, Unfold, Flatten and Unflatten",
           "Verify spatial/channel reshaping and padding values",
           [[1, 1, 16, 16], [1, 4, 8, 8], [[[2.0, 1.0, 2.0, 3.0, 2.0]]], [1, 4, 9], [1, 256], [1, 4, 8, 8]],
           [list(ps.shape), list(cs.shape), pad.tolist(), list(unfold.shape), list(flat.shape), list(unflat.shape)])

    vec = torch.randn(2, 4)
    rms = nn.RMSNorm(4)(vec)
    ln = nn.LayerNorm(4)(vec)
    gn = nn.GroupNorm(2, 4)(torch.randn(2, 4, 3, 3))
    glu = nn.GLU(dim=-1)(torch.randn(2, 6))
    emb = nn.Embedding(10, 4, padding_idx=0)(torch.tensor([0, 3]))
    bag = nn.EmbeddingBag(10, 4, mode="mean")(torch.tensor([1, 2, 3]), torch.tensor([0, 2]))
    record(cases, "activations_norms_dropout_embed", {"embed_vocab": 10, "embed_dim": 4},
           "RMSNorm, LayerNorm, GroupNorm, GLU, Embedding and EmbeddingBag in PyTorch 2.10",
           "Verify output shapes and zero vector for Embedding padding_idx=0",
           [[2, 4], [2, 4], [2, 4, 3, 3], [2, 3], True, [2, 4]],
           [list(rms.shape), list(ln.shape), list(gn.shape), list(glu.shape),
            bool(torch.all(emb[0] == 0)), list(bag.shape)])

    bad_kw_rejected = False
    try:
        nn.Transformer(d_model=16, nhead=4, normalize_before=True)
    except TypeError:
        bad_kw_rejected = True
    tf_ok = nn.Transformer(d_model=16, nhead=4, num_encoder_layers=1, num_decoder_layers=1,
                           dim_feedforward=32, batch_first=True, norm_first=True)
    tf_out = tf_ok(torch.randn(2, 5, 16), torch.randn(2, 4, 16))
    qkv = torch.randn(2, 2, 4, 8)
    with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH):
        sdpa = F.scaled_dot_product_attention(qkv, qkv, qkv, is_causal=True)
    record(cases, "rnn_transformer_and_sdpa", {"d_model": 16, "nhead": 4},
           "nn.Transformer real 2.10 signature (norm_first vs nonexistent normalize_before) + SDPA",
           "Verify rejected bad kwarg, valid Transformer output and causal SDPA under MATH backend",
           [True, [2, 4, 16], [2, 2, 4, 8]],
           [bad_kw_rejected, list(tf_out.shape), list(sdpa.shape)])

    lin = nn.Linear(4, 3)
    nn.init.xavier_uniform_(lin.weight)
    gain = nn.init.calculate_gain("relu")
    vec_p = nn.utils.parameters_to_vector(lin.parameters())
    prune.random_unstructured(lin, name="weight", amount=0.25)
    cos = nn.CosineSimilarity(dim=1)(torch.tensor([[1.0, 0.0]]), torch.tensor([[1.0, 0.0]]))
    mse = nn.MSELoss()(torch.tensor([2.0, 4.0]), torch.tensor([1.0, 2.0]))
    record(cases, "losses_distances_init_utils_prune", {"prune_amount": 0.25},
           "Xavier init, calculate_gain, parameters_to_vector, random_unstructured prune and losses",
           "Check gain value, flattened parameter count, pruning state, cosine similarity and MSE",
           [True, 15, True, True, 2.5],
           [abs(gain - 2 ** 0.5) < 1e-6, len(vec_p), prune.is_pruned(lin), abs(float(cos) - 1.0) < 1e-6, float(mse)])

    s_out = SimpleNet()(torch.randn(5, 10))
    c_model = DemoCNN().eval()
    with torch.inference_mode():
        c_out = c_model(torch.randn(1, 3, 32, 32))
    record(cases, "demo_simplenet_and_cnn", {"mlp_in": [5, 10], "cnn_in": [1, 3, 32, 32]},
           "SimpleNet MLP and 3-stage Conv-BN-ReLU-Pool CNN",
           "Verify forward output tensor shapes",
           [[5, 1], [1, 10]],
           [list(s_out.shape), list(c_out.shape)])

    lstm_cls = BiLSTMClassifier(vocab_size=64, embed_dim=16, hidden_dim=24, num_layers=2, out_dim=5).eval()
    tokens = torch.tensor([[1, 5, 9, 0, 0], [2, 4, 6, 8, 3], [7, 2, 0, 0, 0]])
    lengths = torch.tensor([3, 5, 2])
    with torch.inference_mode():
        l_logits, unpacked_shape, out_lens = lstm_cls(tokens, lengths)
    record(cases, "demo_bidirectional_lstm", {"batch": 3, "lengths": [3, 5, 2]},
           "2-layer bidirectional LSTM with pack_padded_sequence and pad_packed_sequence",
           "Verify classification logits shape, unpacked sequence shape and restored lengths",
           [[3, 5], [3, 5, 48], [3, 5, 2]],
           [list(l_logits.shape), list(unpacked_shape), out_lens])

    tf_cls = TransformerClassifier(input_dim=32, d_model=32, nhead=4, num_layers=2, dim_ff=64, out_dim=10).eval()
    with torch.inference_mode():
        t_logits = tf_cls(torch.randn(4, 16, 32))
    record(cases, "demo_transformer_encoder", {"input": [4, 16, 32]},
           "TransformerEncoderClassifier with batch_first=True and first-position pooling",
           "Verify classifier output shape [4, 10]",
           [[4, 10]],
           [list(t_logits.shape)])

    print(json.dumps(dict(
        version=platform.python_version(), system=platform.system(), torch=torch.__version__,
        cases=cases,
    ), allow_nan=False))


if __name__ == "__main__":
    main()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/pytorch-torch-nn-ref-lab/verify-torch-nn-reference.py

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

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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