44 / 90

第 44 天:自迴歸因果遮罩與嚴格不變性

在生成式語言模型中嚴格實施自迴歸約束。構建下三角因果遮罩,證明 Softmax 將 -inf 精確映射為零機率,並透過實驗驗證未來標記擾動對歷史表徵的影響精確為零。

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

自迴歸約束與下三角因果遮罩構建

助教輔助工程檢查

前置要求

第 43 天的注意力機制與縮放除法推導。

學習目標

闡明解碼器語言模型的自迴歸因式分解約束,構建下三角因果遮罩矩陣 M,並推導遮罩後的分數矩陣 S_masked = S + M。

操作指引

必做任務:解釋為什麼因果解碼器必須滿足 P(x_1, ..., x_T) = prod_{t=1}^T P(x_t | x_{ t,導致模型在訓練時發生“作弊洩露”。定義加性因果遮罩 M in R^{T x T},滿足當 j <= i 時 M_{i,j} = 0,當 j > i 時 M_{i,j} = -inf。寫出序列長度 T=3 時的具體矩陣 M。使用第 43 天縮放後的分數矩陣 S = [[2.0, 0.0, 2.0], [0.0, 3.0, 2.0], [1.0, 1.5, 2.0]],計算遮罩後的分數矩陣 S_masked = S + M。

自主實作與記錄

1. 寫出 3x3 因果遮罩矩陣 M 的完整元素。
2. 寫出加性遮罩後的分數矩陣 S_masked = S + M。
3. 如果代碼中錯誤地將主對角線上方程設為 0、下方設為 -inf,會產生什麼後果?

獨立掌握標準

準確寫出下三角因果遮罩 M 並完成 3x3 遮罩分數矩陣 S_masked 的推導。

權威來源資源與權利證明

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.3: Masked Multi-Head Attention in the decoder preventing leftward information flow

驗證版本與日期: 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) | 原始出處連結 ↗

對應章節 / 時間戳: subsequent_mask implementation using torch.triu and triangular boolean masking

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

02 120 分鐘

因果遮罩下的 Softmax:逐步矩陣精確推導

獨立掌握檢查

前置要求

完成第 44 天活動 1。

學習目標

在遮罩分數矩陣上利用最大值平移計算逐行 Softmax,求出因果注意力矩陣 A_causal,並計算因果加權輸出。

操作指引

必做任務:對 S_masked = [[2.0, -inf, -inf], [0.0, 3.0, -inf], [1.0, 1.5, 2.0]] 執行逐行 Softmax 計算。第 0 行:有限項最大值為 2.0。exp([2.0-2.0, -inf, -inf]) = [1.0, 0.0, 0.0],歸一化得 A_causal[0, :] = [1.0, 0.0, 0.0]。第 1 行:最大值為 3.0。exp([-3.0, 0.0, -inf]) = [exp(-3), 1.0, 0.0] ~= [0.049787, 1.0, 0.0],和為 1.049787。A_causal[1, :] = [0.047426, 0.952574, 0.0]。第 2 行無遮罩,得 [0.186324, 0.307196, 0.506480]。使用第 43 天的 V = [[1,0], [0,2], [1,1]] 計算因果輸出 Out_causal = A_causal V。

自主實作與記錄

1. 計算精確到小數點後 6 位的 A_causal 各行注意力權重。
2. 計算全部 3 行的因果輸出 Out_causal = A_causal V。
3. 對比第 43 天未遮罩的 Out[0] 與本節 Out_causal[0],闡述其本質差異。

獨立掌握標準

精確計算 A_causal 和 Out_causal 各元素,數值與參考值在 4 位小數內一致。

權威來源資源與權利證明

linking MIT

The Annotated Transformer

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

對應章節 / 時間戳: Attention masking implementation: masked_fill with -1e9 before softmax

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

linking MIT

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

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

對應章節 / 時間戳: model.py: att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float("-inf"))

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

