
Block—— Transformer 层第94-106行class Block(nn.Module):def __init__(self, config):super().__init__()self.ln_1 LayerNorm(config.n_embd, biasconfig.bias)self.attn CausalSelfAttention(config)self.ln_2 LayerNorm(config.n_embd, biasconfig.bias)self.mlp MLP(config)def forward(self, x):# 预归一化 残差连接x x self.attn(self.ln_1(x)) # 注意力子层x x self.mlp(self.ln_2(x)) # FFN 子层return x结构图示x│├─────────────────────────┐│ │▼ ▼┌───────┐ ┌───────┐│ Layer │ │ Layer ││ Norm │ │ Norm │└───────┘ └───────┘│ │▼ ▼┌─────────┐ ┌───────┐│ Attention │ │ MLP ││ (Multi- │ │(FFN) ││ Head) │ └───────┘└─────────┘ ││ │└──────────┬───────────┘│▼x (输出)残差连接的作用- 梯度可以直通缓解消失梯度问题- 保留原始信息神经网络只学增量