Pytorch:用 nn.Module 定义第一个网络 —— 把“层“组织起来

延续工程 D:\pytorchStudy\pytorch_case03_tensor\,新增 5 个模块(s16--s20)和 1 个测试文件。config.py、conftest.py、pytest.ini 完全复用。

一、核心知识点汇总

  1. nn.Module 是 PyTorch 组织计算的唯一范式

一个网络 = 一个 nn.Module子类,需要实现两件事:

关键点:PyTorch 通过 setattr 魔法在赋值时拦截。self.fc = nn.Linear(...)不是普通赋值,会自动把 fc注册成子模块,其参数进入 model.parameters()。

  1. 三种"存东西"的属性

最常见 bug:用普通 Python list 存层 → 参数完全丢失。

  1. 三层遍历 API
bash 复制代码
model.parameters()        → 所有可训练参数(扁平)
model.named_parameters()  → 带名字
model.buffers()           → 所有 buffer
model.children()          → 直接子模块
model.modules()           → 递归所有子模块(含自己)
model.state_dict()        → parameters + buffers 的扁平字典
  1. 容器三兄弟

必须用 nn.ModuleList/ nn.ModuleDict而不是普通 list / dict,否则参数不注册。

  1. train() / eval() 的作用

只有两类层会受影响:

model.train() / model.eval() 会递归设置所有子模块。训练完忘记 eval()是推理结果偏低的经典 bug。

  1. model(x) vs model.forward(x)

model(x) 走 call,会触发 forward hook / backward hook;model.forward(x) 不触发。永远用 model(x)。

  1. 保存 / 加载的标准姿势
python 复制代码
# 保存
torch.save(model.state_dict(), "m.pth")

# 加载(必须在加载端先定义完全相同的类结构)
model = MyNet()
model.load_state_dict(torch.load("m.pth", map_location=DEVICE))

不保存类结构,只保存张量------所以要保存完整模型,加载端必须能定义同名类;

保存 state_dict是社区标准,比 torch.save(model)更可移植;

训练恢复用 dict 打包:{"epoch":..., "model":..., "optimizer":...}。

  1. 和 autograd 的配合

所有 nn.Linear的 weight / bias 都是requires_grad=True的叶子张量;

推理必须 model.eval() + with torch.no_grad():;

想在推理中保留梯度调试:with torch.enable_grad():。

二、扩展后的工程结构

bash 复制代码
pytorch_case04_tensor/
├── config.py / conftest.py / pytest.ini     # 不变
├── main.py                                  # 更新:注册 5 个新 section
├── README.md                                # 追加案例4
├── src/
│   ├── __init__.py                          # 更新
│   ├── s1_create.py ~ s15_grad_modes.py     # 案例1~3(不变)
│   ├── s16_nn_module.py                     # 新增 2.16
│   ├── s17_parameters.py                    # 新增 2.17
│   ├── s18_containers.py                    # 新增 2.18
│   ├── s19_train_eval.py                    # 新增 2.19
│   └── s20_state_dict.py                    # 新增 2.20
└── tests/
    ├── test_tensor_basics.py                # 案例1
    ├── test_tensor_ops.py                   # 案例2
    ├── test_autograd.py                     # 案例3
    └── test_nn_module.py                    # 新增(案例4)

三、5 个新模块完整代码

  1. src/s16_nn_module.py

