🧠 图解记忆:Encoder 看全局,Decoder 只看过去并逐步生成;点击图片可查看原图。
💡 答案要点
核心区别:Encoder是双向的,Decoder是单向的
Encoder(编码器):
python
# Encoder 结构(重复N次,通常N=6)
for layer in range(N):
# 1. Multi-Head Self-Attention
# 可以看到整个输入序列(双向)
attn_output = MultiHeadAttention(
Q=x, K=x, V=x # Query、Key、Value 都来自输入
)
x = LayerNorm(x + attn_output) # 残差 + 归一化
# 2. Feed-Forward Network
ffn_output = FeedForward(x)
x = LayerNorm(x + ffn_output)特点:
- ✅ 双向注意力(可以看到前后文)
- ✅ 并行处理所有token
- ✅ 输出:编码后的表示(上下文向量)
Decoder(解码器):
python
# Decoder 结构(重复N次,通常N=6)
for layer in range(N):
# 1. Masked Multi-Head Self-Attention
# 只能看到当前及之前的token(单向)
masked_attn = MaskedMultiHeadAttention(
Q=y, K=y, V=y, # 来自目标序列
mask=causal_mask # 上三角mask
)
y = LayerNorm(y + masked_attn)
# 2. Encoder-Decoder Cross-Attention
# Query来自Decoder,Key和Value来自Encoder输出
cross_attn = MultiHeadAttention(
Q=y, # 来自 Decoder
K=encoder_output, # 来自 Encoder
V=encoder_output # 来自 Encoder
)
y = LayerNorm(y + cross_attn)
# 3. Feed-Forward Network
ffn_output = FeedForward(y)
y = LayerNorm(y + ffn_output)特点:
- ⚠️ 单向注意力(Masked,只能看之前的)
- ✅ 包含Cross-Attention(连接Encoder和Decoder)
- ⚠️ 自回归生成(逐个token生成)
关键差异对比:
| 维度 | Encoder | Decoder |
|---|---|---|
| Self-Attention | 双向(无mask) | 单向(有mask) |
| Cross-Attention | ❌ 无 | ✅ 有(连接Encoder) |
| 输入 | 源序列(如英文) | 目标序列(如中文) |
| 输出 | 编码表示 | 生成序列 |
| 应用 | BERT(仅Encoder) | GPT(仅Decoder) |
Mask 机制详解:
# Encoder: 无mask,所有token都能互相看到
Input: [I, love, AI]
Attention Matrix:
I love AI
I ✓ ✓ ✓
love ✓ ✓ ✓
AI ✓ ✓ ✓
# Decoder: Causal Mask,只能看当前及之前
Input: [我, 喜欢, 人工智能]
Attention Matrix:
我 喜欢 人工智能
我 ✓ ✗ ✗
喜欢 ✓ ✓ ✗
人工智能 ✓ ✓ ✓面试话术:
"Encoder用双向Self-Attention理解输入,Decoder用单向Masked Attention生成输出。Decoder还有Cross-Attention层,让生成的每个token都能关注Encoder的所有输出。BERT只用Encoder(理解任务),GPT只用Decoder(生成任务)。"
