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 2048 | BLOOM |
| RoPE | 每层的 q、k | 无 | 比 sinusoidal 好,但有限 | LLaMA |
必答点
- 为什么:self-attention 是 permutation equivariant,不加位置 = bag of words
- absolute:sinusoidal(固定、多频率)、learned(不能超过训练长度),加在输入
- relative:T5 bias、ALiBi 加在每层 score 上;RoPE 旋转每层的 q、k
- 外推:learned 不能,sinusoidal 很弱,ALiBi 好;现在的 LLM 多用 RoPE
追问
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