47 / 90

第 47 日:前饋網絡 (FFN)、SwiGLU 與多層 Block 堆疊

構建按位置前饋網絡,追蹤中間隱藏維度的擴張與投影,並以嚴格的張量不變量堆疊多個 Transformer 模組。

模型、預訓練與微調 (LoRA) 480 分鐘專注學習(8 小時)
01 120 分鐘

按位置前饋網絡 (FFN) 架構

Agent 輔助工程分析

前置要求

第 46 日 Transformer Block 與第 41 日 MLP 基礎知識。

學習目標

解釋 FFN 作為詞元鍵值記憶庫的角色,及其典型的 4 倍隱層擴展維度 d_ff = 4 * d_model。

操作指引

1. 寫出帶全部形狀的 FFN:x 為 (T, d_model),W1 為 (d_model, d_ff),b1 為 (d_ff),W2 為 (d_ff, d_model),b2 為 (d_model),因此 FFN(x) = act(x W1 + b1) W2 + b2 仍為 (T, d_model)。
2. 解釋「按位置」:同一組 W1, b1, W2, b2 分別作用於每一行 x_t;詞元 s 的值不會進入詞元 t 的 FFN 輸出。跨詞元的混合由注意力負責。
3. 比較激活函數:ReLU max(0, z) 有硬性的零;GELU z * Phi(z) 平滑,允許小的負值通過;SwiGLU 使用門控 (Swish(x W) ⊙ (x V)) W2,因此需要三個矩陣而不是兩個。
4. 對 d_model = 64、d_ff = 256 計算參數量,先不含偏置,再含偏置。
5. 用 d_ff' ≈ (2/3) d_ff 並取整,求出使 SwiGLU 參數量大致相同的隱藏寬度。

時間安排(120 分鐘):閱讀 30 + 練習 60 + 檢查 30。 閱讀:Vaswani et al. 第 3.3 節(按位置前饋網絡)和 nanoGPT model.py 中的 MLP 類別。練習:第 1-5 項。檢查:獨立完成精熟題中的兩種參數量計算。

自主實作與記錄

1. 寫出標準兩層 FFN 數學公式,並標出每個張量的形狀。
2. 為何 FFN 被稱為 '按位置 (position-wise)'?
3. 計算無偏置下 W1 (64x256) 與 W2 (256x64) 的總參數量。
4. 加上偏置 b1 和 b2,給出新的總數。
5. SwiGLU 使用三個矩陣(d_model x d_ff' 的 W 和 V,以及 d_ff' x d_model 的 W2)。選擇 d_ff' 使其參數量接近第 3 項,並給出該數量。

獨立掌握標準

闡明按位置特性並準確推導出 4 倍擴展下的參數賬目。

權威來源資源與權利證明

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.3 Position-wise Feed-Forward Networks

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

nanoGPT: model.py architecture implementation

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

對應章節 / 時間戳: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

入選理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

來源前置條件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

對比候選資源與選型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

02 120 分鐘

手算 FFN 前向傳播與隱藏層擴張

Agent 輔助工程分析

前置要求

活動 01 及第 22 日矩陣乘法。

學習目標

手算一個輸入向量 x = [1.0, 2.0] 通過 d_model=2 擴展到 d_ff=3 再投影回 d_model=2 的完整 FFN 前向傳播。

操作指引

1. 先寫形狀:x 為 1x2,W1 為 2x3,所以 z = x W1 為 1x3;h 為 1x3;W2 為 3x2,所以 y 為 1x2。
2. 把 z 的每個分量算成 x 與 W1 某一列的點積,寫出每個乘積。
3. 逐分量套用 ReLU,記下哪些分量(如果有)變為零。
4. 把 y 算成 h 與 W2 各列的點積。
5. 加上殘差:在模組中子層輸出會被加回,所以模組輸出是 x + y。
6. 對變式 x = [2, -1] 重做整個前向過程,比較激活的隱藏單元數量。

時間安排(120 分鐘):閱讀 20 + 練習 70 + 檢查 30。 閱讀:The Annotated Transformer 中的按位置 FFN 和 nanoGPT 的 MLP forward。練習:手算第 1-5 項。檢查:在白紙上重做變式,並用計算機或 NumPy 驗證一個分量。

自主實作與記錄

1. 計算未激活前向得分 z = x W1。
2. 應用 ReLU 得到 h。
3. 計算最終投影輸出 y = h W2。
4. 加上殘差連接,給出 x + y。
5. 對 x = [2, -1] 重複第 1-3 項,並說明 ReLU 關閉了哪些隱藏單元。

獨立掌握標準

毫無差錯地完成擴張與投影矩陣乘法的手算推導。

權威來源資源與權利證明

linking MIT

The Annotated Transformer

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

對應章節 / 時間戳: Position-wise Feed-Forward Networks (class PositionwiseFeedForward)

驗證版本與日期: 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)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

linking MIT

nanoGPT: model.py architecture implementation

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

對應章節 / 時間戳: model.py: class MLP (c_fc expands to 4 * n_embd, GELU, c_proj back to n_embd)

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

入選理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

來源前置條件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

對比候選資源與選型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

03 120 分鐘

堆疊 Transformer 模組與張量不變量

Agent 輔助工程分析

前置要求

活動 01 與 02。

學習目標

