从一个例子开始
想象我们要翻译这句话:“The cat sat on the mat”。
在处理 “sat” 这个词时,Self-Attention 让模型能够”看到”句子中所有相关的词——“cat” 是主语,“on” 和 “mat” 是位置信息。
Self-Attention 四步走
Step 1: 创建 Q、K、V 向量
每个输入 token 通过三个不同的线性变换,生成 Query、Key 和 Value 向量。
输入: "The cat sat on the mat" (6 个 tokens)
Q = Input × W_Q → (6, d_k) 矩阵
K = Input × W_K → (6, d_k) 矩阵
V = Input × W_V → (6, d_v) 矩阵
Step 2: 计算注意力分数
scores = Q @ K.T / sqrt(d_k) # (6, 6) 矩阵
# scores[i][j] = token i 对 token j 的"关注度"
Step 3: Softmax 归一化
attention_weights = softmax(scores, dim=-1)
# 每一行的权重和为 1
Step 4: 加权求和
output = attention_weights @ V # (6, d_v)
# 对每个 token,将其关注的 Value 向量加权求和
Multi-Head 并行
多头注意力就是同时做多组 Q-K-V 变换,每组关注不同的特征子空间:
- Head 1 可能关注句法关系
- Head 2 可能关注语义关联
- Head 3 可能关注位置邻近性
参考 Transformer 架构详解 和 注意力机制深入理解 获取更深入的理论讲解。