```python

"""2.16 nn.Module 入门:定义第一个网络"""

import torch

import torch.nn as nn

from config import DEVICE

from .utils import info, print_section

class TinyNet(nn.Module):

"""极简 MLP:8 -> 16 -> 4"""

def init(self, in_features: int = 8, hidden: int = 16, num_classes: int = 4):

super().init()

在 init 里"注册"层:只要赋值到 self.xxx,就自动进入 parameters()

self.fc1 = nn.Linear(in_features, hidden)

self.act = nn.ReLU()

self.fc2 = nn.Linear(hidden, num_classes)

def forward(self, x):

只定义数据怎么流;参数管理由 nn.Module 父类完成

x = self.fc1(x)

x = self.act(x)

x = self.fc2(x)

return x

def demo() -> None:

print_section("2.16 nn.Module 入门:定义第一个网络")

model = TinyNet().to(DEVICE)

print(f"\n1 实例化:\n{model}")

print(f" 模型所在设备:{next(model.parameters()).device}")

---------- (2) 前向 ----------

print("\n2 前向:直接 model(x),不要调用 model.forward(x)")

x = torch.randn(32, 8, device=DEVICE)

logits = model(x)

info("输入 x (batch=32, 特征=8)", x)

info("logits = model(x) (batch=32, 类别=4)", logits)

print("\n2.1 为什么不建议直接 model.forward(x)?")

print(" call 会触发 forward pre/post hooks,forward 不会")

print(" 写训练循环时永远用 model(x)")

---------- (3) 最小训练循环 ----------

print("\n3 最小训练循环:把案例3 的 autograd 用上")

targets = torch.randint(0, 4, (32,), device=DEVICE)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

for step in range(3):

optimizer.zero_grad() # 1) 清梯度

logits = model(x) # 2) 前向

loss = criterion(logits, targets) # 3) 损失

loss.backward() # 4) 反向

optimizer.step() # 5) 更新

print(f" step {step}: loss = {loss.item():.4f}")

---------- (4) 参数都是叶子张量 ----------

print("\n4 训练后:所有参数的 is_leaf / requires_grad / grad 形状")

for name, p in model.named_parameters():

gshape = tuple(p.grad.shape) if p.grad is not None else None

print(

f" {name:12s} is_leaf={p.is_leaf} "

f"requires_grad={p.requires_grad} grad_shape={gshape}"

)

print(" => 这就是为什么 optimizer 能只通过 model.parameters() 拿到全部权重")

```

2) `src/s17_parameters.py`

```python

"""2.17 参数、缓冲区与模型遍历"""

import torch

import torch.nn as nn

from config import DEVICE

from .utils import print_section

class WithBuffers(nn.Module):

"""演示 buffer:进 state_dict 但不需要梯度、也要跟着 .to(device) 迁移"""

def init(self):

super().init()

self.fc = nn.Linear(4, 2)

register_buffer 注册的张量:

- requires_grad=False

- 进 state_dict

- 跟着 .to(device) 迁移

典型用途:BatchNorm 的 running_mean/var、位置编码表

self.register_buffer("step", torch.tensor(0, dtype=torch.long))

self.register_buffer("running_mean", torch.zeros(4))

def forward(self, x):

self.step += 1 # 对 buffer 原地加是允许的

return self.fc(x)

def count_params(m: nn.Module, trainable_only: bool = True) -> int:

"""通用小工具:统计参数量。"""

return sum(

p.numel() for p in m.parameters() if (p.requires_grad or not trainable_only)

)

def demo() -> None:

print_section("2.17 参数、缓冲区与模型遍历")

model = WithBuffers().to(DEVICE)

---------- (1) parameters() ----------

print("\n1 parameters() / named_parameters():可训练参数")

print(f" 参数总数:{sum(p.numel() for p in model.parameters())}")

for name, p in model.named_parameters():

print(

f" {name:20s} shape={str(tuple(p.shape)):10s} "

f"dtype={p.dtype} device={p.device}"

)

---------- (2) buffers() ----------

print("\n2 buffers() / named_buffers():非参数张量")

for name, b in model.named_buffers():

val = b.tolist() if b.numel() <= 4 else tuple(b.shape)

print(f" {name:20s} value={val} device={b.device}")

---------- (3) state_dict() ----------

print("\n3 state_dict():parameters + buffers 的扁平字典")

for k, v in model.state_dict().items():

print(f" {k:25s} shape={tuple(v.shape)}")

---------- (4) 遍历子模块 ----------

print("\n4 遍历子模块")

print(" model.children() -> 直接子模块")

for i, m in enumerate(model.children()):

print(f" child{i}: {m.class.name}")

print(" model.modules() -> 递归所有子模块(含自己)")

for i, m in enumerate(model.modules()):

print(f" module{i}: {m.class.name}")

---------- (5) 参数量统计 ----------

print("\n5 常用工具:count_params()")

print(f" trainable 参数:{count_params(model)}")

print(f" 全部参数: {count_params(model, trainable_only=False)}")

print(f" buffers 数量: {sum(b.numel() for b in model.buffers())}")

```

3) `src/s18_containers.py`

