🧠 图解记忆:BERT 补空理解上下文,GPT 沿时间预测下一个 Token;点击图片可查看原图。
💡 答案要点
核心区别:BERT是双向理解,GPT是单向生成
架构对比:
| 维度 | BERT | GPT |
|---|---|---|
| 架构 | 仅Encoder | 仅Decoder |
| 注意力 | 双向(无mask) | 单向(causal mask) |
| 训练目标 | MLM + NSP | 自回归语言模型 |
| 任务类型 | 理解(分类、NER) | 生成(文本生成) |
| 参数 | 110M-340M | 117M-175B |
BERT(Bidirectional Encoder Representations from Transformers):
┌─────────────────────────────────────────────────────────┐
│ BERT 架构 │
└─────────────────────────────────────────────────────────┘
输入:"The [MASK] sat on the mat"
↓
Embedding + Positional Encoding
↓
Transformer Encoder (12/24 层)
├── Multi-Head Self-Attention(双向)
└── Feed-Forward Network
↓
输出:每个token的上下文表示
↓
任务头(分类/NER/...)训练目标1:MLM(Masked Language Model)
python
# 随机mask 15%的token
原文:"The cat sat on the mat"
Mask: "The [MASK] sat on the [MASK]"
# 预测被mask的词
损失 = CrossEntropy(预测, ["cat", "mat"])
# 15%中的策略:
# 80%: 替换为 [MASK]
# 10%: 替换为随机词
# 10%: 保持不变训练目标2:NSP(Next Sentence Prediction)
python
# 判断两句话是否连续
输入:
A: "The cat sat on the mat."
B: "It was very comfortable."
Label: IsNext (1) or NotNext (0)
损失 = BCELoss(预测, Label)GPT(Generative Pre-trained Transformer):
┌─────────────────────────────────────────────────────────┐
│ GPT 架构 │
└─────────────────────────────────────────────────────────┘
输入:"The cat sat on"
↓
Embedding + Positional Encoding
↓
Transformer Decoder (12/96 层)
├── Masked Multi-Head Self-Attention(单向)
└── Feed-Forward Network
↓
输出:下一个token的概率分布
↓
预测:"the" (概率0.8)训练目标:自回归语言模型
python
# 预测下一个词
输入:"The cat sat"
目标:"on"
# 训练时并行计算所有位置的损失
损失 = Σ CrossEntropy(预测[i], 目标[i])
# 推理时自回归生成
generated = []
for i in range(max_len):
next_token = model.predict(generated)
generated.append(next_token)能力对比:
| 任务 | BERT | GPT |
|---|---|---|
| 文本分类 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 命名实体识别 | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| 问答 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| 文本生成 | ⭐ | ⭐⭐⭐⭐⭐ |
| 摘要 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 对话 | ⭐ | ⭐⭐⭐⭐⭐ |
实际应用:
BERT 擅长:
python
# 1. 分类
"This movie is great!" → Positive (0.95)
# 2. NER(命名实体识别)
"Apple was founded by Steve Jobs"
→ [Apple: ORG], [Steve Jobs: PER]
# 3. 问答
Context: "Paris is the capital of France."
Question: "What is the capital of France?"
Answer: "Paris" (span: [0, 5])GPT 擅长:
python
# 1. 文本生成
Prompt: "Once upon a time"
Output: "there was a brave knight..."
# 2. 对话
User: "How are you?"
GPT: "I'm doing well, thank you!"
# 3. 代码生成
Prompt: "Write a Python function to sort a list"
Output: "def sort_list(arr): return sorted(arr)"为什么BERT用双向,GPT用单向?
BERT:
目标是理解语言
双向能看到完整上下文
例如:"bank"(银行 vs 河岸)需要前后文判断
GPT:
目标是生成语言
必须单向,否则"作弊"
生成时只能看已生成的部分面试话术:
"BERT 是理解型模型,用双向Encoder + MLM训练,擅长分类、NER。GPT 是生成型模型,用单向Decoder + 自回归训练,擅长文本生成、对话。BERT看完整上下文理解语义,GPT逐个生成token。"
