🧠 图解记忆:多头在不同子空间看关系,最后合并;点击图片可查看原图。
💡 答案要点
Multi-Head Attention = 多个Self-Attention并行,捕捉不同类型的关系
为什么需要多头?
单头的局限:
单个注意力头只能学习一种模式
例如:
"我 爱 吃 苹果"
单头可能只关注:
语法关系:"我" ← "爱"(主谓)
但错过了:
语义关系:"吃" ← "苹果"(动宾)
共指关系:"我" → "我"(指代)多头的优势:
8个头可以学习不同的模式:
Head 1: 语法关系(主谓宾)
Head 2: 语义关系(实体-动作)
Head 3: 位置关系(相邻词)
Head 4: 长程依赖(句首-句尾)
...
Head 8: 其他模式架构:
展开 Python 代码示例(46 行)
python
class MultiHeadAttention:
def __init__(self, d_model=512, num_heads=8):
self.num_heads = num_heads
self.d_k = d_model // num_heads # 64
# 每个头有独立的 Q、K、V 权重
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, Q, K, V, mask=None):
batch_size = Q.size(0)
# 1. 线性变换并分头
# (batch, seq_len, d_model) → (batch, seq_len, num_heads, d_k)
Q = self.W_Q(Q).view(batch_size, -1, self.num_heads, self.d_k)
K = self.W_K(K).view(batch_size, -1, self.num_heads, self.d_k)
V = self.W_V(V).view(batch_size, -1, self.num_heads, self.d_k)
# 转置以并行计算多头
# (batch, num_heads, seq_len, d_k)
Q = Q.transpose(1, 2)
K = K.transpose(1, 2)
V = V.transpose(1, 2)
# 2. 每个头独立计算注意力
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention = F.softmax(scores, dim=-1)
output = torch.matmul(attention, V)
# 3. 合并多头
# (batch, num_heads, seq_len, d_k) → (batch, seq_len, d_model)
output = output.transpose(1, 2).contiguous()
output = output.view(batch_size, -1, self.num_heads * self.d_k)
# 4. 输出投影
output = self.W_O(output)
return output可视化示例(8个头):
输入:"The cat sat on the mat"
Head 1(主语-谓语):
cat → sat (0.9)
Head 2(谓语-宾语):
sat → mat (0.8)
Head 3(修饰关系):
the → cat (0.7)
the → mat (0.6)
Head 4(位置关系):
on → the (0.9)
...
最终输出 = Concat(Head1, Head2, ..., Head8) @ W_O参数对比:
| 方案 | 参数量 | 表达能力 |
|---|---|---|
| 单头(d_model=512) | 512² × 3 = 786K | 低 |
| 8头(d_k=64) | 512² × 3 + 512² = 1.05M | 高 |
实验证明(BLEU分数,机器翻译):
| 头数 | BLEU | 说明 |
|---|---|---|
| 1 | 25.8 | 单头 |
| 2 | 26.4 | +0.6 |
| 4 | 27.1 | +1.3 |
| 8 | 27.3 | 最佳 |
| 16 | 27.2 | 过多反而下降 |
面试话术:
"Multi-Head Attention让模型同时学习多种注意力模式。8个头可以分别关注语法、语义、位置等不同维度的关系。虽然参数量略增,但表达能力大幅提升。实验表明8头是最佳选择。"