```python

"""2.18 容器:Sequential / ModuleList / ModuleDict"""

import torch

import torch.nn as nn

from config import DEVICE

from .utils import info, print_section

class MLPList(nn.Module):

"""用 nn.ModuleList 存动态层数"""

def init(self, sizes):

super().init()

★ 必须放进 ModuleList!普通 list 不会注册参数

self.layers = nn.ModuleList(

nn.Linear(sizes\[i\], sizes\[i + 1\]) for i in range(len(sizes) - 1)

)

def forward(self, x):

for i, layer in enumerate(self.layers):

x = layer(x)

if i < len(self.layers) - 1:

x = torch.relu(x)

return x

class MultiHead(nn.Module):

"""用 nn.ModuleDict 存多个 head"""

def init(self, in_dim: int, hidden: int, heads: int):

super().init()

self.heads = nn.ModuleDict(

{f"head{i}": nn.Linear(in_dim, hidden) for i in range(heads)}

)

def forward(self, x):

return torch.cat(h(x) for h in self.heads.values(), dim=-1)

def demo() -> None:

print_section("2.18 容器:Sequential / ModuleList / ModuleDict")

---------- (1) Sequential ----------

print("\n1 nn.Sequential:线性流水线(最常用)")

seq = nn.Sequential(

nn.Linear(8, 16),

nn.ReLU(),

nn.Linear(16, 4),

).to(DEVICE)

print(f" 模型结构:\n{seq}")

x = torch.randn(3, 8, device=DEVICE)

info("输入 x (3,8)", x)

info("输出 (3,4)", seq(x))

print("\n1.1 两种访问方式")

print(f" seq0 -> {seq0.class.name}")

print(f" seq2 -> {seq2.class.name}")

print(f" 遍历:{m.__class__.__name__ for m in seq}")

---------- (2) ModuleList ----------

print("\n2 nn.ModuleList:像 list 一样存模块,但参数会被注册")

mlp = MLPList(8, 16, 16, 4).to(DEVICE)

print(f" MLPList(8,16,16,4) 参数总数 = "

f"{sum(p.numel() for p in mlp.parameters())}")

info("输出 (3,4)", mlp(x))

print("\n2.1 经典 bug 演示:普通 list 存层,参数丢失")

class BadMLP(nn.Module):

def init(self):

super().init()

self.layers = nn.Linear(8, 16), nn.Linear(16, 4) # ❌ 普通 list

def forward(self, x):

for layer in self.layers:

x = layer(x)

return x

bad = BadMLP()

print(f" BadMLP.parameters() 数量 = {len(list(bad.parameters()))} ← 是 0!")

print(" => 训练这种模型会以为 '没有参数需要优化',完全跑不动")

---------- (3) ModuleDict ----------

print("\n3 nn.ModuleDict:按名字索引子模块")

mh = MultiHead(in_dim=8, hidden=4, heads=3).to(DEVICE)

info("MultiHead 输出 (3, 12)", mh(x))

print(f" keys = {list(mh.heads.keys())}")

print(f" mh.heads'head1' -> {mh.heads'head1'.class.name}")

---------- (4) 嵌套网络 ----------

print("\n4 嵌套:一个 Module 可以是另一个 Module 的属性")

class TwoStage(nn.Module):

def init(self):

super().init()

self.backbone = nn.Sequential(nn.Linear(8, 32), nn.ReLU())

self.head = MLPList(32, 16, 4)

def forward(self, x):

return self.head(self.backbone(x))

ts = TwoStage().to(DEVICE)

print(f" TwoStage 参数总数 = {sum(p.numel() for p in ts.parameters())}")

info("TwoStage 输出 (3,4)", ts(x))

```

4) `src/s19_train_eval.py`

