组装现代大模型的标准积木:Transformer Block
无论是 7B 还是 671B 参数的大模型,其主体都是由数十层结构完全一致的 Transformer Block 堆叠而成。每一个标准 Block 由四大核心组件配合工作:
- 多头自注意力(Multi-Head Attention):将通道拆分为多个“注意力头”并行关注语法、指代、位置等不同维度的关系(负责 Token 之间的信息沟通)。
- 前馈全连接网络(Feed-Forward MLP):通常先升维 4 倍经过
GELU激活后再降回原维度(负责单 Token 内部的深度特征加工)。 - 层归一化(LayerNorm):现代大模型普遍采用 Pre-Norm(先做 LayerNorm 再进子层),大幅提升深层训练稳定性。
- 残差连接(Residual Connection):
x = x + sublayer(norm(x)),为反向传播开辟无损梯度高速公路。
import torch
import torch.nn as nn
class TransformerBlock(nn.Module):
def __init__(self, d_model=64, n_heads=4):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
self.ln2 = nn.LayerNorm(d_model)
self.mlp = nn.Sequential(
nn.Linear(d_model, 4 * d_model),
nn.GELU(),
nn.Linear(4 * d_model, d_model),
)
def forward(self, x):
T = x.size(1)
causal_mask = nn.Transformer.generate_square_subsequent_mask(T, device=x.device)
# Pre-Norm + 残差连接 1:多头自注意力沟通上下文
h = self.ln1(x)
attn_out, _ = self.attn(h, h, h, attn_mask=causal_mask, is_causal=True)
x = x + attn_out
# Pre-Norm + 残差连接 2:MLP 逐位置非线性变换
x = x + self.mlp(self.ln2(x))
return x
block = TransformerBlock(d_model=64, n_heads=4)
inp = torch.randn(2, 12, 64)
out = block(inp)
print("输入形状:", inp.shape, "-> 经过 TransformerBlock 输出形状:", out.shape)
print("单层参数量:", sum(p.numel() for p in block.parameters()))