编辑模式 · Ctrl+S 保存

Transformer

改变 AI 的架构

从 "Attention is All You Need" 到统治 AI 世界

为什么需要 Transformer?

RNN 的局限性

⚠️ 串行处理

必须按顺序处理每个词,无法并行化

t₁ → t₂ → t₃ → t₄...

⚠️ 长距离依赖

梯度消失/爆炸,难以捕捉远距离关系

信息会随着序列变长而衰减

核心创新

Attention is All You Need

完全抛弃循环结构

用 Self-Attention 机制 直接建模序列中任意两个位置的关系

Self-Attention 机制

让每个词"关注"其他所有词

输入: "我 爱 AI"
Q (查询)
K (键)
V (值)
计算相似度: Q·Kᵀ / √dₖ
Softmax 归一化
加权求和: Attention(Q,K,V)
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

Multi-Head Attention

多个"视角"同时关注

不是只用一组 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

Position Encoding

让模型知道词的顺序

⚠️ 问题: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)

编码器-解码器结构

📥 Encoder(编码器)

  • ✓ Multi-Head Self-Attention
  • ✓ Feed-Forward Network
  • ✓ Layer Norm + Residual
  • ✓ N=6 层堆叠

用于:理解输入序列

📤 Decoder(解码器)

  • ✓ Masked Self-Attention
  • ✓ Cross-Attention(看 Encoder)
  • ✓ Feed-Forward Network
  • ✓ N=6 层堆叠

用于:生成输出序列

输入 Embedding + Position Encoding
Encoder × N 层
Decoder × N 层
Linear + Softmax
输出概率分布

Transformer 的应用

统治 NLP 和多模态 AI

🤖 GPT 系列

Decoder-only

GPT-3: 175B 参数
GPT-4: 1.7T+ 参数
应用: 文本生成、对话、代码

🔍 BERT 系列

Encoder-only

BERT-base: 110M 参数
BERT-large: 340M 参数
应用: 文本分类、NER、问答

🔄 T5

Encoder-Decoder

T5-11B: 11B 参数
应用: 翻译、摘要、统一文本任务

🖼️ Vision Transformer (ViT)

图像 = 序列

将图像切成 Patch
用 Transformer 处理
应用: 图像分类、检测、分割

总结

  • Self-Attention - 核心创新,全局关注
  • 并行化 - 训练速度提升 10-100 倍
  • Multi-Head - 多视角捕捉关系
  • Position Encoding - 位置信息注入
  • 可扩展性 - 从 110M 到 1.7T+ 参数

Transformer = AI 的基础设施

从 NLP 到 CV,从单模态到多模态,从 2017 到现在
Attention is All You Need 彻底改变了 AI

🚀 继续学习:GPT、BERT、ViT、Diffusion Models...