```python

"""2.19 train() / eval():BatchNorm 与 Dropout 的行为切换"""

import torch

import torch.nn as nn

from config import DEVICE

from .utils import print_section

class MiniNet(nn.Module):

"""用于演示 train/eval 状态递归传播"""

def init(self):

super().init()

self.fc1 = nn.Linear(8, 16)

self.bn = nn.BatchNorm1d(16)

self.drop = nn.Dropout(p=0.1)

self.fc2 = nn.Linear(16, 4)

def forward(self, x):

x = self.fc1(x)

x = self.bn(x)

x = torch.relu(x)

x = self.drop(x)

return self.fc2(x)

def demo() -> None:

print_section("2.19 train() / eval():BatchNorm 与 Dropout")

---------- (1) Dropout ----------

print("\n1 Dropout:训练时随机置零,eval 时恒等")

drop = nn.Dropout(p=0.5)

x = torch.ones(6)

drop.train()

print(f" train 模式:{drop(x).tolist()}")

drop.eval()

print(f" eval 模式:{drop(x).tolist()}")

print(" => eval 下 Dropout 是恒等映射;训练完必须 model.eval()")

---------- (2) BatchNorm ----------

print("\n2 BatchNorm1d:训练时用 batch 统计量,eval 时用 running 统计量")

bn = nn.BatchNorm1d(4)

x = torch.tensor(

\[1.0, 2.0, 3.0, 4.0,

5.0, 6.0, 7.0, 8.0\]

)

print(f" running_mean 初始值:{bn.running_mean.tolist()}")

bn.train()

y_train = bn(x)

print(f"\n train 下输出:\n{y_train}")

print(f" train 后 running_mean = {bn.running_mean.tolist()}")

print(f" train 后 running_var = {bn.running_var.tolist()}")

bn.eval()

before = bn.running_mean.clone()

_ = bn(x)

print(f"\n eval 后 running_mean 是否变化:{not torch.allclose(before, bn.running_mean)}")

print(" => eval 下不再更新 running 统计量")

---------- (3) 状态递归传播 ----------

print("\n3 model.train() / eval() 会递归设置所有子模块")

model = MiniNet().to(DEVICE)

model.train()

print(f" model.train() 后:model.training = {model.training}")

print(f" 所有子模块都在训练态:{all(m.training for m in model.modules())}")

model.eval()

print(f" model.eval() 后:model.training = {model.training}")

print(f" 所有子模块都在评估态:{all(not m.training for m in model.modules())}")

---------- (4) 正确训练循环骨架 ----------

print("\n4 标准训练 / 评估流程(伪代码)")

print("""

训练

model.train()

for x, y in train_loader:

optimizer.zero_grad()

loss = criterion(model(x), y)

loss.backward()

optimizer.step()

评估

model.eval()

with torch.no_grad():

for x, y in val_loader:

pred = model(x)

""".rstrip())

```

5) `src/s20_state_dict.py`

```python

"""2.20 保存 / 加载:state_dict、设备迁移、与 autograd 配合"""

import tempfile

from pathlib import Path

import torch

import torch.nn as nn

from config import DEVICE

from .utils import print_section

class DemoNet(nn.Module):

def init(self, in_dim: int = 8, num_classes: int = 4):

super().init()

self.fc1 = nn.Linear(in_dim, 16)

self.fc2 = nn.Linear(16, num_classes)

def forward(self, x):

return self.fc2(torch.relu(self.fc1(x)))

def demo() -> None:

print_section("2.20 保存 / 加载:state_dict、设备迁移、autograd 配合")

model = DemoNet().to(DEVICE)

---------- (1) 保存 ----------

print("\n1 保存:torch.save(model.state_dict(), path)")

print(" => 只保存张量字典,不保存类结构,加载端必须自己定义模型类")

save_path = Path(tempfile.gettempdir()) / "case4_demo_net.pth"

torch.save(model.state_dict(), save_path)

print(f" 已保存到:{save_path} ({save_path.stat().st_size / 1024:.1f} KB)")

---------- (2) 加载 ----------

print("\n2 加载:先创建同结构模型,再 load_state_dict")

model2 = DemoNet().to(DEVICE)

state = torch.load(save_path, map_location=DEVICE)

model2.load_state_dict(state)

same = torch.allclose(

model.fc1.weight.detach(), model2.fc1.weight.detach()

)

print(f" 加载后 fc1.weight 与原始一致:{same}")

---------- (3) map_location ----------

print("\n3 map_location:跨设备加载")

print(" torch.load(path, map_location='cpu') -> 强制 CPU")

print(" torch.load(path, map_location=DEVICE) -> 跟随当前 DEVICE")

print(" => 在 GPU 保存、在 CPU 加载必须用 map_location,否则报 CUDA 错误")

---------- (4) 完整 checkpoint ----------

print("\n4 完整训练恢复:同时保存 optimizer.state_dict()")

optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

ckpt_path = Path(tempfile.gettempdir()) / "case4_ckpt.pth"

torch.save(

{

"epoch": 5,

"model": model.state_dict(),

"optimizer": optimizer.state_dict(),

},

ckpt_path,

)

print(f" 已保存 checkpoint:{ckpt_path}")

ckpt = torch.load(ckpt_path, map_location=DEVICE)

print(f" ckpt keys = {list(ckpt.keys())}")

print(f" epoch = {ckpt'epoch'}")

model3 = DemoNet().to(DEVICE)

optimizer3 = torch.optim.Adam(model3.parameters(), lr=1e-3)

model3.load_state_dict(ckpt"model")

optimizer3.load_state_dict(ckpt"optimizer")

print(" 加载完成(模型 + 优化器)")

---------- (5) 与 autograd 的配合 ----------

print("\n5 和 autograd 配合")

print(" (a) 所有参数都是叶子、requires_grad=True")

for name, p in model.named_parameters():

assert p.requires_grad and p.is_leaf

print(" ✓ 全部参数 is_leaf=True, requires_grad=True")

print(" (b) 推理:model.eval() + torch.no_grad()")

model.eval()

with torch.no_grad():

out = model(torch.randn(4, 8, device=DEVICE))

print(f" out.requires_grad = {out.requires_grad}")

print(" (c) 想在 no_grad 里临时恢复追踪:torch.enable_grad()")

with torch.no_grad():

with torch.enable_grad():

out = model(torch.randn(4, 8, device=DEVICE))

print(f" out.requires_grad = {out.requires_grad}")

清理临时文件

for p in (save_path, ckpt_path):

try:

p.unlink()

except FileNotFoundError:

pass

```


