改变 AI 的架构
从 "Attention is All You Need" 到统治 AI 世界
必须按顺序处理每个词,无法并行化
t₁ → t₂ → t₃ → t₄...
梯度消失/爆炸,难以捕捉远距离关系
信息会随着序列变长而衰减
完全抛弃循环结构
用 Self-Attention 机制 直接建模序列中任意两个位置的关系
def self_attention(Q, K, V):
# Q, K, V shape: (batch, seq_len, d_model)
d_k = K.shape[-1]
# 计算注意力分数
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
# Softmax 归一化
attention_weights = F.softmax(scores, dim=-1)
# 加权求和
output = torch.matmul(attention_weights, V)
return output, attention_weights
不是只用一组 Q、K、V,而是将它们分成 h 个头(heads)
GPT-3: h=96 个头 · BERT-base: h=12 个头
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
self.num_heads = num_heads
self.d_k = d_model // num_heads
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
def forward(self, x):
# 分成多个头,并行计算
Q, K, V = self.split_heads(x)
attn_output = self.scaled_dot_product_attention(Q, K, V)
output = self.W_o(attn_output)
return output
⚠️ 问题:Self-Attention 是位置无关的
"我爱AI" 和 "AI爱我" 的 Attention 结果相同
✓ 解决方案:Position Encoding
在输入 Embedding 上叠加位置信息
# 正弦/余弦位置编码(原始 Transformer)
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
# 可学习位置编码(BERT、GPT)
position_embeddings = nn.Embedding(max_seq_len, d_model)
# 相对位置编码(T5、RoPE)
def relative_position_bias(q_len, k_len):
return self.relative_attention_bias(q_len, k_len)
用于:理解输入序列
用于:生成输出序列
Decoder-only
GPT-3: 175B 参数
GPT-4: 1.7T+ 参数
应用: 文本生成、对话、代码
Encoder-only
BERT-base: 110M 参数
BERT-large: 340M 参数
应用: 文本分类、NER、问答
Encoder-Decoder
T5-11B: 11B 参数
应用: 翻译、摘要、统一文本任务
图像 = 序列
将图像切成 Patch
用 Transformer 处理
应用: 图像分类、检测、分割
Transformer = AI 的基础设施
从 NLP 到 CV,从单模态到多模态,从 2017 到现在
Attention is All You Need 彻底改变了 AI
🚀 继续学习:GPT、BERT、ViT、Diffusion Models...