追蹤一批詞元張量 (B=2, T=4, d=64) 連續通過 2 個 Transformer Block,斷言張量形狀與數據類型的不變性。

操作指引

1. 把一個 Pre-LN 模組寫成兩個殘差子層:x = x + Attn(LN1(x)),然後 x = x + FFN(LN2(x))。
2. 固定示例:B = 2,T = 4,d_model = 64,n_heads = 4(head_dim = 16),d_ff = 256。
3. 追蹤注意力內部(每個頭的 Q, K, V、得分矩陣、合併後的輸出)和 FFN 內部(隱藏層)的形狀。
4. 標出形狀不同於 (B, T, d_model) 的每個位置,並檢查它在每次殘差相加之前回到 (B, T, d_model)。
5. 也檢查 dtype:模組必須回傳與輸入相同的 dtype。
6. 解釋為什麼相同的模組介面允許堆疊 L 個模組,以及為什麼殘差相加需要形狀一致。

時間安排(120 分鐘):閱讀 25 + 練習 60 + 檢查 35。 閱讀:Vaswani et al. 第 3.1 節(編碼器與解碼器堆疊)和 The Annotated Transformer 中 EncoderLayer/SublayerConnection 的程式碼。練習:第 1-4 項及完整形狀表。檢查:不看筆記解釋形狀契約,再對照。

自主實作與記錄

1. 寫出 2 層 Pre-LN Transformer 的子層執行序列。
2. 說明 Block 1 與 Block 2 之間所有邊界處的張量形狀。
3. 為何各層保持統一維度是殘差直接相加的前提?
4. 假設有 4 個頭且 d_ff = 256。給出每個頭的 Q、注意力得分和 FFN 隱藏層的形狀。

獨立掌握標準

清晰掌握模組化契約與形狀不變性原理。

權威來源資源與權利證明

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.1 Encoder and Decoder Stacks (N = 6 identical layers, d_model = 512)

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.

linking MIT

The Annotated Transformer

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

對應章節 / 時間戳: Encoder and Decoder Stacks

驗證版本與日期: 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)
HuggingFace Transformers library source ↗ compared_alternative [Apache 2.0]

Industrial scale with hundreds of model variations; Annotated Transformer is pedagogically focused on the core architecture.

PyTorch nn.Transformer documentation ↗ compared_alternative [Modified BSD]

Standard library implementation, but internal C++ bindings obscure the first-principles data flow.

04 120 分鐘

Transformer 模組參數量與計算複雜度精算

獨立完成核心推導

前置要求

完成活動 01 至 03。

學習目標

精確推導一個完整 Transformer Block(注意力 + FFN)的參數量預算與比例關係。

操作指引

1. 使用 GPT-2 small 的模組:d_model = 768,n_heads = 12(head_dim = 64),d_ff = 3072。
2. 計算注意力權重(Q, K, V, O:4 * 768 * 768)和 FFN 權重(2 * 768 * 3072),再求比例。
3. 加上偏置(每個注意力投影 768,FFN 上投影 3072,下投影 768)和兩個 LayerNorm(增益與偏置,各 2 * 768)。
4. 擴展到整個模型:12 個模組、詞元嵌入 50257 x 768、位置嵌入 1024 x 768、最終 LayerNorm,以及權重綁定的 LM 頭(無額外參數)。
5. 估計每個詞元的前向 FLOPs:矩陣乘法中每個權重約 2 FLOPs,另加注意力得分與加權求和的乘積,每層約 4 * T * d_model。
6. 在 T = 1024 下,比較 FFN 與注意力在參數量和 FLOPs 中各自的佔比。

時間安排(120 分鐘):閱讀 25 + 練習 60 + 檢查 35。 閱讀:nanoGPT model.py(Block、CausalSelfAttention、MLP、get_num_params)和 Vaswani et al. 表 1。練習:第 1-6 項。檢查:獨立重算 124M 總數,並與 get_num_params 對照。

自主實作與記錄

1. 計算注意力子層的總參數量(無偏置)。
2. 計算 FFN 子層的總參數量(無偏置)。
3. FFN 與注意力層在單個 Block 中的參數佔比分別是多少?
4. 加上偏置和兩個 LayerNorm,得到整個模組的參數量。
5. 對於 12 個模組、詞表 50257、上下文 1024、LM 頭權重綁定的模型,計算總參數量。
6. 估計 T = 1024 時一個模組每個詞元的前向 FLOPs。

獨立掌握標準

準確推導參數賬目,並指認 FFN 與注意力層 2:1 的黃金參數比例。

權威來源資源與權利證明

linking MIT

nanoGPT: model.py architecture implementation

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

對應章節 / 時間戳: model.py: GPT.get_num_params and GPT.estimate_mfu

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

入選理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

來源前置條件:

Python, PyTorch, and Day 43-45 attention fundamentals.

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

Local models and classes in the curriculum mirror nanoGPT semantics directly.

對比候選資源與選型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

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.3 Position-wise Feed-Forward Networks and Section 4 Why Self-Attention (Table 1)

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

High-level visual intuition, but Vaswani et al. provides the primary mathematical specifications needed for implementation.

Annotated Transformer (Harvard NLP) ↗ compared_selected_for_day46_48 [MIT]

Co-primary: PyTorch line-by-line implementation alongside the paper equations.