四、更新 `src/init.py`

```python

"""案例1 + 2 + 3 + 4 的全部演示模块。"""

from . import (

s1_create, s2_attrs, s3_dtype, s4_device, s5_numpy,

s6_elementwise, s7_matmul, s8_broadcast, s9_inplace,

s10_autograd_inplace,

s11_requires_grad, s12_compute_graph, s13_backward,

s14_nonscalar_backward, s15_grad_modes,

s16_nn_module, s17_parameters, s18_containers,

s19_train_eval, s20_state_dict,

)

all = [

"s1_create", "s2_attrs", "s3_dtype", "s4_device", "s5_numpy",

"s6_elementwise", "s7_matmul", "s8_broadcast", "s9_inplace",

"s10_autograd_inplace",

"s11_requires_grad", "s12_compute_graph", "s13_backward",

"s14_nonscalar_backward", "s15_grad_modes",

"s16_nn_module", "s17_parameters", "s18_containers",

"s19_train_eval", "s20_state_dict",

]

```


五、更新 `main.py`(完整覆盖)

```python

"""案例1 + 2 + 3 + 4 入口。"""

import argparse

import sys

from config import describe_env, set_seed

from src import (

s1_create, s2_attrs, s3_dtype, s4_device, s5_numpy,

s6_elementwise, s7_matmul, s8_broadcast, s9_inplace,

s10_autograd_inplace,

s11_requires_grad, s12_compute_graph, s13_backward,

s14_nonscalar_backward, s15_grad_modes,

s16_nn_module, s17_parameters, s18_containers,

s19_train_eval, s20_state_dict,

)

SECTIONS = {

案例1

"create": ("2.1 张量的创建方式", s1_create.demo),

"attrs": ("2.2 张量属性、索引与形状操作", s2_attrs.demo),

"dtype": ("2.3 dtype 与类型转换", s3_dtype.demo),

"device": ("2.4 设备(device)与 CPU/GPU 迁移", s4_device.demo),

"numpy": ("2.5 张量与 NumPy 互转", s5_numpy.demo),

案例2

"elem": ("2.6 逐元素运算", s6_elementwise.demo),

"matmul": ("2.7 矩阵乘法", s7_matmul.demo),

"broadcast": ("2.8 广播机制", s8_broadcast.demo),

"inplace": ("2.9 原地操作 vs 普通操作", s9_inplace.demo),

"autograd": ("2.10 自动求导 + 原地操作", s10_autograd_inplace.demo),

案例3

"reqgrad": ("2.11 requires_grad:开启自动追踪", s11_requires_grad.demo),

"graph": ("2.12 动态计算图:grad_fn 链", s12_compute_graph.demo),

"backward": ("2.13 backward:累积/retain/高阶导", s13_backward.demo),

"nonscalar": ("2.14 非标量 backward:J^T·v", s14_nonscalar_backward.demo),

"gradmodes": ("2.15 detach/no_grad/inference_mode", s15_grad_modes.demo),

案例4

"nn": ("2.16 nn.Module 入门", s16_nn_module.demo),

"params": ("2.17 参数、缓冲区与模型遍历", s17_parameters.demo),

"containers":("2.18 Sequential/ModuleList/ModuleDict", s18_containers.demo),

"traineval": ("2.19 train() / eval() 切换", s19_train_eval.demo),

"statedict": ("2.20 state_dict 保存 / 加载", s20_state_dict.demo),

}

def main() -> int:

parser = argparse.ArgumentParser(description="PyTorch 微案例工程")

parser.add_argument(

"--section",

choices="all", \*SECTIONS.keys(),

default="all",

help="选择要运行的章节,默认 all",

)

parser.add_argument("--seed", type=int, default=42, help="随机种子")

args = parser.parse_args()

set_seed(args.seed)

print(f"环境:{describe_env()}")

print(f"随机种子:{args.seed}")

keys = list(SECTIONS.keys()) if args.section == "all" else args.section

for k in keys:

_, fn = SECTIONSk

fn()

print("\n" + "=" * 72)

print("全部演示结束 ✅")

print("=" * 72)

return 0

if name == "main":

sys.exit(main())

```


