多頭子空間:為什麼以及如何分割 d_model
助教輔助工程檢查
前置要求
第 43-44 天的縮放點積注意力與因果遮罩機制。
學習目標
闡明多頭注意力的表徵必要性,形式化線性投影 W^Q, W^K, W^V, W^O,並推導微型模型與標準 GPT 規模的參數總帳。
操作指引
必做任務:解釋為什麼單頭注意力會將多種截然不同的關聯(如句法主謂依存與長程語義共指)壓縮為單一的加權平均。形式化 MultiHead(Q,K,V) = Concat(head_1, ..., head_h) W^O,其中每個 head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)。設 d_model = 4, h = 2,因此 d_k = d_v = 2。推導參數總帳:W^Q, W^K, W^V, W^O 均為 (4, 4) 矩陣,各含 16 個參數(無偏置共 64 參數,含偏置共 80 參數)。計算 GPT-2 Small 的參數量:d_model = 768, h = 12, d_k = 64(權重 4 * 768*768 = 2,359,296,偏置 4*768 = 3,072,總計 2,362,368)。
自主實作與記錄
1. 為什麼單個注意力頭無法在關注相鄰標記的同時關注遠距離句法依存?
2. 寫出 d_model = 4, h = 2 在含偏置和不含偏置情況下的精確參數總帳。
3. 計算 GPT-2 Small 注意力層的參數總帳(d_model = 768, h = 12)。
單個頭對每對標記只能輸出一個標量相關度,多頭機制則提供 h 個獨立的標量路由權重,使模型在不同特徵子空間中並行關注不同模式。
單頭注意力對每個位置的值向量只能生成單一的凸組合;若其權重被局部位置佔滿,便無法兼顧長程語法關聯。對於 d_model=4, h=2:4 個 (4,4) 矩陣共 64 個權重;加偏置(+16)共 80 個參數。對於 GPT-2 Small:W^Q, W^K, W^V, W^O 為 4 個 (768,768) 矩陣 = 4 * 589,824 = 2,359,296 個權重;偏置為 4 * 768 = 3,072;總注意力參數量為 2,362,368。
準確闡述多頭子空間路由的表徵意義,並無誤推導出微型模型與 GPT-2 規模的完整參數台帳。
權威來源資源與權利證明
Attention Is All You Need
對應章節 / 時間戳: Section 3.2.2: Multi-Head Attention architecture, linear projections, and parameter equations
驗證版本與日期: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)
The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.
Linear algebra, matrix multiplication, softmax probability distributions
Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.
對比候選資源與選型分析 (3)
Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.
Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.
Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.
The Annotated Transformer
對應章節 / 時間戳: MultiHeadedAttention module implementation: linear projections and subspace splitting
驗證版本與日期: Updated 2022 edition (Verified: 2026-10-30)
Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.
Intermediate Python, PyTorch broadcasting and tensor slicing semantics
The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.
對比候選資源與選型分析 (3)
Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.
Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.
The original primary paper; Annotated Transformer annotates it directly.