43 / 90

第 43 天:縮放點積注意力與查詢-鍵-值投影

將注意力機制形式化為用查詢匹配鍵以加權聚合值。推導 R^{d_k} 中點積的方差,證明為什麼 1/sqrt(d_k) 縮放因子能防止 Softmax 梯度消失,並透過手算與代碼完整追蹤 (T, d_k) 形狀的分數矩陣。

模型與訓練 480 分鐘主動學習(8 小時專注研讀)
01 120 分鐘

查詢、鍵與值:向量角色與注意力公式形式化

助教輔助工程檢查

前置要求

第 41-42 天的前向傳播、矩陣乘法與逐行 Softmax 機制。

學習目標

將注意力機制分解為用查詢檢索鍵以聚合值的路由過程,推導張量維度,並完成原始點積分數矩陣的數值計算。

操作指引

學習來源:在本活動現有的閱讀與練習時段內,參考 Stanford CS224N: Natural Language Processing with Deep Learning 的 Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。必做任務:形式化縮放點積注意力公式 Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V。給定序列長度 T=3、鍵維度 d_k=4、值維度 d_v=2。設定 Q 各行為 q_0=[2.0, 0.0, 2.0, 0.0], q_1=[0.0, 2.0, 0.0, 2.0], q_2=[1.0, 1.0, 1.0, 1.0];K 各行為 k_0=[1.0, 0.0, 1.0, 0.0], k_1=[0.0, 2.0, 0.0, 1.0], k_2=[2.0, 1.0, 0.0, 1.0];V 各行為 v_0=[1.0, 0.0], v_1=[0.0, 2.0], v_2=[1.0, 1.0]。逐步手算原始分數矩陣 S_raw = Q K^T。闡述查詢(當前位置在找什麼)、鍵(當前位置提供什麼資訊)與值(傳輸的具體表徵內容)的幾何與物理意義。

自主實作與記錄

1. 計算 S_raw = Q K^T 的 3x3 矩陣全部數值。
2. 明確給出 Q、K、V、Q K^T 以及最終輸出矩陣的張量形狀。
3. 用兩句話說明為什麼注意力是一種數據驅動的關聯檢索,而非靜態固定權重層?

獨立掌握標準

準確列出矩陣乘法各步驟,得到完全正確的 3x3 S_raw 矩陣及各張量形狀。

權威來源資源與權利證明

linking Stanford University copyright; no course-wide open reuse license verified linking only; no reproduction

Stanford CS224N: Natural Language Processing with Deep Learning

作者 / 機構: Stanford University CS224N staff | 原始出處連結 ↗

對應章節 / 時間戳: Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides

驗證版本與日期: Public edition checked 2026-11-01; moving pages may change

入選理由:

Selected attention/Transformer lecture slides provide a coherent teaching check on Q/K/V and architecture; original papers remain definition references and local code exercises remain required.

來源前置條件:

Linear algebra, gradients, basic neural language models and PyTorch.

安全回退方案(離線彈性):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

對比候選資源與選型分析 (2)
The Annotated Transformer ↗ compared_alternative [MIT]

Runnable code commentary remains the implementation spine; its sublayer convention must not be mistaken for the original paper.

The Illustrated Transformer ↗ compared_alternative [Copyright Jay Alammar; edition-specific reuse terms unverified]

Concise diagrams are useful, but provide neither the wider lecture sequence nor checked implementation exercises.

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 機構: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出處連結 ↗

對應章節 / 時間戳: Section 3.2.1: Scaled Dot-Product Attention equation and query/key/value matrix definitions

驗證版本與日期: 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.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

對應章節 / 時間戳: model.py: CausalSelfAttention forward pass query/key/value projection extraction

驗證版本與日期: GitHub master commit (Verified: 2026-10-30)

入選理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

來源前置條件:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

安全回退方案(離線彈性):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

對比候選資源與選型分析 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

02 120 分鐘

縮放因子 sqrt(d_k) 與注意力分數矩陣 Softmax

獨立掌握檢查

前置要求

完成第 43 天活動 1。

學習目標

對分數矩陣應用 1/sqrt(d_k) 縮放因子,計算數值穩定的逐行 Softmax 機率分佈,並完成值的加權聚合輸出。

操作指引

必做任務:當 d_k = 4 時,縮放因子為 sqrt(4) = 2.0。將 S_raw 各元素除以 2.0 獲得縮放矩陣 S = S_raw / 2.0。隨後採用最大值平移法逐行計算 Softmax:第 0 行縮放值為 [2.0, 0.0, 2.0];第 1 行為 [0.0, 3.0, 2.0];第 2 行為 [1.0, 1.5, 2.0]。求出注意力權重矩陣 A = softmax(S),並計算最終輸出 Out = A V。驗證 A 的每一行求和嚴格為 1.0。

自主實作與記錄

1. 寫出縮放後的分數矩陣 S = S_raw / 2.0。
2. 計算精確到小數點後 6 位的 Softmax 注意力矩陣 A。
3. 計算所有 3 個位置的輸出表徵向量 Out = A V。

獨立掌握標準

獨立推導 S 矩陣,求得與參考值在 4 位小數內一致的注意力機率並計算出正確的 Out。

權威來源資源與權利證明

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 機構: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出處連結 ↗