六、测试文件 `tests/test_nn_module.py`

```python

"""案例4 回归测试:nn.Module / 参数管理 / 容器 / train-eval / state_dict"""

import tempfile

from pathlib import Path

import pytest

import torch

import torch.nn as nn

from config import DEVICE

from src.s16_nn_module import TinyNet

from src.s17_parameters import WithBuffers, count_params

from src.s18_containers import MLPList, MultiHead

from src.s19_train_eval import MiniNet

from src.s20_state_dict import DemoNet

============ 2.16 nn.Module ============

def test_tiny_net_forward_shape():

model = TinyNet().to(DEVICE)

x = torch.randn(32, 8, device=DEVICE)

y = model(x)

assert tuple(y.shape) == (32, 4)

assert y.device.type == DEVICE.type

def test_tiny_net_parameters_are_leaves():

model = TinyNet()

for p in model.parameters():

assert p.is_leaf

assert p.requires_grad

def test_training_loop_decreases_loss():

torch.manual_seed(0)

model = TinyNet().to(DEVICE)

x = torch.randn(64, 8, device=DEVICE)

y = torch.randint(0, 4, (64,), device=DEVICE)

crit = nn.CrossEntropyLoss()

opt = torch.optim.SGD(model.parameters(), lr=0.1)

losses = \[\]

for _ in range(20):

opt.zero_grad()

loss = crit(model(x), y)

loss.backward()

opt.step()

losses.append(loss.item())

assert losses-1 < losses0

def test_call_triggers_hooks_but_forward_does_not():

model = TinyNet()

counter = {"n": 0}

def hook(module, inputs, output):

counter"n" += 1

model.register_forward_hook(hook)

x = torch.randn(2, 8)

model(x) # 走 call,触发 hook

model.forward(x) # 直接调 forward,不触发

assert counter"n" == 1

============ 2.17 参数 / 缓冲区 ============

def test_named_parameters_keys():

names = n for n, _ in TinyNet().named_parameters()

for expect in ("fc1.weight", "fc1.bias", "fc2.weight", "fc2.bias"):

assert expect in names

def test_buffers_not_in_parameters():

m = WithBuffers()

param_names = {n for n, _ in m.named_parameters()}

buffer_names = {n for n, _ in m.named_buffers()}

assert "running_mean" in buffer_names

assert "running_mean" not in param_names

assert "step" in buffer_names

def test_state_dict_contains_params_and_buffers():

sd = WithBuffers().state_dict()

for k in ("fc.weight", "fc.bias", "running_mean", "step"):

assert k in sd

def test_count_params():

TinyNet(8 -> 16 -> 4):fc1 = 8*16 + 16 = 144,fc2 = 16*4 + 4 = 68,总 212

assert count_params(TinyNet()) == 8 * 16 + 16 + 16 * 4 + 4

def test_buffers_move_with_model_to():

for b in WithBuffers().to(DEVICE).buffers():

assert b.device.type == DEVICE.type

============ 2.18 容器 ============

def test_sequential_forward():

seq = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 4)).to(DEVICE)

out = seq(torch.randn(3, 8, device=DEVICE))

assert tuple(out.shape) == (3, 4)

def test_modulelist_registers_params():

assert len(list(MLPList(8, 16, 4).parameters())) > 0

def test_plain_list_does_not_register_params():

class Bad(nn.Module):

def init(self):

super().init()

self.layers = nn.Linear(8, 4) # ❌ 普通 list

def forward(self, x):

return self.layers0(x)

assert len(list(Bad().parameters())) == 0

def test_moduledict_forward():

m = MultiHead(in_dim=8, hidden=4, heads=3).to(DEVICE)

out = m(torch.randn(2, 8, device=DEVICE))

3 个 head 输出 cat 在一起 → (2, 12)

assert tuple(out.shape) == (2, 12)

============ 2.19 train / eval ============

def test_dropout_in_eval_is_identity():

drop = nn.Dropout(p=0.9)

x = torch.ones(100)

drop.eval()

assert torch.equal(drop(x), x)

def test_dropout_in_train_zeros_some():

torch.manual_seed(0)

drop = nn.Dropout(p=0.5)

x = torch.ones(1000)

drop.train()

y = drop(x)

zeros = (y == 0).sum().item()

1000 元素 p=0.5,大约 500 个 0,放宽到 300, 700

assert 300 < zeros < 700

def test_batchnorm_running_stats_update_in_train():

bn = nn.BatchNorm1d(4)

x = torch.randn(8, 4)

before = bn.running_mean.clone()

bn.train()

_ = bn(x)

assert not torch.allclose(bn.running_mean, before)

def test_batchnorm_running_stats_frozen_in_eval():

bn = nn.BatchNorm1d(4)

x = torch.randn(8, 4)

bn.eval()

before = bn.running_mean.clone()

_ = bn(x)

assert torch.allclose(bn.running_mean, before)

def test_model_train_eval_toggle_propagates():

m = MiniNet()

m.train()

assert m.training

assert all(sub.training for sub in m.modules())

m.eval()

assert not m.training

assert all(not sub.training for sub in m.modules())

============ 2.20 state_dict ============

def test_state_dict_roundtrip():

m1 = DemoNet().to(DEVICE)

m2 = DemoNet().to(DEVICE)

with tempfile.TemporaryDirectory() as d:

path = Path(d) / "m.pth"

torch.save(m1.state_dict(), path)

m2.load_state_dict(torch.load(path, map_location=DEVICE))

for k, v in m1.state_dict().items():

assert torch.allclose(v, m2.state_dict()k)

def test_checkpoint_with_optimizer():

m = DemoNet().to(DEVICE)

opt = torch.optim.Adam(m.parameters(), lr=1e-3)

with tempfile.TemporaryDirectory() as d:

path = Path(d) / "ckpt.pth"

torch.save(

{"epoch": 3, "model": m.state_dict(), "optimizer": opt.state_dict()},

path,

)

ckpt = torch.load(path, map_location=DEVICE)

assert ckpt"epoch" == 3

assert "model" in ckpt and "optimizer" in ckpt

def test_eval_plus_no_grad_does_not_track():

m = DemoNet().to(DEVICE)

m.eval()

with torch.no_grad():

out = m(torch.randn(2, 8, device=DEVICE))

assert out.requires_grad is False

def test_enable_grad_inside_no_grad():

m = DemoNet().to(DEVICE)

with torch.no_grad():

with torch.enable_grad():

out = m(torch.randn(2, 8, device=DEVICE))

assert out.requires_grad is True

```


