解析Transformer位置编码演进,揭示长上下文处理的关键机制。
Position Encoding in Transformers: From Absolute and Relative Methods to Rotary Position Embeddings and Long-Context Scaling
- 提出统一框架,对比绝对、相对与旋转位置编码的原理与设计差异。
- 发现训练长度外的位置推断不等于可靠长文本理解,需多维度验证。
- 详解多种长序列扩展技术,适合大模型研发与系统优化人员阅读。
自注意力机制虽能捕捉词元间内容依赖关系,但无法自动编码顺序信息。位置编码通过引入绝对坐标、相对距离或位置相关旋转来补充这一缺陷。本文系统梳理正弦与可学习的绝对位置嵌入、Shaw风格的相对位置表示、Transformer-XL、T5相对偏置、ALiBi及旋转位置编码(RoPE)等方法,推导出RoPE如何将绝对位置转为查询-键内积中的相对相位差。从位置注入方式、计算开销、KV缓存兼容性、长度外推能力等方面进行比较。进一步分析长上下文扩展技术:位置插值、RoPE缩放律、NTK感知缩放、动态NTK、NTK分部法、YaRN、LongRoPE与LongRoPE2,重点考察频率分配、注意力重缩放、训练长度与目标上下文长度的关系。还总结了主流大模型中的实现细节、评估协议与位置编码选择策略。核心结论是:在训练长度之外计算位置特征,并不保证可靠的长上下文泛化;上下文扩展必须通过短上下文保留率、逐位置困惑度、检索、推理及长代码任务等综合评估。
原文摘要 · Abstract (English)
Self-attention models content-dependent interactions between tokens but does not by itself encode token order. Position encoding addresses this limitation by introducing absolute coordinates, relative distances, or position-dependent rotations into Transformer representations and attention scores. This technical survey develops a unified account of sinusoidal and learned absolute position embeddings, Shaw-style relative position representations, Transformer-XL, T5 relative position bias, ALiBi, and Rotary Position Embeddings (RoPE). We derive how RoPE converts absolute position indices into relative phase differences in Query-Key inner products and compare these methods in terms of where position is injected, computational cost, compatibility with KV caching, and length extrapolation. We then examine long-context extensions, including Position Interpolation, RoPE scaling laws, NTK-aware scaling, Dynamic NTK, NTK-by-parts, YaRN, LongRoPE, and LongRoPE2, with emphasis on frequency allocation, attention rescaling, training length, and target context length. We also summarize implementation considerations, evaluation protocols, and position-encoding choices in representative large language models. A central conclusion is that the ability to compute positional features beyond the training length does not imply reliable long-context generalization; context extension must be evaluated through short-context retention, position-wise perplexity, retrieval, reasoning, and long-context code tasks.
Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。