positional encoding 为什么需要?
有哪几种,各有什么区别?

英文问法How does positional encoding of a transformer work? · Why do we need it? · Absolute vs relative position encoding? · Sinusoidal vs learned vs ALiBi vs RoPE?

考过面经:NVIDIA DL 组("how does positional encoding of a transformer work",Reddit);他司:MSRA 2022 实习(「nlp中的位置编码,transformer如何编码,直接编码和间接编码…有什么区别」,牛客)、字节大模型实习(「lora调参,位置编码」,牛客)、Roblox MLE 2025 电面(Positional Encoding,一亩三分地)

先弄清楚:每个概念是什么

Permutation equivariance
把输入 token 打乱,输出只是跟着打乱。没有位置信息时,"狗咬人"和"人咬狗"里"狗"的表示一模一样。
Absolute 与 relative
absolute 像门牌号"我在第 5 位"。relative 像"他在我左边 2 位",整句往后挪几位也不变。
Sinusoidal
一组转速不同的钟表指针,快的区分相邻位置,慢的区分远距离,一个位置的编码就是所有指针的读数。例:\(d = 4\) 时位置 1 是 (sin 1, cos 1, sin 0.01, cos 0.01) = (0.841, 0.540, 0.010, 1.000)。
Extrapolation
推理时序列比训练时长,位置编码还能不能用。

30 秒回答

Self-attention is permutation-equivariant: shuffle the tokens and the outputs shuffle the same way, so without positions the model sees a bag of words. Absolute encodings add a vector to each input embedding: the original Transformer uses fixed sinusoids at geometrically spaced frequencies, and BERT learns one vector per position, which can't go beyond the trained length. Relative methods act inside every attention layer: T5 adds a learned bias per distance bucket, ALiBi subtracts a fixed per-head slope times the distance and extrapolates well, and RoPE rotates q and k so their dot product depends only on the offset. Most current open LLMs use RoPE.

关键公式

为什么需要:\(P\) 是任意置换矩阵

\[ \mathrm{Attn}(PX) = P\,\mathrm{Attn}(X) \]

Sinusoidal(加到输入 embedding 上)

\[ PE_{(pos,\,2i)} = \sin\big(pos/10000^{2i/d}\big) \] \[ PE_{(pos,\,2i+1)} = \cos\big(pos/10000^{2i/d}\big) \]

波长从 \(2\pi\) 到 \(10000\cdot 2\pi\) 等比增长,值域在 [−1, 1]。每对 (sin, cos) 平移 \(k\) 位等于旋转一个只和 \(k\) 有关的角度,所以 \(PE_{pos+k}\) 是 \(PE_{pos}\) 的线性函数,模型容易学相对位置。

ALiBi(加到每层 score 上,\(j \le i\))

\[ s_{ij} = q_i\cdot k_j - m\,(i - j) \]

\(m\) 每个 head 一个,固定不学,\(h\) 个 head 时是首项和公比都为 \(2^{-8/h}\) 的等比数列。例:8 个 head 是 1/2, 1/4, …, 1/256,slope 1/2 的 head 里距离 3 的 key 被减 1.5。

RoPE

按位置旋转 q、k,\(\langle R_m q, R_n k\rangle\) 只依赖 \(n - m\)。见 RoPE。

几种做法对比

方法作用在哪参数外推例子
sinusoidal加到输入无理论上可以,实测很弱原版 Transformer
learned加到输入每个位置一个向量不能超过训练长度BERT(512)
relative bias每层 score每个距离桶一个标量较好,但训练至少慢一倍T5(32 桶)
ALiBi每层 score无(slope 固定)好:train 1024 → test 2048BLOOM
RoPE每层的 q、k无比 sinusoidal 好,但有限LLaMA

必答点

追问

learned 和 sinusoidal 哪个好?

原论文 Table 3 (E) 里几乎一样(BLEU 25.7 vs 25.8)。选 sinusoidal 是希望能外推到更长的序列。

ALiBi 为什么能外推?

它没有 position embedding,更长的距离只是罚得更多(recency bias),不会出现训练没见过的向量。

来源Vaswani et al. 2017 §3.5(p.6)、Table 3 row (E)(p.9)· Dive into Deep Learning §11.6.3 eq. 11.6.2–11.6.3 · Press et al. 2022(ALiBi) Abstract、§2(pp.3–4)、§3(p.5)· Raffel et al. 2020(T5) §2.1(p.5)· Su et al.(RoFormer) §3.2.2 eq. 14–16(p.5)· Devlin et al. 2019(BERT) Appendix A.2(p.13)· BigScience 2022(BLOOM) §3.2.3(p.16)· Touvron et al. 2023(LLaMA) §2.2(p.3)· Haviv et al. 2022(NoPE) Abstract