對應章節 / 時間戳: Section 3.2.1: Mathematical justification for scaling factor 1/sqrt(d_k) to prevent vanishing softmax gradients

驗證版本與日期: 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.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

The Annotated Transformer

作者 / 機構: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | 原始出處連結 ↗

對應章節 / 時間戳: Scaled Dot Product Attention code cell and attention matrix visualization

驗證版本與日期: 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)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

03 120 分鐘

方差縮放推導與梯度飽和反例剖析

助教輔助工程檢查

前置要求

完成第 43 天活動 2;具備初等機率統計與微積分基礎。

學習目標

在數學上證明兩個 d_k 維獨立隨機向量的點積方差為 d_k,並定量演示未縮放時 Softmax 梯度嚴重消失的數值反例。

操作指引

必做任務:設 q 與 k 的各分量 q_i, k_i 相互獨立,且 E[q_i] = E[k_i] = 0, Var(q_i) = Var(k_i) = 1。推導 E[q . k] = 0 與 Var(q . k) = d_k。證明 Var((q . k) / sqrt(d_k)) = 1。隨後分析反例:當 d_k = 64 時,sqrt(d_k) = 8。若不縮放,點積標準差高達 8,極易產生 +16 和 -16 的對數幾率。計算 softmax([16, 0, -16]) 的機率輸出,並依據 Softmax 導數公式 dp_i / dz_j = p_i (delta_ij - p_j) 說明梯度為什麼幾乎為 0。

自主實作與記錄

1. 利用獨立零均值變數性質 Var(XY) = E[X^2]E[Y^2] 給出完整的方差推導步驟。
2. 計算 softmax([16, 0, -16]) 並在數值上給出其局域梯度幅度。
3. 說明為什麼未縮放點積會導致深層 Transformer 在訓練初期即陷入優化停滯?

獨立掌握標準

完整書寫代數推導過程並給出數值反例的具體計算結果。

權威來源資源與權利證明

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

作者 / 機構: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出處連結 ↗

對應章節 / 時間戳: Section 3.2.1 footnote and variance derivation for inner products of unit-variance components

驗證版本與日期: 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.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

對應章節 / 時間戳: model.py: scaling by 1.0 / math.sqrt(k.size(-1)) in attention calculation

驗證版本與日期: GitHub master commit (Verified: 2026-10-30)

入選理由:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

來源前置條件:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

安全回退方案(離線彈性):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

對比候選資源與選型分析 (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

04 120 分鐘

獨立掌握檢查:點積注意力運算與張量形狀

獨立掌握檢查

前置要求

活動 43-01 至 43-03。

學習目標

在聲明無 AI 輔助的條件下,獨立完成全新配置的縮放點積注意力手算、方差推導與張量形狀契約檢驗。

操作指引

必做任務:閉卷獨立作答,不依賴 AI 助手與現成計算器。面對新配置 T=2, d_k=4, d_v=2:Q 矩陣包含行 [0.0, 2.0, 0.0, 2.0], [2.0, 0.0, 2.0, 0.0];K 矩陣包含行 [0.0, 2.0, 0.0, 2.0], [1.0, 0.0, 1.0, 0.0];V 矩陣包含行 [2.0, 1.0], [0.0, 3.0]。計算原始點積矩陣 S_raw,以 sqrt(4)=2 進行縮放,求出精確的 Softmax 矩陣與最終輸出表徵。完成客觀測試題。

自主實作與記錄

1. 計算 S_raw 與縮放後的 S = S_raw / 2.0。
2. 計算精確的 2x2 Softmax 權重矩陣 A。
3. 計算 2x2 輸出表徵矩陣 Out = A V。
4. 完成 3 道單項選擇題。

客觀理解度測試:縮放點積注意力機制

請回答以下診斷題目檢驗掌握情況。提交前請誠實聲明你的輔助條件。

聲明輔助條件

說明:無 AI 輔助屬於誠實聲明條件,非平台監控或強制檢測手段。

1.

將點積結果 Q K^T 除以 sqrt(d_k) 的核心數學動機是什麼?

2.

對於序列長度 T=3、鍵維度 d_k=4、值維度 d_v=2 的輸入,注意力分數矩陣 S = (Q K^T) / sqrt(d_k) 的張量形狀是什麼?

3.

若向量 q, k in R^{d_k} 的各分量相互獨立且服從零均值、單位方差分佈,其未縮放點積 q . k 的方差是多少?

作答應證與歷史記錄

    獨立掌握標準

    獨立推導出 S、A、Out 矩陣全套數值,且客觀測試題獲得 100% 滿分。

    權威來源資源與權利證明

    linking arXiv.org perpetual non-exclusive license / Open Access

    Attention Is All You Need

    作者 / 機構: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | 原始出處連結 ↗

    對應章節 / 時間戳: Section 3.2.1: Attention equation verification and tensor shape dimensions

    驗證版本與日期: 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.

    Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

    Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

    linking MIT

    The Annotated Transformer

    作者 / 機構: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | 原始出處連結 ↗

    對應章節 / 時間戳: Attention function test assertions and shape contracts

    驗證版本與日期: 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)
    Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

    Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

    Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

    Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

    Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

    The original primary paper; Annotated Transformer annotates it directly.