1. nn.Module的设计哲学
torch.nn.Module是PyTorch中所有神经网络层的基类。无论是最简单的线性层,还是包含数十亿参数的Transformer,都继承自这个类。理解nn.Module的设计哲学,是构建任何PyTorch模型的前提。
1.1 为什么需要nn.Module
在纯PyTorch张量操作中,我们需要手动管理权重、偏置等参数。当网络变深、参数变多时,手动管理变得不可行。nn.Module通过自动注册机制解决了这个问题——你只需在__init__中定义子模块和参数,PyTorch就会自动跟踪它们。
Python
import torch
import torch.nn as nn
# 不使用nn.Module:手动管理参数
def manual_linear(x, weight, bias):
return x @ weight.T + bias
# 需要手动创建和跟踪每个参数
w1 = torch.randn(64, 128, requires_grad=True)
b1 = torch.randn(64, requires_grad=True)
w2 = torch.randn(10, 64, requires_grad=True)
b2 = torch.randn(10, requires_grad=True)
x = torch.randn(1, 128)
h = torch.relu(manual_linear(x, w1, b1))
out = manual_linear(h, w2, b2)
print(f"手动实现输出形状: {out.shape}")
# 使用nn.Module:自动管理参数
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(128, 64) # 自动注册参数
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
h = torch.relu(self.fc1(x))
return self.fc2(h)
model = SimpleNet()
out = model(x) # 自动调用forward
print(f"nn.Module输出形状: {out.shape}")
print(f"自动跟踪的参数数量: {sum(p.numel() for p in model.parameters())}")
1.2 nn.Module的核心机制
| 机制 | 说明 | 相关方法 |
| 自动注册 | __init__中赋值的nn.Module/Parameter自动被跟踪 | __setattr__ |
| forward调用 | model(x)自动调用model.forward(x) | __call__ |
| 参数遍历 | 递归遍历所有子模块的参数 | parameters(), named_parameters() |
| 模块遍历 | 递归遍历所有子模块 | modules(), children() |
| 状态管理 | 保存/加载模型参数 | state_dict(), load_state_dict() |
| 设备迁移 | 将模型移到GPU或其他设备 | to(), cuda(), cpu() |
| 模式切换 | 训练/评估模式 | train(), eval() |
2. 构建自定义模型
2.1 基本模式:__init__ + forward
Python
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.1):
super().__init__()
# 在__init__中定义所有层和参数
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, output_dim)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(hidden_dim)
def forward(self, x):
# 在forward中定义计算流程
x = self.fc1(x)
x = torch.relu(x)
x = self.dropout(x)
x = self.fc2(x)
x = self.layer_norm(x) # 残差连接前做LayerNorm
x = torch.relu(x)
x = self.dropout(x)
x = self.fc3(x)
return x
# 创建模型
model = MLP(input_dim=768, hidden_dim=512, output_dim=10)
print(model)
2.2 残差连接(Residual Connection)
Python
class ResidualBlock(nn.Module):
def __init__(self, dim, dropout=0.1):
super().__init__()
self.fc1 = nn.Linear(dim, dim)
self.fc2 = nn.Linear(dim, dim)
self.norm1 = nn.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# Pre-LN残差连接(Transformer风格)
residual = x
x = self.norm1(x)
x = torch.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return residual + x # 残差连接
# 堆叠多个残差块
class DeepResNet(nn.Module):
def __init__(self, dim, num_blocks=6):
super().__init__()
self.blocks = nn.ModuleList([
ResidualBlock(dim) for _ in range(num_blocks)
])
self.final_norm = nn.LayerNorm(dim)
def forward(self, x):
for block in self.blocks:
x = block(x)
return self.final_norm(x)
model = DeepResNet(dim=512, num_blocks=6)
x = torch.randn(4, 512)
print(f"输出形状: {model(x).shape}")
3. 参数管理
3.1 Parameter与named_parameters
Python
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 5)
)
# 遍历所有命名参数
print("=== named_parameters ===")
for name, param in model.named_parameters():
print(f"{name}: {param.shape}, requires_grad={param.requires_grad}")
# 只遍历参数值
print("\n=== parameters ===")
for i, param in enumerate(model.parameters()):
print(f"param[{i}]: {param.shape}, numel={param.numel()}")
# 统计总参数量
total_params = sum(p.numel() for p in model.parameters())
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"\n总参数量: {total_params}")
print(f"可训练参数量: {trainable_params}")
3.2 buffers:非参数状态
Python
# buffers是模型状态的一部分,但不参与梯度计算
# 典型例子:BatchNorm的running_mean和running_var
bn = nn.BatchNorm1d(10)
print("=== 参数 ===")
for name, p in bn.named_parameters():
print(f" {name}: {p.shape}")
print("=== Buffers ===")
for name, b in bn.named_buffers():
print(f" {name}: {b.shape}")
# state_dict包含参数和buffers
print("\n=== state_dict ===")
for key in bn.state_dict():
print(f" {key}: {bn.state_dict()[key].shape}")
3.3 state_dict与模型保存
Python
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 5)
self.bn = nn.BatchNorm1d(5)
def forward(self, x):
return self.bn(torch.relu(self.fc(x)))
model = MyModel()
# 获取state_dict(有序字典)
sd = model.state_dict()
print("state_dict键:")
for k, v in sd.items():
print(f" {k}: {v.shape}")
# 保存模型(推荐只保存state_dict)
torch.save(model.state_dict(), "model_weights.pth")
# 加载模型
model_loaded = MyModel()
model_loaded.load_state_dict(torch.load("model_weights.pth"))
model_loaded.eval()
print("模型加载成功!")
# 部分加载(迁移学习场景)
# model.load_state_dict(torch.load("pretrained.pth"), strict=False)
4. 常用网络层全览
4.1 线性层
Python
import torch.nn as nn
# nn.Linear:全连接层 y = xW^T + b
linear = nn.Linear(in_features=768, out_features=1024, bias=True)
# nn.Bilinear:双线性层 z = x1^T A x2 + b
bilinear = nn.Bilinear(in1_features=10, in2_features=10, out_features=5)
# nn.LazyLinear:延迟推断输入维度
lazy = nn.LazyLinear(out_features=100) # 第一次forward时自动推断in_features
4.2 卷积层
Python
import torch
import torch.nn as nn
# Conv2d:二维卷积
conv = nn.Conv2d(
in_channels=3, # 输入通道(RGB=3)
out_channels=64, # 输出通道(卷积核数量)
kernel_size=3, # 卷积核大小
stride=1, # 步长
padding=1, # 填充(same padding)
bias=True
)
x = torch.randn(1, 3, 224, 224) # (B, C, H, W)
print(f"Conv2d: {x.shape} -> {conv(x).shape}")
# Conv1d:一维卷积(用于序列/时间序列)
conv1d = nn.Conv1d(12, 64, kernel_size=3, padding=1)
x1d = torch.randn(1, 12, 100) # (B, C, L)
print(f"Conv1d: {x1d.shape} -> {conv1d(x1d).shape}")
# ConvTranspose2d:转置卷积(用于上采样/生成器)
convt = nn.ConvTranspose2d(64, 3, kernel_size=4, stride=2, padding=1)
x_t = torch.randn(1, 64, 16, 16)
print(f"ConvT2d: {x_t.shape} -> {convt(x_t).shape}") # 空间维度翻倍
4.3 归一化层
Python
import torch
import torch.nn as nn
x = torch.randn(2, 10, 768) # (batch, seq_len, hidden)
# BatchNorm:跨batch和空间维度归一化
# 适合CNN,不适合NLP(batch内统计不稳定)
bn = nn.BatchNorm1d(768)
# bn(x) # 需要输入(B, C)或(B, C, L)格式
# LayerNorm:跨特征维度归一化(每个样本独立)
# Transformer的标准选择
ln = nn.LayerNorm(768)
print(f"LayerNorm: {ln(x).shape}")
print(f"归一化后均值: {ln(x).mean(dim=-1).abs().max():.6f}")
# RMSNorm:LayerNorm的简化版(不中心化)
# LLaMA等大模型使用,计算更快
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x):
rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).sqrt()
return x / rms * self.weight
rmsnorm = RMSNorm(768)
print(f"RMSNorm: {rmsnorm(x).shape}")
4.4 Dropout与Embedding
Python
import torch
import torch.nn as nn
# Dropout:训练时随机置零,测试时不操作
dropout = nn.Dropout(p=0.1)
x = torch.ones(5, 5)
dropout.train()
print(f"训练模式:\n{dropout(x)}")
dropout.eval()
print(f"评估模式:\n{dropout(x)}")
# Embedding:整数索引 -> 稠密向量
# 大模型的核心层:token_id -> embedding向量
embedding = nn.Embedding(
num_embeddings=50000, # 词表大小
embedding_dim=768, # 嵌入维度
padding_idx=0 # padding位置的embedding固定为0
)
token_ids = torch.randint(1, 50000, (2, 10)) # (batch, seq_len)
embedded = embedding(token_ids)
print(f"Embedding: {token_ids.shape} -> {embedded.shape}")
# (2, 10) -> (2, 10, 768)
6. 容器:Sequential、ModuleList、ModuleDict
6.1 nn.Sequential
Python
import torch.nn as nn
# Sequential:按顺序执行,最简单的容器
model = nn.Sequential(
nn.Linear(768, 1024),
nn.LayerNorm(1024),
nn.GELU(),
nn.Dropout(0.1),
nn.Linear(1024, 768),
nn.LayerNorm(768),
nn.GELU(),
nn.Linear(768, 10)
)
# 也可以用OrderedDict命名每一层
from collections import OrderedDict
model_named = nn.Sequential(OrderedDict([
("fc1", nn.Linear(768, 1024)),
("norm1", nn.LayerNorm(1024)),
("act1", nn.GELU()),
("fc2", nn.Linear(1024, 10)),
]))
print(model_named)
6.2 nn.ModuleList vs Python list
Python
import torch
import torch.nn as nn
# ❌ 错误:使用普通Python list,参数不会被注册
class WrongModel(nn.Module):
def __init__(self):
super().__init__()
self.layers = [nn.Linear(10, 10) for _ in range(3)] # 参数不会被跟踪!
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
wrong = WrongModel()
print(f"错误写法参数量: {sum(p.numel() for p in wrong.parameters())}") # 0!
# ✅ 正确:使用nn.ModuleList
class CorrectModel(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList([nn.Linear(10, 10) for _ in range(3)])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
correct = CorrectModel()
print(f"正确写法参数量: {sum(p.numel() for p in correct.parameters())}") # 330
注意
这是初学者最常犯的错误之一。当你需要在模型中存储一组子模块时,
必须使用
nn.ModuleList或
nn.ModuleDict,而不是普通的Python list或dict。否则参数不会被注册,模型保存/加载会丢失权重,优化器也不会更新这些参数。
6.3 nn.ModuleDict
Python
class MultiHeadModel(nn.Module):
def __init__(self, hidden_dim, head_specs):
super().__init__()
self.backbone = nn.Linear(hidden_dim, hidden_dim)
# 使用ModuleDict管理多个任务头
self.heads = nn.ModuleDict({
name: nn.Linear(hidden_dim, num_classes)
for name, num_classes in head_specs.items()
})
def forward(self, x, task_name):
features = torch.relu(self.backbone(x))
return self.heads[task_name](features)
# 多任务模型:分类+回归
model = MultiHeadModel(768, {"classification": 10, "regression": 1})
x = torch.randn(4, 768)
print(f"分类输出: {model(x, 'classification').shape}")
print(f"回归输出: {model(x, 'regression').shape}")
7. 参数初始化
7.1 初始化策略对比
| 方法 | 公式 | 适用场景 |
| Xavier/Glorot Uniform | U(-√(6/(n+m)), √(6/(n+m))) | tanh/sigmoid激活 |
| Xavier/Glorot Normal | N(0, √(2/(n+m))) | tanh/sigmoid激活 |
| He/Kaiming Uniform | U(-√(6/n), √(6/n)) | ReLU及其变体 |
| He/Kaiming Normal | N(0, √(2/n)) | ReLU及其变体 |
| Orthogonal | 正交矩阵 | RNN/深度网络 |
| Truncated Normal | 截断正态分布 | Embedding/大模型 |
7.2 使用init模块
Python
import torch
import torch.nn as nn
import torch.nn.init as init
class InitializedModel(nn.Module):
def __init__(self, dim):
super().__init__()
self.fc1 = nn.Linear(dim, dim * 2)
self.fc2 = nn.Linear(dim * 2, dim)
# 手动初始化每一层
init.kaiming_normal_(self.fc1.weight, mode="fan_in", nonlinearity="relu")
init.zeros_(self.fc1.bias)
init.xavier_normal_(self.fc2.weight)
init.zeros_(self.fc2.bias)
def forward(self, x):
return self.fc2(torch.relu(self.fc1(x)))
model = InitializedModel(768)
print(f"fc1权重均值: {model.fc1.weight.mean():.4f}")
print(f"fc1权重标准差: {model.fc1.weight.std():.4f}")
7.3 使用apply()批量初始化
Python
def init_weights(module):
# apply会递归地对所有子模块调用此函数
if isinstance(module, nn.Linear):
init.xavier_normal_(module.weight)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0, std=0.02)
elif isinstance(module, nn.LayerNorm):
init.ones_(module.weight)
init.zeros_(module.bias)
# 创建复杂模型并统一初始化
model = nn.Sequential(
nn.Linear(768, 1024),
nn.LayerNorm(1024),
nn.GELU(),
nn.Linear(1024, 768),
)
model.apply(init_weights)
print("统一初始化完成!")
# 大模型常用的初始化方式
def init_bert_weights(module):
# BERT风格的初始化
if isinstance(module, nn.Linear):
init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0.0, std=0.02)
8. 模型结构检查
8.1 打印模型与参数计数
Python
import torch
import torch.nn as nn
class TransformerBlock(nn.Module):
def __init__(self, dim=768, heads=12, dropout=0.1):
super().__init__()
self.attention = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
self.norm1 = nn.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim)
self.ffn = nn.Sequential(
nn.Linear(dim, dim * 4),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(dim * 4, dim),
)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
attn_out, _ = self.attention(x, x, x)
x = self.norm1(x + self.dropout(attn_out))
ffn_out = self.ffn(x)
x = self.norm2(x + self.dropout(ffn_out))
return x
model = TransformerBlock()
# 打印模型结构
print(model)
# 详细参数统计
print("\n=== 参数统计 ===")
for name, param in model.named_parameters():
print(f"{name:40s} {str(param.shape):20s} {param.numel():>8d}")
total = sum(p.numel() for p in model.parameters())
print(f"\n总参数量: {total:,d}")
print(f"总参数量(MB): {total * 4 / 1024 / 1024:.2f}") # float32
8.2 使用Hook检查中间输出
Python
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 10),
)
# 注册forward hook:捕获中间层输出
activations = {}
def get_activation(name):
def hook(module, input, output):
activations[name] = output.detach()
return hook
# 对第0层(第一个Linear)注册hook
model[0].register_forward_hook(get_activation("fc1"))
model[2].register_forward_hook(get_activation("fc2"))
# 运行模型
x = torch.randn(3, 10)
output = model(x)
print("中间层输出:")
for name, act in activations.items():
print(f" {name}: shape={act.shape}, mean={act.mean():.4f}, std={act.std():.4f}")
# 注册backward hook:捕获梯度
gradients = {}
def get_gradient(name):
def hook(module, grad_input, grad_output):
gradients[name] = grad_output[0].detach()
return hook
model[0].register_full_backward_hook(get_gradient("fc1_grad"))
output.sum().backward()
print("\n梯度:")
for name, grad in gradients.items():
print(f" {name}: shape={grad.shape}")
9. 自定义网络层
9.1 带可学习参数的自定义层
Python
import torch
import torch.nn as nn
class LoRALinear(nn.Module):
"""LoRA低秩适配层:大模型微调的核心组件
将权重更新分解为两个低秩矩阵的乘积:W + BA
其中B是(d, r),A是(r, d),r远小于d
"""
def __init__(self, in_features, out_features, r=8, alpha=16):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.r = r
self.scaling = alpha / r
# 原始权重(冻结,不训练)
self.base_weight = nn.Parameter(
torch.randn(out_features, in_features), requires_grad=False
)
# LoRA低秩矩阵(可训练)
self.lora_A = nn.Parameter(torch.randn(r, in_features) * 0.01)
self.lora_B = nn.Parameter(torch.zeros(out_features, r))
def forward(self, x):
# 原始变换 + LoRA低秩更新
base_out = x @ self.base_weight.T
lora_out = (x @ self.lora_A.T) @ self.lora_B.T * self.scaling
return base_out + lora_out
def enable_lora(self):
"""只训练LoRA参数"""
self.base_weight.requires_grad = False
self.lora_A.requires_grad = True
self.lora_B.requires_grad = True
# 使用LoRA层
lora_layer = LoRALinear(768, 768, r=8, alpha=16)
lora_layer.enable_lora()
# 参数对比
base_params = sum(p.numel() for p in lora_layer.parameters() if not p.requires_grad)
lora_params = sum(p.numel() for p in lora_layer.parameters() if p.requires_grad)
print(f"原始参数: {base_params:,d}")
print(f"LoRA参数: {lora_params:,d}")
print(f"压缩比: {lora_params/base_params*100:.2f}%")
9.2 无参数自定义层
Python
class GradientReversalLayer(nn.Module):
"""梯度反转层:对抗训练中常用
前向传播不变,反向传播时梯度乘以-λ
"""
def __init__(self, lambda_val=1.0):
super().__init__()
self.lambda_val = lambda_val
def forward(self, x):
# 使用自定义autograd Function实现梯度反转
return GradientReversalFunction.apply(x, self.lambda_val)
from torch.autograd import Function
class GradientReversalFunction(Function):
@staticmethod
def forward(ctx, x, lambda_val):
ctx.lambda_val = lambda_val
return x.clone()
@staticmethod
def backward(ctx, grad_output):
return -ctx.lambda_val * grad_output, None
# 使用示例
grl = GradientReversalLayer(lambda_val=0.1)
x = torch.randn(3, 10, requires_grad=True)
y = grl(x).sum()
y.backward()
print(f"梯度反转后的x.grad: {x.grad}")
print(f"梯度均值: {x.grad.mean():.4f} (应为-0.1)")
11. 模型设备迁移与保存
11.1 设备迁移
Python
import torch
import torch.nn as nn
model = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5))
# 方式1:to()(推荐)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# 方式2:cuda()/cpu()
# model = model.cuda()
# 方式3:指定GPU编号
# model = model.to("cuda:0")
# 数据也需要移到相同设备
x = torch.randn(3, 10).to(device)
output = model(x)
print(f"输出设备: {output.device}")
# 混合精度训练
if torch.cuda.is_available():
scaler = torch.amp.GradScaler()
with torch.amp.autocast(device_type="cuda"):
output = model(x)
print(f"混合精度输出类型: {output.dtype}")
11.2 完整的模型保存与加载
Python
import torch
import torch.nn as nn
import os
class SaveableModel(nn.Module):
def __init__(self, dim=768):
super().__init__()
self.embedding = nn.Embedding(50000, dim)
self.transformer = nn.TransformerEncoder(
nn.TransformerEncoderLayer(dim, nhead=8, dim_feedforward=dim*4, batch_first=True),
num_layers=6
)
self.classifier = nn.Linear(dim, 10)
def forward(self, input_ids):
x = self.embedding(input_ids)
x = self.transformer(x)
return self.classifier(x[:, 0]) # 取[CLS]位置
model = SaveableModel()
# === 保存checkpoint ===
checkpoint = {
"epoch": 10,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": torch.optim.AdamW(model.parameters()).state_dict(),
"loss": 0.123,
}
torch.save(checkpoint, "checkpoint.pth")
# === 加载checkpoint ===
checkpoint = torch.load("checkpoint.pth", map_location="cpu")
model_loaded = SaveableModel()
model_loaded.load_state_dict(checkpoint["model_state_dict"])
print(f"加载epoch {checkpoint['epoch']}, loss={checkpoint['loss']}")
# === 保存为TorchScript(部署用) ===
scripted = torch.jit.script(model)
scripted.save("model_scripted.pt")
# 加载TorchScript模型(不需要类定义)
loaded = torch.jit.load("model_scripted.pt")
print("TorchScript模型保存/加载成功!")