扩展4 - 软注意力、硬注意力、自注意力机制简介
1 课程概览
本课介绍三种注意力机制:软注意力(Soft Attention)、硬注意力(Hard Attention)、自注意力机制(Self-Attention)。重点讲解注意力机制的本质思想:target 中每个单词是对 source 中每个单词的加权求和,权重反映 source 中每个单词对 target 中每个单词的重要程度。
2 核心概念与定义
- 软注意力(Soft Attention):给每个输入项分配 0~1 之间的权重,可微。
- 硬注意力(Hard Attention):只选择一个或几个输入项,权重为 0 或 1,不可微。
- 自注意力机制(Self-Attention):Q、K、V 都来自同一个序列。
- 加权求和:target 中每个单词是 source 中每个单词的加权求和。
- 重要程度:source 中每个单词对 target 中每个单词的重要程度。
3 模型与算法详解
注意力机制的本质思想
target 中每个单词是对 source 中每个单词的加权求和,权重是 source 中每个单词对 target 中每个单词的重要程度。
示例:翻译"汤姆"(target)
- source:Tom, chases, Jerry
- 权重:
[0.6, 0.2, 0.2](重要程度) - 加权求和:$0.6 \times V_{Tom} + 0.2 \times V_{chases} + 0.2 \times V_{Jerry}$
QKV 的作用
| 组件 | 作用 | 示例 |
|---|---|---|
| Q(Query) | 查询,当前要生成的词 | 翻译"汤姆" |
| K(Key) | source 中每个单词的标签 | Tom, chases, Jerry |
| V(Value) | source 中每个单词的词向量 | 各词的词向量 |
计算流程
- Q 与 K 算匹配分:$F(Q, K)$
- 匹配分 × V:得到最终结果
三种注意力机制对比
| 类型 | 权重 | 可微 | 特点 |
|---|---|---|---|
| 软注意力 | 0~1 之间 | 是 | 给每个输入项分配权重 |
| 硬注意力 | 0 或 1 | 否 | 只选择一个或几个输入项 |
| 自注意力 | 0~1 之间 | 是 | Q、K、V 来自同一序列 |
4 数学原理与推导
注意力公式
$$\text{Attention}(Q, \text{source}) = \sum_{i=1}^{L_x} \text{Similarity}(Q, K_i) \times V_i$$
其中:
- $Q$:查询
- $K_i$:source 中第 $i$ 个单词的标签
- $V_i$:source 中第 $i$ 个单词的词向量
- $L_x$:source 的长度
软注意力
$$\alpha_i = \text{softmax}(\text{score}(Q, K_i))$$ $$C = \sum_i \alpha_i V_i$$
硬注意力
$$\alpha_i = \begin{cases} 1 & i = \arg\max_i \text{score}(Q, K_i) \ 0 & \text{otherwise} \end{cases}$$ $$C = \sum_i \alpha_i V_i$$
自注意力
$$Q = K = V = X$$(来自同一序列) $$\text{Attention}(X) = \text{softmax}\left(\frac{XX^T}{\sqrt{d_k}}\right)X$$
5 代码示例
import torch
import torch.nn.functional as F
# 软注意力示例
def soft_attention(Q, K, V):
"""软注意力:权重在 0~1 之间"""
scores = torch.matmul(Q, K.T)
weights = F.softmax(scores, dim=-1)
output = torch.matmul(weights, V)
return output, weights
# 硬注意力示例
def hard_attention(Q, K, V):
"""硬注意力:权重为 0 或 1"""
scores = torch.matmul(Q, K.T)
# 选择得分最高的一个
max_idx = torch.argmax(scores, dim=-1)
weights = F.one_hot(max_idx, num_classes=K.size(0)).float()
output = torch.matmul(weights, V)
return output, weights
# 自注意力示例
def self_attention(X):
"""自注意力:Q=K=V=X"""
Q = K = V = X
scores = torch.matmul(Q, K.T)
weights = F.softmax(scores / (K.size(-1) ** 0.5), dim=-1)
output = torch.matmul(weights, V)
return output, weights
# 示例
Q = torch.tensor([[1.0, 0.0, 0.0]])
K = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
V = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
# 软注意力
output, weights = soft_attention(Q, K, V)
print("软注意力权重:", weights)
print("软注意力输出:", output)
# 硬注意力
output, weights = hard_attention(Q, K, V)
print("硬注意力权重:", weights)
print("硬注意力输出:", output)
# 自注意力
X = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
output, weights = self_attention(X)
print("自注意力权重:", weights)
print("自注意力输出:", output)
6 重难点与易错提醒
- ❗重点:注意力机制本质——target 中每个单词是 source 中每个单词的加权求和。
- ❗重点:权重反映 source 中每个单词对 target 中每个单词的重要程度。
- ⚠️易错:硬注意力不可微,需要强化学习训练。
- 💡深入理解:自注意力机制的 Q、K、V 来自同一序列。
- 💡深入理解:软注意力可微,可用反向传播训练。
7 课堂问答精选
Q1:注意力机制的本质思想是什么?
A:target 中每个单词是对 source 中每个单词的加权求和,权重是 source 中每个单词对 target 中每个单词的重要程度。
Q2:软注意力和硬注意力有什么区别?
A:软注意力给每个输入项分配 0~1 之间的权重,可微,可用反向传播训练;硬注意力只选择一个或几个输入项,权重为 0 或 1,不可微,需要强化学习训练。
Q3:自注意力机制的特点是什么?
A:自注意力机制的 Q、K、V 都来自同一个序列,用于捕捉序列内部的关系。
Q4:Q、K、V 分别是什么?
A:Q(Query)是查询,当前要生成的词;K(Key)是 source 中每个单词的标签;V(Value)是 source 中每个单词的词向量。用 Q 和 K 算匹配分,再乘以 V 得到最终结果。
8 本课小结
- 注意力本质:target = source 的加权求和。
- 权重 = source 对 target 的重要程度。
- 软注意力:权重 0~1,可微。
- 硬注意力:权重 0 或 1,不可微。
- 自注意力:Q=K=V 来自同一序列。
9 延伸思考
- 自注意力机制在 Transformer 中如何应用?
- 硬注意力如何用强化学习训练?