七、README 追加段落

在 `README.md` 末尾追加:

```markdown


案例4:nn.Module 定义第一个网络

运行

```bash

python main.py --section nn # 2.16 Module 入门

python main.py --section params # 2.17 参数 / buffer 遍历

python main.py --section containers # 2.18 Sequential/ModuleList/ModuleDict

python main.py --section traineval # 2.19 train() / eval()

python main.py --section statedict # 2.20 state_dict

pytest tests/test_nn_module.py -v

pytest tests/ -v # 全部 4 个案例

```

知识地图

必须记住的 7 条

  1. 层写在 __init__里用 self.xxx = nn.Linear(...),数据流写在 forward里------这是 nn.Module的全部。

  2. model(x),不要 model.forward(x)------前者会触发 hook,后者不会。

  3. 存层必须用 **`nn.ModuleList` / `nn.ModuleDict`**;普通 list / dict 不注册参数。

  4. register_buffer注册的 buffer:**不需要梯度**,**进 state_dict**,**跟着 `.to(device)` 迁移**------`BatchNorm` 的 `running_mean` 就是它。

  5. 训练前model.train(),推理前 model.eval():影响 Dropout 和 BatchNorm。

  6. 推理必须 model.eval() + torch.no_grad()(或用 `torch.inference_mode()`)。

  7. 保存用torch.save(model.state_dict(), path),加载端必须先创建同结构模型再 load_state_dict;跨设备用map_location。

典型报错对照

八、运行方式

```powershell

