大语言模型基础
Transformer 架构
注意力机制
自注意力原理
# 查询、键、值计算
Q = X × WQ
K = X × WK
V = X × WV
# 注意力权重
Attention(Q, K, V) = softmax(QK^T / √dk) V
其中:
- dk: 键向量维度
- softmax: 归一化函数
多头注意力
# 多头计算
MultiHead(Q, K, V) = Concat(head1, ..., headh)WO
where headi = Attention(QWQi, KWKi, VWVi)
特点:
- 并行计算多个注意力
- 捕获不同类型关系
- 提升模型表达能力
位置编码
正弦位置编码
PE(pos, 2i) = sin(pos / 10000^(2i/dmodel))
PE(pos, 2i+1) = cos(pos / 10000^(2i/dmodel))
特点:
- 绝对位置信息
- 周期性函数
- 外推性有限
可学习位置编码
# 参数化位置嵌入
position_embeddings = Embedding(max_seq_len, dmodel)
特点:
- 灵活学习位置关系
- 需要大量训练数据
- 可能过拟合
编码器-解码器结构
编码器层
class EncoderLayer:
def __init__(self):
self.self_attn = MultiHeadAttention()
self.ffn = FeedForward()
self.norm1 = LayerNorm()
self.norm2 = LayerNorm()
def forward(self, x):
# 自注意力 + 残差连接
x = self.norm1(x + self.self_attn(x, x, x))
# 前馈网络 + 残差连接
x = self.norm2(x + self.ffn(x))
return x
解码器层
class DecoderLayer:
def __init__(self):
self.self_attn = MultiHeadAttention()
self.cross_attn = MultiHeadAttention()
self.ffn = FeedForward()
self.norm1 = LayerNorm()
self.norm2 = LayerNorm()
self.norm3 = LayerNorm()
def forward(self, x, encoder_output):
# 掩码自注意力
x = self.norm1(x + self.self_attn(x, x, x, mask=True))
# 编码器-解码器注意力
x = self.norm2(x + self.cross_attn(x, encoder_output, encoder_output))
# 前馈网络
x = self.norm3(x + self.ffn(x))
return x
预训练技术
语言模型目标
因果语言模型(Causal LM)
# 自回归预测
P(wt | w1, w2, ..., w(t-1)) = softmax(W × ht)
损失函数:
L = -Σt log P(wt | w<t)
特点:
- 从左到右生成
- 适合文本生成
- GPT 系列使用
掩码语言模型(Masked LM)
# 掩码预测
P(wi | context) = softmax(W × hi)
损失函数:
L = -