# 位置编码

位置编码是Transformer神经网络用来将词元顺序信息注入其表示的一类技术，因为自注意力本身将输入视为无序的向量集合。位置信息可以以嵌入的形式加到输入词元上，也可以作为对注意力矩阵本身的修改进入，已发表的方案分为绝对参照和相对参照两类。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup> 本文涵盖正弦编码与学习式绝对编码、基于偏置的相对编码与旋转相对编码，以及将基于RoPE的模型扩展到更长上下文的方法。

| 关键事实 | 详情 |
|---|---|
| 正弦编码 | \( \mathrm{PE}(pos, 2i) = \sin(pos / 10000^{2i/d_{\mathrm{model}}}) \)，\( \mathrm{PE}(pos, 2i+1) = \cos(pos / 10000^{2i/d_{\mathrm{model}}}) \)；波长从 \( 2\pi \) 到 \( 10000 \cdot 2\pi \) 构成等比数列 <sup>[2](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> |
| 平移性质 | 对任意固定偏移 \( k \)，\( \mathrm{PE}_{pos+k} \) 是 \( \mathrm{PE}_{pos} \) 的线性函数；在原始消融实验中，学习式嵌入产生了几乎相同的结果 <sup>[2](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> |
| 外推基线 | 正弦模型无法外推到训练长度 \( L \) 之外超过几十个词元；学习式嵌入不具备外推能力 <sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup> |
| ALiBi效率 | 一个在1024词元序列上训练的1.3B参数模型，其困惑度与在2048词元上训练的正弦模型相当，同时训练速度快11%、内存占用少11% <sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup> |
| T5偏置成本 | 查找表式相对偏置可使训练和推理耗时达到使用绝对位置嵌入的模型的近两倍 <sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> |
| RoPE基准波长 | 默认 \( \theta = 10{,}000 \)；在Llama 3及其他长上下文模型中增大至500,000 <sup>[5](https://arxiv.org/pdf/2410.06205)</sup> |
| 长上下文困惑度 | 在长度2048上训练、在8192上评估，FIRE达到21.24困惑度，而最佳基线（Kerple）为23.52 <sup>[6](https://sanjivk.com/FIRE_ICLR24.pdf)</sup> |

## 工作原理

自注意力层计算所有词元向量对之间的分数，因此置换输入会以相同方式置换输出；查询-键点积中没有任何东西能区分位置 \( i \) 和位置 \( j \)。位置编码在两个位置之一打破这种对称性：加到每个词元输入嵌入上的向量（绝对编码），或者加到注意力矩阵中的项、或在注意力矩阵内施加的变换。相对方案仅使用注意力矩阵途径，因为相对偏移是为位置对而非单个位置定义的。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup>

正弦编码是固定的，不是学出来的：编码的每一维是一条正弦曲线，其波长在各维之间按几何级数增长，因此邻近位置在快维度上不同，远距离位置在慢维度上不同。<sup>[2](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)</sup> 其点积具有一个有用的性质：对于嵌入 \( P_t \) 和 \( P_{t+r} \)，内积仅取决于相对距离 \( r \)，而与 \( t \) 无关，尽管它不感知方向。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup>

大多数基于偏置的相对方案都符合一种形式：注意力logits为 \( A_{\mathrm{RPE}}(X) = \frac{1}{\sqrt{d}}(X \cdot W_{Q})(X \cdot W_{K})^{\top} + B \)，其中 \( B \) 是由位置函数 \( b(i,j) \) 诱导的偏置矩阵；T5偏置、[ALiBi](https://www.edgepedia.org/zh/alibi)、Kerple和Sandwich都是其变体。<sup>[6](https://sanjivk.com/FIRE_ICLR24.pdf)</sup> RoPE则采用乘法而非加法：它按与绝对位置成比例的角度旋转查询向量和键向量的二维块，使得查询-键点积取决于它们之间的相对偏移。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup> 旋转角度为 \( g_{k} = \theta^{-2(k-1)/d} \)，其中 \( k = 1, \dots, d/2 \)，通过块对角旋转矩阵施加。<sup>[5](https://arxiv.org/pdf/2410.06205)</sup>

## 实现方式

**绝对编码**在输入层将位置向量加到每个词元嵌入上。学习式编码是每个位置索引对应一个向量的查找表；正弦编码根据上述方程计算向量，无需参数，适用于任意长度序列，且参数高效。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup>

**基于偏置的相对编码**从查询-键距离计算一个标量，并将其加到每个注意力分数上。ALiBi在查询-键点积之后加一个静态的、非学习的、各注意力头特定的偏置，即与距离成比例的线性递减惩罚，不同头使用从等比数列中取出的不同斜率；它完全消除了位置嵌入。<sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup><sup> • </sup><sup>[7](https://docs.nvidia.com/nemo-framework/user-guide/25.02/nemotoolkit/nlp/nemo_megatron/positional_embeddings.html)</sup> T5式偏置通过一个学习式查找表将距离映射为标量，超过阈值的所有距离共享一个参数。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

**RoPE**在每一层的点积之前旋转查询表示和键表示，角度与绝对位置成比例。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

**上下文扩展**修改已训练的RoPE模型而非架构。[位置插值](https://www.edgepedia.org/zh/position-interpolation)重新缩放位置索引，使其落入原始上下文窗口内。<sup>[7](https://docs.nvidia.com/nemo-framework/user-guide/25.02/nemotoolkit/nlp/nemo_megatron/positional_embeddings.html)</sup> NTK感知插值则改变RoPE基数 \( b \) 为 \( b' \)，将最低频率缩放至与线性插值相同的程度，同时保持最高频率不变。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> 动态NTK在每次前向传播时重新计算缩放因子 \( s = \max(1, l'/L) \)，其中 \( l' \) 是当前序列长度，从而使性能逐步下降而非突然崩溃。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> YaRN将NTK分段插值与查询向量和键向量上的温度因子相结合。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> LongRoPE通过进化搜索找到逐维插值因子 \( \lambda_{j} \)，在无需微调的情况下最小化困惑度。<sup>[9](https://openreview.net/attachment?id=9xuGBOrIW7&name=pdf)</sup>

## 起源

面向位置不敏感模型的学习式位置嵌入由格林（Gehring）及其同事（2017）在卷积序列到序列学习中引入。<sup>[10](https://doi.org/10.48550/arxiv.1705.03122)</sup> TUPE在注意力矩阵中解绑位置贡献和内容贡献，由柯（Ke）、何（He）和刘（Liu）（2020）提出。<sup>[11](https://doi.org/10.48550/arxiv.2006.15595)</sup> 旋转位置嵌入由苏（Su）及其同事在RoFormer（2021）中报告。<sup>[12](https://doi.org/10.48550/arxiv.2104.09864)</sup> ALiBi由普雷斯（Press）、史密斯（Smith）和刘易斯（Lewis）（2021）提出。<sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup> xPos是一种长度可外推的基于旋转的变体，由孙（Sun）及其同事（2022）报告。<sup>[13](https://doi.org/10.48550/arxiv.2212.10554)</sup> 位置插值由陈（Chen）及其同事（2023）报告。<sup>[14](https://doi.org/10.48550/arxiv.2306.15595)</sup> YaRN由彭（Peng）及其同事（2023）报告，<sup>[15](https://doi.org/10.48550/arxiv.2309.00071)</sup> 而将上下文扩展到200万词元以上的LongRoPE由丁（Ding）及其同事（2024）报告。<sup>[16](https://doi.org/10.48550/arxiv.2402.13753)</sup> FIRE由李（Li）及其同事（2023）报告。<sup>[6](https://sanjivk.com/FIRE_ICLR24.pdf)</sup> 仅解码器Transformer可以在没有显式编码的情况下工作这一NoPE发现，由卡泽姆内贾德（Kazemnejad）及其同事（2023）报告。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> TENER将相对、方向和距离感知的注意力适配用于命名实体识别（严（Yan）、邓（Deng）、李（Li）和邱（Qiu），2019）。<sup>[17](https://doi.org/10.48550/arxiv.1911.04474)</sup> 用于长度泛化的随机位置编码由鲁斯（Ruoss）及其同事（2023）报告，<sup>[18](https://doi.org/10.48550/arxiv.2305.16843)</sup> 而上下文位置编码（CoPE）——相对于显著词元计数位置——由戈洛夫涅娃（Golovneva）及其同事（2024）报告。<sup>[19](https://doi.org/10.48550/arxiv.2405.18719)</sup> 基于RoPE的外推缩放律由刘（Liu）及其同事（2023）报告，<sup>[20](https://doi.org/10.48550/arxiv.2310.05209)</sup> p-RoPE频率截断分析由巴尔贝罗（Barbero）及其同事（2024）报告。<sup>[5](https://arxiv.org/pdf/2410.06205)</sup>

## 变体

**学习式绝对嵌入**在模型实际学到的东西上与正弦嵌入表现不同。一个反转正弦映射的探针能完美恢复绝对位置，并以小误差恢复GPT-2的学习式嵌入，但BERT的学习式位置嵌入显示出极高的[平均绝对误差](https://www.edgepedia.org/zh/mean-absolute-error)，表明其编码器学到的绝对位置信息很少，主要是对掩码语言建模有用的局部位置信息。<sup>[21](https://aclanthology.org/2020.emnlp-main.555.pdf)</sup>

**相对编码**将位置信息附加到词元对上。Transformer-XL将Transformer与段级递归相结合以覆盖超出固定上下文的长序列，在其偏置项中使用正弦矩阵 \( R \) 和可学习参数 \( b \) 与 \( c \)。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup> T5偏置将距离分箱到查找表中，超过阈值则共享参数。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> 可学习相对嵌入必须考虑两倍的位置，因此训练和存储更多参数。<sup>[1](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)</sup>

**NoPE**从仅解码器模型中移除显式编码。理论上这样的模型可以表示绝对编码和相对编码，但当使用SGD训练时，其注意力模式最接近T5相对偏置，最不接近绝对编码和旋转编码。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

## 应用

已部署的模型沿这些家族分化：旋转编码用于PaLM和LLaMA，ALiBi用于BLOOM，学习式绝对嵌入用于GPT-3和OPT，其中无法为未见位置生成嵌入这一特性固定了上下文窗口长度。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> 在扩展方法中，[Code Llama](https://www.edgepedia.org/zh/code-llama)使用NTK感知插值（将RoPE基数缩放到100万），Qwen 7B使用动态NTK。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> NeMo/Megatron框架通过单一配置开关提供学习式绝对、RoPE、ALiBi、Kerple、xPos、Sandwich和T5相对等选项。<sup>[7](https://docs.nvidia.com/nemo-framework/user-guide/25.02/nemotoolkit/nlp/nemo_megatron/positional_embeddings.html)</sup>

## 局限与替代方案

**外推是比较的主要轴线。** 正弦编码和学习式编码在超出训练长度后失效，<sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup> 基于RoPE的语言模型对更长序列的泛化也很差。<sup>[6](https://sanjivk.com/FIRE_ICLR24.pdf)</sup> 存在一个理论保证：如果对应于相对位置编码指数的级数收敛，则Transformer保证可以外推，ALiBi、Kerple和Sandwich满足此条件。<sup>[22](https://ojs.aaai.org/index.php/AAAI/article/download/29855/31489)</sup> 已发表文献对ALiBi存在分歧：其作者报告在[WikiText-103](https://www.edgepedia.org/zh/wikitext-103)上困惑度改善至大约 \( 3L \)（而T5偏置约为 \( 2L \)），<sup>[3](https://arxiv.org/pdf/2108.12409v1)</sup> 而一项对推理和数学任务的系统研究发现ALiBi、旋转编码和绝对编码不太适合那里的长度泛化。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup> 同一研究发现NoPE在不增加计算的情况下优于显式编码。<sup>[4](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)</sup>

**扩展方法各有不同的权衡。** 位置插值微调在输出退化前仅达到大约 \( s = 8 \) 的缩放因子；NTK感知插值将某些维度外推到边界之外，微调结果劣于PI，但在不微调时效果更好。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup> YaRN以约为先前方法十分之一的计算量和五分之二的训练步数达到相当的扩展效果。<sup>[8](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)</sup>

**频率的作用很重要。** 在Gemma 7B中，最高的RoPE频率构建稳健的位置注意力模式，而最低频率携带语义信息；截断最低频率（p-RoPE）维持或改善验证困惑度，其中 \( p = 0 \) 与NoPE一致，\( p = 1 \) 与完整RoPE一致。<sup>[5](https://arxiv.org/pdf/2410.06205)</sup>

## References

1. [Position Information in Transformers: An Overview (Computational Linguistics 2022)](https://aclanthology.org/anthology-files/pdf/cl/2022.cl-3.7.pdf)
2. [Attention is All you Need](https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf)
3. [Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation (ALiBi)](https://arxiv.org/pdf/2108.12409v1)
4. [The Impact of Positional Encoding on Length Generalization in Transformers (NoPE)](https://proceedings.neurips.cc/paper_files/paper/2023/file/4e85362c02172c0c6567ce593122d31c-Paper-Conference.pdf)
5. [Round and Round We Go: What makes Rotary Positional Encodings useful? (p-RoPE)](https://arxiv.org/pdf/2410.06205)
6. [Functional Interpolation for Relative Positions Improves Long Context Transformers (FIRE, ICLR 2024)](https://sanjivk.com/FIRE_ICLR24.pdf)
7. [Positional embeddings, NVIDIA NeMo Framework User Guide](https://docs.nvidia.com/nemo-framework/user-guide/25.02/nemotoolkit/nlp/nemo_megatron/positional_embeddings.html)
8. [YaRN: Efficient Context Window Extension of Large Language Models (ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/file/874a4d89f2d04b4bcf9a2c19545cf040-Paper-Conference.pdf)
9. [S3PE: unified framework for positional encoding interpolation schemes](https://openreview.net/attachment?id=9xuGBOrIW7&name=pdf)
10. [Gehring, Jonas and colleagues (2017). Convolutional Sequence to Sequence Learning. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1705.03122)
11. [Ke, Guolin, He, Di, Liu, Tie-Yan (2020). Rethinking Positional Encoding in Language Pre-training. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2006.15595)
12. [Su, Jianlin and colleagues (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2104.09864)
13. [Sun, Yutao and colleagues (2022). A Length-Extrapolatable Transformer. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2212.10554)
14. [Chen, Shouyuan and colleagues (2023). Extending Context Window of Large Language Models via Positional Interpolation. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2306.15595)
15. [Peng, Bowen and colleagues (2023). YaRN: Efficient Context Window Extension of Large Language Models. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2309.00071)
16. [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)
17. [Yan, Hang and colleagues (2019). TENER: Adapting Transformer Encoder for Named Entity Recognition. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.1911.04474)
18. [Ruoss, Anian and colleagues (2023). Randomized Positional Encodings Boost Length Generalization of Transformers. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2305.16843)
19. [Golovneva, Olga and colleagues (2024). Contextual Position Encoding: Learning to Count What's Important. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2405.18719)
20. [Liu, Xiaoran and colleagues (2023). Scaling Laws of RoPE-based Extrapolation. arXiv (Cornell University).](https://doi.org/10.48550/arxiv.2310.05209)
21. [What Do Position Embeddings Learn? An Empirical Study of Pre-Trained Language Model Positional Encoding (EMNLP 2020)](https://aclanthology.org/2020.emnlp-main.555.pdf)
22. [Exploring Transformer Extrapolation (AAAI 2024)](https://ojs.aaai.org/index.php/AAAI/article/download/29855/31489)

---
*Initially written Sep 29, 2026 · Edited: Oct 15, 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/position-encoding

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