net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X).shapeDive into Deep Learning · §5.1
模块与模型构造
模块树 · 子模块注册 · 容器 · 残差块 · 延迟推断形状 · 配置
动机与规模
模块树
模块抽象
当各层构成直线流水线时,顺序容器按整数索引注册每个子模块,并按插入顺序依次传递激活值:
torch.Size([2, 10])
{'0': Linear(in_features=20, out_features=256, bias=True),
'1': ReLU(),
'2': Linear(in_features=256, out_features=10, bias=True)}
继承基础模块类
torch.Size([2, 10])
__setattr__ 自动注册:赋值 self.hidden = ... 会将子模块插入模块的子模块注册表;务必调用 net(X) 以触发钩子和构建器。为什么注册至关重要
构建容器
__init__ 中注册子模块,并在 forward 中循环调用它们:torch.Size([2, 10])
普通列表陷阱
list(self.layers = [...])中时,forward 仍能运行,但 net.parameters() 为空(参数量为 0,而非 7,946):(torch.Size([2, 10]), 0)
静默训练缺陷
外层作为属性、中间层放在普通列表中:优化器会静默接受该模型。
class PartlyRegisteredMLP(nn.Module):
def __init__(self):
super().__init__()
self.first = nn.Linear(20, 256)
self.blocks = [nn.Linear(256, 256), nn.Linear(256, 256)] # Plain list
self.last = nn.Linear(256, 10)
def forward(self, X):
X = F.relu(self.first(X))
for block in self.blocks:
X = F.relu(block(X))
return self.last(X)[True, False, False, True]
self.first 正常更新(True),但优化器从未收到 self.blocks,因此它们的权重始终不变(False, False)。已注册的集合容器
非顺序连接
模块的前向传播方法可以表达任意分支与跳跃路径,例如将输入直接加到双层变换 f(\mathbf{x}) 上的残差块:
\mathbf{y} = \mathbf{x} + f(\mathbf{x})
num_hiddens。前向传播就是普通 Python 代码
跳跃连接不需要任何特殊的框架原语——前向传播方法只需返回 X + self.body(X):
torch.Size([2, 24])
前向传播执行模式
if/while 循环和 print 调试都能直接使用。for block in self.blocks:)可以干净地展开,而依赖数据的分支则需要符号控制流。延迟形状推断
训练前实例化参数形状
class TinyMLP(d2l.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(),
nn.LazyLinear(10))
def init_xavier(module):
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight)
model = TinyMLP()
model.apply_init([X], init_xavier)
model.net[0].weight.shapetorch.Size([256, 20])
Dataclass 配置
@dataclass 中,并与 build 函数配对使用。Dataclass 配置
@dataclass
class MLPConfig:
num_inputs: int = 784
num_hiddens: int = 256
num_blocks: int = 4
num_outputs: int = 10
def build(cfg: MLPConfig) -> nn.Module:
blocks = [ResidualBlock(cfg.num_hiddens) for _ in range(cfg.num_blocks)]
return nn.Sequential(nn.Linear(cfg.num_inputs, cfg.num_hiddens),
*blocks, nn.Linear(cfg.num_hiddens, cfg.num_outputs))解析计算与树遍历统计
借助 MLPConfig(num_inputs=784, num_hiddens=256, num_blocks=4, num_outputs=10) 中显式指定的宽度,我们可以在纸上算出精确的参数量,并在模块树中加以验证:
| 模块组件 | 形状公式(W + b) | 参数量 |
|---|---|---|
输入投影(0) |
784 \times 256 + 256 | 200{,}960 |
4 个残差块(1..4) |
4 \times 2 \times (256 \times 256 + 256) | 526{,}336 |
输出头(5) |
256 \times 10 + 10 | 2{,}570 |
| 整个网络 | 10 个线性层(20 个参数张量) | 729{,}866 |
num_hiddens=256, num_blocks=4: 729,866 parameters
num_hiddens=512, num_blocks=8: 4,609,546 parameters
概念自测
基于 MLPConfig 架构(d_{\text{in}}=784,K 个宽度为 d 的残差块,d_{\text{out}}=10)解答以下两个问题:
d = 256)存放在普通的 Python list 中(在不会扫描列表的框架里),同时将输入层和输出层分别赋值给 self.first 和 self.last。优化器会接收到多少个参数?在 GPU 上运行时会发生什么?num_hiddens(256 \to 512)和 num_blocks(4 \to 8)同时翻倍,会使总参数量增长超过 6\times(729{,}866 \to 4{,}609{,}546)?答案:
.to(gpu) 仅移动外层,导致首次前向传播因 CPU/GPU 设备不匹配而崩溃。核心要点
| 概念 | 机制与规则 | 实际系统影响 |
|---|---|---|
| 模块树 | 由层和块构成的递归层次结构;叶节点保存参数 | 每个参数都由从根到叶的点分路径唯一寻址 |
| 注册 | __setattr__ 与已注册的模块容器 |
未注册的普通列表会使优化器、检查点和 GPU 找不到其中的层 |
自定义 forward |
任意 Python 张量代码(例如 \mathbf{x} + f(\mathbf{x}));通过 net(X) 调用 |
编译后的步骤禁止基于张量值的条件分支 |
| 延迟初始化层 | 在首个小批量上推断 n_{\text{in}};空运行后初始化 | 便于快速原型开发;生产环境优先使用显式宽度 |
| 配置 + 构建器 | 可序列化的 @dataclass 超参数 + build(cfg) 工厂函数 |
重建模型需要权重 + 配置 + 构建器代码 |