计算机

位置编码

参考:

自注意力的置换等变

自注意力定义参考:Attention 注意力机制

为什么 Transformer 需要正弦编码?因为 self-attention 自带的自注意力机制。

对于任意的参数矩阵,self-attention 拥有置换等变性。对于一个输入的词向量序列 (x_1, \dots, x_n)(也就是行分块的输入矩阵 X = \begin{bmatrix} x_1 \\ \vdots \\ x_n \end{bmatrix}),W_Q, W_K, W_V 为其参数。注意到 self-attention 的计算公式为:

f(X) = \operatorname{rowwise-softmax}\left( (X W_Q)(X W_K)^{\mathrm{T}} \right) X W_V

其输出行分块后,同样是一个序列 (y_1, \dots, y_n)。

改变输入的顺序,可以视为对输入矩阵 X 行的调换顺序,这等价于左乘一个置换矩阵 P,则新的输入矩阵是 X' = PX,softmax 内的计算变为

(P X W_Q)(P X W_K)^{\mathrm{T}} = P (X W_Q)(X W_K)^{\mathrm{T}} P^{\mathrm{T}}.

注意这里的 softmax 是逐行 softmax,显然先交换行顺序、再逐行运算,与先逐行运算、再交换行顺序的效果是一致的,因此:

\operatorname{rowwise-softmax}(PA) = P\operatorname{rowwise-softmax}(A).

再分析一行内交换顺序的影响,由于 softmax 的计算公式为:

\operatorname{softmax}(x_1, \dots, x_n) = \frac{1}{e^{x_1} + \cdots + e^{x_n}} (e^{x_1}, \dots, e^{x_n}),

它可以表示为一个逐元素指数运算,和一个求和后缩放的复合。交换元素顺序不影响求和,而先逐元素操作、再交换列顺序,与先交换列顺序,再逐元素操作的效果是一致的,于是右乘的置换矩阵也可以提取,即:

\operatorname{rowwise-softmax}(A P^{\mathrm{T}}) = \operatorname{rowwise-softmax}(A) P^{\mathrm{T}}.

两者合并,我们得到:

\operatorname{rowwise-softmax}(PAP^{\mathrm{T}}) = P \cdot \operatorname{rowwise-softmax}(A) P^{\mathrm{T}}

于是自注意力整体的计算为:

\begin{aligned} f(PX) &= \operatorname{rowwise-softmax}(P (X W_Q)(X W_K)^{\mathrm{T}}P^{\mathrm{T}} ) P X W_V \\ &= P \cdot \operatorname{rowwise-softmax}((X W_Q)(X W_K)^{\mathrm{T}}) P^{\mathrm{T}} P X W_V \\ &= P \cdot \operatorname{rowwise-softmax}((X W_Q)(X W_K)^{\mathrm{T}}) X W_V = Pf(X). \end{aligned}

这说明自注意力的计算拥有置换等变性,改变输入的顺序后,输出的顺序也会一致地改变。模型只能学习到任意两个输入之间的关系,而无法感知到 x_i 和 x_j 在序列中的距离。换句话说,现在的 self-attention 中,一个词向量的“近在咫尺”位置的词向量和“远在天涯”位置的词向量效果是一样的。

正弦位置编码

由《Attention is all you need》提出。

旋转位置编码

简称 RoPE,是截至目前(2025.10)在 LLM 中最常用的编码方法。

参考:

绝对位置编码与相对位置编码

正弦位置编码是一种绝对位置编码,而 RoPE 是一种相对位置编码。

BEYOND THE ARTICLE

读完了,有什么想法?

阅读已保存的问答示例,并循着引用回到原文。

查看公开问答示例
— 本文完 — 返回文章列表