# 位置编码

位置编码是一类技术的统称，用于将词元或元素的顺序信息注入神经网络的输入或注意力计算中，最典型的应用是 [Transformer](https://www.edgepedia.org/zh/transformer) 模型——其自注意力机制本身无法区分序列位置。由于注意力机制将其输入视为一个集合，在没有位置信息的情况下具有置换等变性：对输入词进行置换，输出表示也会发生相同的置换。<sup>[18](https://d2l.smola.org/chapter_attention/positional-information.html)</sup>

| 关键事实 | 内容 |
|---|---|
| 所解决的问题 | 自注意力具有置换等变性，因此必须显式注入词元顺序<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> |
| 原始方案 | 正弦编码，波长从 \( 2\pi \) 到 \( 10000 \cdot 2\pi \)<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> |
| 学习式替代方案 | 在 2017 年基础模型中，学习式位置嵌入与正弦编码的结果几乎相同<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> |
| 外推能力 | ALiBi 在 1024 词元上训练，即可匹配在 2048 词元上训练的正弦模型，同时训练速度快 11%、内存占用少 11%<sup>[2](https://arxiv.org/pdf/2108.12409)</sup> |
| 主流大语言模型选择 | 旋转位置嵌入（RoPE），用于 PaLM 和 LLaMA<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> |
| 出人意料的结果 | 无位置编码（NoPE）的纯解码器 Transformer 在长度泛化上匹配甚至超越显式方案<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> |
| 长上下文扩展 | 相较于先前方法，YaRN 扩展 RoPE 模型仅需十分之一的词元和五分之二的训练步数<sup>[4](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> |

## 工作原理

自注意力计算查询向量与键向量之间的交互，其中不含任何依赖于词元在序列中位置的项；它是一种集合运算，具有置换等变性，因此若不引入位置信息，许多词元之间的关系无法确定。<sup>[5](https://github.com/huggingface/blog/blob/main/designing-positional-encoding.md)</sup> 2017 年的 Transformer 完全移除了循环和卷积，因此论文指出必须将词元的相对或绝对位置信息注入输入。<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> 带因果掩码的纯解码器模型是部分例外：它们并非置换不变，可以在没有显式位置信息的情况下对序列建模，因为掩码本身打破了对称性。<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

各方案的区别在于位置信号的注入位置：加到输入嵌入上（绝对方案）、作为查询-键距离的函数插入注意力分数中（相对方案）、作为旋转施加到查询和键上（RoPE），或作为距离惩罚从注意力分数中减去（ALiBi）。

## 实现方式

**正弦编码。** 对于位置 \( pos \) 和维度对 \( i \)，模型宽度为 \( d_{\mathrm{model}} \)<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup>：

\[ PE_{(pos, 2i)} = \sin\left( pos / 10000^{2i/d_{\mathrm{model}}} \right), \qquad PE_{(pos, 2i+1)} = \cos\left( pos / 10000^{2i/d_{\mathrm{model}}} \right) \]

每个维度是一条正弦曲线；波长构成从 \( 2\pi \) 到 \( 10000 \cdot 2\pi \) 的等比数列。对于任意固定偏移 \( k \)，\( PE_{(pos+k)} \) 是 \( PE_{(pos)} \) 的线性函数，因此模型可以学会按相对位置进行注意力分配。每个频率对的移位变换恰好是一个旋转矩阵，这意味着正弦方案已经将相对位置编码为旋转。

**学习式绝对嵌入。** 为每个位置学习一个可训练的嵌入向量，加到词元嵌入上。在原始基础模型中，该方案困惑度为 4.92、BLEU 为 25.7，与正弦版本几乎相同。<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup>

**相对方案。** Shaw、Uszkoreit 和 Vaswani 将元素间距离的学习式表示（截断到最大绝对值 \( k \)，共 \( 2k+1 \) 个标签）加入注意力分数<sup>[6](https://aclanthology.org/N18-2074.pdf)</sup>：

\[ e_{ij} = \left( x_i W^{Q} (x_j W^{K})^{\top} + x_i W^{Q} (a^{K}_{ij})^{\top} \right) / \sqrt{d_z} \]

[Transformer-XL](https://www.edgepedia.org/zh/transformer-xl) 则用无参数的相对正弦函数 \( R_{i-j} \) 替代绝对键嵌入，并加入可训练的全局偏置 \( u \) 和 \( v \)。<sup>[7](https://aclanthology.org/P19-1285.pdf)</sup>

**RoPE。** 每个查询和键按其绝对位置旋转一个正比于该位置的角度，因此内积仅取决于内容和相对偏移：\( \langle f_{q}(x_{m}, m), f_{k}(x_{n}, n) \rangle = g(x_{m}, x_{n}, m-n) \)，频率为 \( \theta_{i} = 10000^{-2i/d} \)，随着相对距离增大，内积呈现长期衰减。<sup>[8](https://arxiv.org/pdf/2104.09864)</sup>

**ALiBi。** 不添加任何嵌入；从每个注意力分数中减去一个随查询-键距离线性增长的标量偏置，各注意力头的斜率构成等比数列（8 头模型为 \( 1/2^{1} \) 到 \( 1/2^{8} \)）。<sup>[2](https://arxiv.org/pdf/2108.12409)</sup>

## 起源

正弦方案和学习式绝对方案均出现在《Attention Is All You Need》中，这是首个完全基于注意力的序列转导模型。<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> 相对位置表示用于自注意力。<sup>[6](https://aclanthology.org/N18-2074.pdf)</sup> Transformer-XL 于 2019 年将段级循环与其相对正弦方案相结合。<sup>[7](https://aclanthology.org/P19-1285.pdf)</sup> RoPE 由 Su 及其同事在 2021 年的 RoFormer 论文中提出<sup>[8](https://arxiv.org/pdf/2104.09864)</sup>，ALiBi 由 Press、Smith 和 Lewis 于 2021 年提出。<sup>[2](https://arxiv.org/pdf/2108.12409)</sup>

## 变体

除主要方案外，若干研究路线对其权衡进行了改进。随机位置编码（Stochastic Positional Encoding，Liutkus 及同事，2021）通过将位置与相关高斯过程的互协方差结构关联，生成可证明具有相对编码行为的编码，并适用于线性注意力。<sup>[9](https://proceedings.mlr.press/v139/liutkus21a/liutkus21a.pdf)</sup> KERPLE（Chi 及同事，2022）将相对位置嵌入核化以实现长度外推。<sup>[10](https://doi.org/10.48550/arxiv.2205.09921)</sup> TENER（Yan、Deng、Li 和 Qiu，2019）将 Transformer 注意力适配于命名实体识别<sup>[11](https://doi.org/10.48550/arxiv.1911.04474)</sup>，CAPE（Likhomanenko 及同事，2021）用连续增强嵌入编码相对位置。<sup>[12](https://doi.org/10.48550/arxiv.2106.03143)</sup> Haviv 及同事于 2022 年表明，无位置编码的 Transformer 语言模型仍能学到位置信息<sup>[13](https://doi.org/10.48550/arxiv.2203.16634)</sup>，预示了 NoPE 路线。在长上下文方面，位置插值微调在缩放因子约 \( s = 8 \) 以上时性能退化；NTK 感知缩放则通过高频少缩放、低频多缩放，将插值压力分散到各维度，[Code Llama](https://www.edgepedia.org/zh/code-llama) 采用此方法将 RoPE 基数手动缩放至 1M，称之为 RoPE“调整基频”（ABF）；动态 NTK 无需微调即可应用此方法；YaRN 将分段 NTK 插值与查询和键的温度缩放相结合，推理零开销。<sup>[4](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> LongRoPE（Ding 及同事，2024）将上下文推至 200 万词元以上。<sup>[14](https://doi.org/10.48550/arxiv.2402.13753)</sup>

## 应用

原始正弦/学习式方案支撑了 2017 年的翻译结果（WMT 2014 英德翻译 BLEU 28.4）。<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> RoPE 用于 PaLM 和 LLaMA；ALiBi 用于 BLOOM。<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> RoPE 的乘法式保范数形式还为线性注意力 Transformer 提供了相对位置能力，而线性注意力架构本身无法提供这一组合。<sup>[15](https://doi.org/10.48550/arxiv.2006.16236)</sup> 为实现公平比较，1B 规模的纯解码器代码模型在相同配置下分别用 NoPE、Rotary 和 ALiBi 在 30B 词元上预训练，并已公开发布。<sup>[16](https://github.com/McGill-NLP/length-generalization)</sup>

## 局限与替代方案

**外推是比较的主要维度，已发表的比较结果不一。** 2017 年的作者选择正弦函数，是因为它们可能允许外推到更长的序列<sup>[1](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup>，但 ALiBi 论文的语言建模实验发现正弦嵌入无法外推超过训练长度 \( L \) 几十个词元<sup>[2](https://arxiv.org/pdf/2108.12409)</sup>；最初的论断是假设，后来的结果是实证测量。在 [WikiText-103](https://www.edgepedia.org/zh/wikitext-103) 上，ALiBi 的困惑度至少在序列长度增至约 \( 3L \) 时仍持续改善，而 T5 偏置基线只能持续改善至约 \( 2L \)。<sup>[2](https://arxiv.org/pdf/2108.12409)</sup> Transformer-XL 以注意力长度 128 训练，在 640 上评估。<sup>[7](https://aclanthology.org/P19-1285.pdf)</sup>

**成本。** Shaw 的相对方案使每秒步数下降 7%<sup>[6](https://aclanthology.org/N18-2074.pdf)</sup>，但 T5 式相对偏置可使训练和推理耗时接近使用绝对嵌入时的两倍<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>；早期 RPE 的空间复杂度为 \( O(N^{2} \cdot D) \)，后来降至 \( O(N^{2}) \)，且所有此类变体都需要显式注意力矩阵，而线性注意力模型无法提供。<sup>[9](https://proceedings.mlr.press/v139/liutkus21a/liutkus21a.pdf)</sup>

**NoPE。** 在推理和数学任务上，无位置编码的纯解码器 Transformer 在长度泛化方面与最佳显式方案（T5 的相对偏置）持平或更优，且无额外成本，而 ALiBi、Rotary 和 APE 不太适合下游任务中的长度泛化。<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> NoPE 理论上可以表示绝对和相对编码，但用 SGD 训练时其注意力模式大多类似于 T5 的相对方案。<sup>[3](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

DeepMind 最近的一项结果还发现，训练后的 Gemma 7B 模型主要使用最低的 RoPE 频率，截断这些频率可以保持甚至提升性能。<sup>[17](https://arxiv.org/html/2410.06205v1)</sup>

## References

1. [Attention Is All You Need (NeurIPS 2017)](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)
2. [Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation (ALiBi, Press et al.)](https://arxiv.org/pdf/2108.12409)
3. [The Impact of Positional Encoding on Length Generalization in Transformers (Kazemnejad et al., NeurIPS 2023)](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)
4. [YaRN: Efficient Context Window Extension of Large Language Models (Peng et al., ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)
5. [Designing positional encoding (Hugging Face blog)](https://github.com/huggingface/blog/blob/main/designing-positional-encoding.md)
6. [Self-Attention with Relative Position Representations (Shaw, Uszkoreit, Vaswani, NAACL 2018)](https://aclanthology.org/N18-2074.pdf)
7. [Transformer-XL: Attentive Language Models beyond a Fixed-Length Context (Dai et al., ACL 2019)](https://aclanthology.org/P19-1285.pdf)
8. [RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)](https://arxiv.org/pdf/2104.09864)
9. [Relative Positional Encoding for Transformers with Linear Complexity (SPE, Liutkus et al., ICML 2021)](https://proceedings.mlr.press/v139/liutkus21a/liutkus21a.pdf)
10. [Chi, Ta-Chung and colleagues (2022). KERPLE: Kernelized Relative Positional Embedding for Length Extrapolation. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2205.09921)
11. [Yan, Hang and colleagues (2019). TENER: Adapting Transformer Encoder for Named Entity Recognition. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1911.04474)
12. [Likhomanenko, Tatiana and colleagues (2021). CAPE: Encoding Relative Positions with Continuous Augmented Positional Embeddings. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2106.03143)
13. [Haviv, Adi and colleagues (2022). Transformer Language Models without Positional Encodings Still Learn Positional Information. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2203.16634)
14. [Ding, Yiran and colleagues (2024). LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2402.13753)
15. [Katharopoulos, Angelos and colleagues (2020). Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2006.16236)
16. [McGill-NLP/length-generalization (code and 1B-scale pretrained models)](https://github.com/McGill-NLP/length-generalization)
17. [2410.06205v1 (arxiv.org)](https://arxiv.org/html/2410.06205v1)
18. [10.4 Positional Information, Dive into Deep Learning](https://d2l.smola.org/chapter_attention/positional-information.html)

---
*Initially written Sep 29, 2026 · Reviewed: Sep 30, 2026 · Edited: Sep 30, 2026 · Last review: Sep 30, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 现代人工智能：基础模型、生成式人工智能与人工智能产业 › Foundation-model methods and training › Large language model architecture and scaling

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/positional-encoding

English original: https://www.edgepedia.org/positional-encoding
