大模型原理与训练 / 系统课时
组装 GPT 解码块与模型头
组装 GPT 解码块与模型头
这一节把因果自注意力扩展成可堆叠的 GPT 风格 Decoder-only 网络:加入 Pre-LN、两条残差连接、前馈网络、Token 与位置嵌入,以及把隐藏状态映射到词表的语言模型头。最终会跑通一次前向计算和交叉熵损失。
学习目标
- 能说明 GPT 解码块中归一化、注意力、前馈层与残差的连接顺序。
- 能把多个解码块堆叠成 Decoder-only 主干,并连接语言模型头。
- 能用 logits 形状和有限损失验证模型前向链路。
Decoder-only 解码块如何组合
一个常见的 GPT 风格块采用 Pre-LN:先归一化再进入子层,子层输出与原输入做残差相加。注意力负责跨 Token 混合信息,MLP 负责在每个 Token 位置内部变换特征;两者都保持 [B,T,C] 形状,因此可以重复堆叠。

语言模型头对每个位置独立执行同一个线性映射,把最后一维从 C 变为词表大小 V,因此 logits 形状是 [B,T,V]。训练时,第 t 个位置的 logits 用于预测相应目标 Token。
实现可堆叠的 MiniGPT
下面是完整可运行示例。为保持重点清晰,注意力、MLP、解码块和整模都放在同一文件中;模型使用学习式位置嵌入,并在提供 targets 时计算交叉熵。
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalSelfAttention(nn.Module):
def __init__(self, embed_dim: int, num_heads: int, block_size: int):
super().__init__()
if embed_dim % num_heads != 0:
raise ValueError("embed_dim must be divisible by num_heads")
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.qkv = nn.Linear(embed_dim, 3 * embed_dim)
self.proj = nn.Linear(embed_dim, embed_dim)
mask = torch.tril(
torch.ones(block_size, block_size, dtype=torch.bool)
)
self.register_buffer(
"mask",
mask.view(1, 1, block_size, block_size),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
bsz, seq_len, channels = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
def split_heads(t: torch.Tensor) -> torch.Tensor:
return t.view(
bsz, seq_len, self.num_heads, self.head_dim
).transpose(1, 2)
q, k, v = map(split_heads, (q, k, v))
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
mask = self.mask[:, :, :seq_len, :seq_len]
scores = scores.masked_fill(
~mask, torch.finfo(scores.dtype).min
)
weights = torch.softmax(scores, dim=-1)
context = weights @ v
context = context.transpose(1, 2).contiguous().view(
bsz, seq_len, channels
)
return self.proj(context)
class MLP(nn.Module):
def __init__(self, embed_dim: int):
super().__init__()
self.net = nn.Sequential(
nn.Linear(embed_dim, 4 * embed_dim),
nn.GELU(),
nn.Linear(4 * embed_dim, embed_dim),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
class DecoderBlock(nn.Module):
def __init__(self, embed_dim: int, num_heads: int, block_size: int):
super().__init__()
self.ln1 = nn.LayerNorm(embed_dim)
self.attn = CausalSelfAttention(
embed_dim, num_heads, block_size
)
self.ln2 = nn.LayerNorm(embed_dim)
self.mlp = MLP(embed_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Pre-LN:每个子层先看归一化特征,再把结果加回残差。
x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return x
class MiniGPT(nn.Module):
def __init__(
self,
vocab_size: int,
block_size: int,
embed_dim: int,
num_heads: int,
num_layers: int,
):
super().__init__()
self.block_size = block_size
self.token_emb = nn.Embedding(vocab_size, embed_dim)
self.pos_emb = nn.Embedding(block_size, embed_dim)
self.blocks = nn.ModuleList(
[
DecoderBlock(embed_dim, num_heads, block_size)
for _ in range(num_layers)
]
)
self.ln_f = nn.LayerNorm(embed_dim)
self.lm_head = nn.Linear(embed_dim, vocab_size, bias=False)
def forward(self, input_ids: torch.Tensor, targets=None):
_, seq_len = input_ids.shape
if seq_len > self.block_size:
raise ValueError("sequence length exceeds block_size")
positions = torch.arange(
seq_len, device=input_ids.device
)
x = self.token_emb(input_ids) + self.pos_emb(positions)
for block in self.blocks:
x = block(x)
logits = self.lm_head(self.ln_f(x))
loss = None
if targets is not None:
loss = F.cross_entropy(
logits.reshape(-1, logits.size(-1)),
targets.reshape(-1),
)
return logits, loss
torch.manual_seed(7)
model = MiniGPT(
vocab_size=32,
block_size=8,
embed_dim=16,
num_heads=4,
num_layers=2,
)
input_ids = torch.randint(0, 32, (2, 8))
targets = torch.randint(0, 32, (2, 8))
logits, loss = model(input_ids, targets)
print("logits shape:", tuple(logits.shape))
print("number of blocks:", len(model.blocks))
print("loss finite:", bool(torch.isfinite(loss)))预期输出如下:
logits shape: (2, 8, 32)
number of blocks: 2
loss finite: True(2, 8, 32) 表示两个样本、每个八个位置、每个位置对 32 个词表项给出一个分数。损失为有限值说明嵌入、解码块、最终归一化、语言模型头和交叉熵已经连成一条可训练的前向链路。
残差与归一化各自解决什么
残差连接要求子层输入输出形状一致,因此注意力和 MLP 都最终回到 C 维。这样每个块只学习对当前表示的增量修改,堆叠深度增加时仍保留直接的信息通道。
Pre-LN 把 LayerNorm 放在注意力或 MLP 之前,而残差主路径不先被归一化。这里两个子层各有自己的归一化层,模型堆叠结束后再经过 ln_f,然后才交给语言模型头。
验证 Decoder-only 的关键约束
模型能返回 logits 并不代表结构一定正确。最基本的验收是:输入 [B,T] 后得到 [B,T,V];块数量与配置一致;损失有限;序列长度超过 block_size 时明确拒绝;每个注意力层内部都应用同方向的因果 Mask。
语言模型头不负责因果性,它只读取主干已经计算好的隐藏状态。真正保证“只能根据当前位置及其左侧上下文预测”的,是每一层自注意力里的因果掩码。把这条约束与残差、Pre-LN、MLP 和最终词表投影组合起来,就得到一个可以继续接训练循环的最小 GPT 主干。