cd D:\pytorchStudy\pytorch_case03_tensor

单独跑案例4 各节

python main.py --section nn

python main.py --section params

python main.py --section containers

python main.py --section traineval

python main.py --section statedict

案例4 测试

pytest tests/test_nn_module.py -v

全部 20 节 + 全部测试

python main.py

pytest tests/ -v

```

**预期测试结果:**

```text

configfile: pytest.ini

collected 70 items

tests/test_autograd.py ..................... (24 passed)

tests/test_nn_module.py .................... (22 passed)

tests/test_tensor_basics.py ................ (9 passed)

tests/test_tensor_ops.py ................... (15 passed)

============================== 70 passed in ~5s ==============================

```


九、预期输出节选

```text

========================================================================

2.16 nn.Module 入门:定义第一个网络

========================================================================

1 实例化:

TinyNet(

(fc1): Linear(in_features=8, out_features=16, bias=True)

(act): ReLU()

(fc2): Linear(in_features=16, out_features=4, bias=True)

)

模型所在设备:cuda:0

3 最小训练循环:把案例3 的 autograd 用上

step 0: loss = 1.4012

step 1: loss = 1.3321

step 2: loss = 1.2784

4 训练后:所有参数的 is_leaf / requires_grad / grad 形状

fc1.weight is_leaf=True requires_grad=True grad_shape=(16, 8)

fc1.bias is_leaf=True requires_grad=True grad_shape=(16,)

fc2.weight is_leaf=True requires_grad=True grad_shape=(4, 16)

fc2.bias is_leaf=True requires_grad=True grad_shape=(4,)

========================================================================

2.18 容器:Sequential / ModuleList / ModuleDict

========================================================================

2.1 经典 bug 演示:普通 list 存层,参数丢失

BadMLP.parameters() 数量 = 0 ← 是 0!

=> 训练这种模型会以为 '没有参数需要优化',完全跑不动

========================================================================

2.19 train() / eval():BatchNorm 与 Dropout

========================================================================

1 Dropout:训练时随机置零,eval 时恒等

train 模式:2.0, 0.0, 2.0, 2.0, 0.0, 2.0

eval 模式:1.0, 1.0, 1.0, 1.0, 1.0, 1.0

2 BatchNorm1d:训练时用 batch 统计量,eval 时用 running 统计量

train 下输出:

tensor(\[-1.0000, -1.0000, -1.0000, -1.0000,

1.0000, 1.0000, 1.0000, 1.0000], grad_fn=<NativeBatchNormBackward0>)

train 后 running_mean = 0.3, 0.3, 0.3, 0.3

train 后 running_var = 1.7, 1.7, 1.7, 1.7

========================================================================

2.20 保存 / 加载:state_dict、设备迁移、autograd 配合

========================================================================

1 保存:torch.save(model.state_dict(), path)

已保存到:C:\Users\...\Temp\case4_demo_net.pth (4.0 KB)

2 加载:先创建同结构模型,再 load_state_dict

加载后 fc1.weight 与原始一致:True

```

--

相关推荐
zhanghongyi_cpp8 分钟前
第5章 学习自测
python·学习
数字供应链安全产品选型18 分钟前
从 Skill 安全准入到 Agent 运行时防护,问境 AgentAI 打通企业智能体规模化落地的安全关卡
人工智能·安全
掘金安东尼33 分钟前
任务成功率从 60% 做到 99%:Strands Evals 的运行框架优化
人工智能
Cosolar41 分钟前
当 Harness 标准化后,工程师还剩什么?
人工智能·后端·agent
Wellijohn1 小时前
大模型推理为什么这么贵?从 KV Cache 到投机解码的一线优化实录
人工智能·性能优化·llm
打工仔折腾 AI1 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
无奈何杨1 小时前
我把一张健身 Excel 表,做成了一个能聊天的健身助手
人工智能
Wellijohn1 小时前
从 RAG 到 Agent:大模型应用为什么「演示很惊艳,上线就翻车」
人工智能·llm·agent
IvanCodes2 小时前
LangChain(15):LangSmith 应用评估与回归测试
python·langchain·agent
土星云SaturnCloud2 小时前
DirectMHP 边缘部署实战(下):土星云SE110S 三机型 28.98ms 实测——模型编译、精度验证与七条工程化经验
人工智能·边缘计算·lightstereo