大模型原理与训练 / 系统课时
编码器层实现
编码器层实现
本课将四个核心部件组合成一个可运行的 Transformer 编码器层:多头自注意力负责聚合上下文,前馈网络逐位置变换特征,残差连接保留信息,层归一化稳定训练。最终代码同时支持 Pre-LN 与 Post-LN。
学习目标
- 理解编码器层中各模块的连接顺序
- 使用 PyTorch 实现支持两种归一化位置的编码器层
- 验证张量形状、填充掩码和数值有效性
结构与张量约定
示例采用 batch_first=True,输入张量形状为 [batch_size, seq_len, d_model]。自注意力的查询、键和值都来自同一个输入,因此属于自注意力;前馈网络只作用于最后一个特征维度,不会混合不同位置。

key_padding_mask 的形状为 [batch_size, seq_len],其中 True 表示该键位置应被忽略。它会阻止有效词元关注填充键,但不会自动删除填充位置对应的输出,后续损失计算仍应继续忽略这些位置。
完整实现
下面是完整文件示例,依赖已安装的 PyTorch。norm_first=True 使用 Pre-LN,设为 False 时切换为 Post-LN。
import torch
from torch import nn
class EncoderLayer(nn.Module):
def __init__(
self,
d_model: int,
num_heads: int,
dim_feedforward: int,
dropout: float = 0.1,
norm_first: bool = True,
) -> None:
super().__init__()
self.norm_first = norm_first
# batch_first=True 统一使用 [批次, 序列长度, 特征维度]
self.self_attn = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=num_heads,
dropout=dropout,
batch_first=True,
)
self.ffn = nn.Sequential(
nn.Linear(d_model, dim_feedforward),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(dim_feedforward, d_model),
)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
def _attention(
self,
x: torch.Tensor,
key_padding_mask: torch.Tensor | None,
) -> torch.Tensor:
# 不需要注意力权重时关闭返回,可减少额外内存占用
output, _ = self.self_attn(
x,
x,
x,
key_padding_mask=key_padding_mask,
need_weights=False,
)
return output
def forward(
self,
x: torch.Tensor,
key_padding_mask: torch.Tensor | None = None,
) -> torch.Tensor:
if self.norm_first:
# Pre-LN:归一化只作用于子层输入,残差主路保持直通
x = x + self.dropout1(
self._attention(self.norm1(x), key_padding_mask)
)
x = x + self.dropout2(self.ffn(self.norm2(x)))
return x
# Post-LN:每次残差相加之后再执行归一化
x = self.norm1(
x + self.dropout1(self._attention(x, key_padding_mask))
)
x = self.norm2(x + self.dropout2(self.ffn(x)))
return x
def main() -> None:
torch.manual_seed(7)
layer = EncoderLayer(
d_model=8,
num_heads=2,
dim_feedforward=16,
dropout=0.0,
norm_first=True,
)
layer.eval()
inputs = torch.randn(2, 4, 8)
padding_mask = torch.tensor(
[
[False, False, False, False],
[False, False, False, True],
]
)
with torch.no_grad():
outputs = layer(inputs, key_padding_mask=padding_mask)
print("input shape:", tuple(inputs.shape))
print("output shape:", tuple(outputs.shape))
print("all finite:", bool(torch.isfinite(outputs).all()))
if __name__ == "__main__":
main()将代码保存为 encoder_layer.py 后运行:
python encoder_layer.py预期输出:
input shape: (2, 4, 8)
output shape: (2, 4, 8)
all finite: True关键边界与验收
d_model 必须能被 num_heads 整除,否则每个注意力头无法获得相同维度。前馈网络的最后一层必须投影回 d_model,这样结果才能与残差分支相加。
示例把两个 Dropout 分开,便于清晰表达两个残差分支。训练阶段它们会随机丢弃部分子层输出,验证或推理时应调用 eval() 关闭随机性。
当批次含有填充位置时,掩码应与输入位于兼容设备上。训练语言模型或分类器时,还要在损失函数或池化逻辑中继续排除填充位置,不能只依赖注意力掩码。
运行结果首先应满足输入与输出形状相同,因为编码器层不会改变序列长度和模型维度。其次,all finite: True 表明当前输入下没有产生 NaN 或无穷值。还可以把 norm_first 改为 False 再运行,输出形状应保持一致,但数值会因计算顺序不同而变化。
本课总结
- 编码器层由自注意力子层和前馈子层组成,每个子层都配有残差与归一化
norm_first决定 Pre-LN 或 Post-LN,张量外形在层前后保持不变- 填充掩码只限制注意力读取,损失和池化阶段仍需继续忽略填充位置
下一课预告
下一课将把多个编码器层堆叠成完整编码器,并讨论层数、最终归一化和中间表示的组织方式。