位置信息表示:可学习编码、正弦编码与旋转位置编码 (RoPE)
Agent 辅助工程分析
前置要求
第 43 日自注意力与第 47 日 Transformer 模块堆叠。
学习目标
解释为何在无位置信息时自注意力具有排列等变性,对比可学习绝对编码、正弦绝对编码与旋转位置编码 (RoPE)。
操作指引
证明调换词元 1 与词元 2 将导致无位置编码的自注意力输出发生等变交换。定义加性位置编码 x = tok_emb + pos_emb,并对比 RoPE 在复数平面上的乘性旋转机制。
自主演练与记录
1. 证明朴素点积注意力具有排列等变性。
2. GPT-2 如何将位置向量注入到词元嵌入中?
3. RoPE 相比可学习绝对位置编码具有什么关键的外推优势?
置换矩阵 P 满足 (P Q)(P K)^T = P (Q K^T) P^T,注意力权重随输入等变置换,无法感知语序。
排列等变性:没有位置编码时,注意力机制无法区分语序。GPT-2 采用加性可学习编码:x_t = C[tok_t] + W_pos[t]。RoPE 通过将 Q、K 向量以相对距离进行 2D 旋转,赋予注意力得分对相对位置的显式依赖,大幅提升长度外推能力。
清晰阐明排列等变性,准确对比加性编码与 RoPE 的几何本质。
权威源资源与权利证明
Attention Is All You Need
对应章节 / 时间戳: Section 3.5 Positional Encoding
验证版本与日期: arXiv:1706.03762v7 (Verified: 2026-10-30)
Foundational primary literature defining the Transformer architecture, multi-head attention, and scaled dot-product attention.
Matrix multiplication and basic neural network concepts from Days 22-24 and 34-36.
All mathematical formulas and structural definitions are self-contained in the lesson text.
对比候选资源与选型分析 (2)
High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.
Co-primary: PyTorch line-by-line implementation alongside the paper equations.
The Annotated Transformer
对应章节 / 时间戳: Positional Encoding (class PositionalEncoding)
验证版本与日期: Updated PyTorch 2.0 edition (Verified: 2026-10-30)
Clear reference implementation of Transformer modules, residual connections, and layer normalization.
PyTorch tensor operations and attention theory.
All block assembly and normalization logic are provided in runnable local Python snippets.
对比候选资源与选型分析 (2)
Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.
Standard library implementation, but internal C++ bindings obscure the first-principles data flow.