位置信息表示:可學習編碼、正弦編碼與旋轉位置編碼 (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.