多头:分别取信息,再合并

以论文的 base 配置为例:模型宽度为 512,共 8 个注意力头,每个头的键和值宽度均为 64。

多头注意力的并行投影与合并八组独立投影分别计算注意力,沿特征维拼接,再通过输出矩阵混合。图中仅展开头 1 与头 8。输入序列
X∈Rn×512X\in\mathbb{R}^{n\times512}
注意力头 1
W1Q,  W1K,  W1VW_1^Q,\;W_1^K,\;W_1^V
512⟶64512\longrightarrow64
注意力头 8
W8Q,  W8K,  W8VW_8^Q,\;W_8^K,\;W_8^V
512⟶64512\longrightarrow64
注意力权重
A1=softmax⁡ ⁣(Q1K1T8)A_1=\operatorname{softmax}\!\left(\frac{Q_1K_1^{\mathsf T}}{8}\right)
注意力权重
A8=softmax⁡ ⁣(Q8K8T8)A_8=\operatorname{softmax}\!\left(\frac{Q_8K_8^{\mathsf T}}{8}\right)
head⁡1=A1V1\operatorname{head}_1=A_1V_1
n×64n\times64
head⁡8=A8V8\operatorname{head}_8=A_8V_8
n×64n\times64
拼接各头输出
Concat⁡(head⁡1,…,head⁡8)\operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_8)
n×(8⋅64)=n×512n\times(8\cdot64)=n\times512
输出投影
WO∈R512×512W^O\in\mathbb{R}^{512\times512}
输出:  n×512\text{输出:}\;n\times512
多头注意力的并行投影与合并八组独立投影分别计算注意力,沿特征维拼接,再通过输出矩阵混合。图中仅展开头 1 与头 8。输入序列
X∈Rn×512X\in\mathbb{R}^{n\times512}
注意力头 1
W1Q,  W1K,  W1VW_1^Q,\;W_1^K,\;W_1^V
512⟶64512\longrightarrow64
注意力头 8
W8Q,  W8K,  W8VW_8^Q,\;W_8^K,\;W_8^V
512⟶64512\longrightarrow64
注意力权重
A1=softmax⁡(S1)A_1=\operatorname{softmax}(S_1)
S1=Q1K1T8S_1=\frac{Q_1K_1^{\mathsf T}}{8}
注意力权重
A8=softmax⁡(S8)A_8=\operatorname{softmax}(S_8)
S8=Q8K8T8S_8=\frac{Q_8K_8^{\mathsf T}}{8}
head⁡1=A1V1\operatorname{head}_1=A_1V_1
n×64n\times64
head⁡8=A8V8\operatorname{head}_8=A_8V_8
n×64n\times64
拼接各头输出
Concat⁡(head⁡1,…,head⁡8)\operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_8)
n×(8⋅64)=n×512n\times(8\cdot64)=n\times512
输出投影
WO∈R512×512W^O\in\mathbb{R}^{512\times512}
输出:  n×512\text{输出:}\;n\times512

读图重点:分支表示并行计算,不是沿着 head 编号依次执行。各头独立做 softmax,之后才拼接。图中折叠 head 2 至 7,仅展开 head 1 与 head 8。

播放控件显示当前步骤。键盘 ← / → 切换步骤,Home / End 查看起点和终点。