03 120 分鐘

因果不變性擾動實驗與代數證明

助教輔助工程檢查

前置要求

完成第 44 天活動 2。

學習目標

透過數值實驗與代數推導,嚴格驗證擾動未來標記時歷史位置的注意力權重和輸出表徵精確保持不變。

操作指引

必做任務:對序列執行嚴格擾動實驗。將未來標記(t=2)替換為任意極端數值:q_2' = [99.0, -42.0, 13.0, 7.0], k_2' = [-50.0, 12.0, 34.0, -8.0], v_2' = [100.0, -200.0]。重新計算 S_masked、A_causal 和 Out_causal。證明 diff(A_causal[0], A_causal_pert[0]) = 0.0,diff(A_causal[1], A_causal_pert[1]) = 0.0,diff(Out[0], Out_pert[0]) = 0.0,以及 diff(Out[1], Out_pert[1]) = 0.0。將此特性與無遮罩層(所有歷史行均被污染)進行深入對比。

自主實作與記錄

1. 從 Softmax 分子分母公式證明為什麼 A_causal 的第 i 行絕不依賴任何 j > i 的 k_j 或 v_j。
2. 給出對標記 2 擾動前後,第 0、1、2 行表徵差異的最大絕對值。
3. 說明因果不變性如何保障大模型自迴歸生成中 KV-Cache(鍵值快取)機制的正確性?

獨立掌握標準

給出嚴謹的未來獨立性代數證明,並在數值上驗證歷史位置差異精確為 0.0。

權威來源資源與權利證明

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.3: Autoregressive self-attention property ensuring causal factorization

驗證版本與日期: 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 buffer verification ensuring past tokens remain strictly invariant

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

獨立掌握檢查:因果洩漏、遮罩缺陷與不變性斷言

獨立掌握檢查

前置要求

活動 44-01 至 44-03。

學習目標

在聲明無 AI 輔助條件下,獨立識別遮罩實現缺陷,推導 2 標記序列的因果注意力,並給出嚴謹的不變性斷言。

操作指引

必做任務:閉卷獨立作答。給定 T=2、縮放分數 S = [[3.0, 1.0], [2.0, 4.0]] 與 V = [[1.0, 2.0], [3.0, 0.0]]:1. 構建 2x2 因果遮罩 M 並寫出 S_masked。2. 計算精確的 2x2 因果注意力矩陣 A_causal。3. 計算 Out_causal。4. 若標記 1 被替換為任意新向量,證明 Out_causal[0] 的變化量。5. 完成客觀選擇題。

自主實作與記錄

1. 寫出 2x2 設置下的 S_masked。
2. 計算精確到 6 位小數的 A_causal。
3. 計算 Out_causal = A_causal V。
4. 指出若擾動標記 1,Out_causal[0] 的精確變化量。
5. 完成 3 道單項選擇題。

客觀理解度測試:因果遮罩與嚴格不變性

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

聲明輔助條件

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

1.

在自迴歸生成中,下三角因果遮罩(Causal Mask)的核心操作目標是什麼?

2.

在為注意力分數構建加性因果遮罩時,必須為主對角線上方的上三角區域(j > i)賦予什麼數值?

3.

若對長度為 3 的序列(t in {0, 1, 2})中的第 2 個標記進行任意數值擾動,在嚴格因果遮罩下,位置 0 的注意力權重和輸出表徵會發生什麼變化?

作答應證與歷史記錄

    獨立掌握標準

    獨立推導 2x2 因果注意力和輸出,正確斷言歷史不變性,且客觀測試獲 100% 滿分。

    權威來源資源與權利證明

    linking MIT

    The Annotated Transformer

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

    對應章節 / 時間戳: subsequent_mask unit tests and triangular boundary checks

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

    linking MIT

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

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

    對應章節 / 時間戳: model.py: causal mask shape registration and forward assertion

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