49 / 90

第 49 天:第 7 週總複習:從注意力到 logits,以及預訓練資料管線

回想並串聯第 43-48 天(注意力、遮罩、多頭、區塊結構、前向傳播),再補上預訓練迴圈唯一需要的新內容:自迴歸 (x, y) 批次。

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

新內容:自迴歸 (x, y) 批次與 get_batch

Agent 輔助工程分析

先修要求

第 1-3 天的分詞、第 36 天的交叉熵、第 48 天的前向傳播。

學習目標

從一維 token 陣列建構因果輸入-目標對,用 get_batch 取樣批次,計算批次張量的大小,並用 ln(V) 核對第一個損失。

實驗指南

這是今天唯一的新內容,其餘時間複習第 7 週。解碼器用位置 t 及之前的 token 預測 token t+1。上下文長度為 L 時,切出 L + 1 個 token 的視窗 chunk = tokens[i : i + L + 1],再令 x = chunk[:-1]、y = chunk[1:],兩者形狀都是 (L,)。一個批次把 B 個隨機視窗堆疊成形狀為 (B, T) 的 x 和 y。模型輸出 logits 的形狀是 (B, T, V),而 F.cross_entropy 需要 (N, V) 和 (N,),因此用 logits.view(-1, V) 和 y.view(-1) 攤平。訓練開始前所有 token 等機率,第一個損失應接近 ln(V)。

實戰與預測記錄

1. tokens = [502, 1204, 33, 991, 88, 412],L = 4,從索引 0 開始,寫出 x 和 y。為什麼視窗需要 L + 1 個 token?
2. 寫出 get_batch(data, batch_size, block_size, device)。
3. B = 64、T = 1024 時,x 和 y 合計在 int64 下佔多少位元組?int32 呢?
4. 寫出正確攤平後的 cross_entropy 呼叫,並給出 V = 50,257 時第一個損失的期望值。
5. 如果 y = x(不位移)會怎樣?

獨立掌握標準

能推導位移後的 (x, y) 對,寫出可執行的 get_batch,精確計算批次張量大小,並用 ln(V) 檢查第一個損失。

權威來源與學術版權說明

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始來源鏈接 ↗

對應章節/時間戳: train.py: get_batch(split): x = data[i:i+block_size], y = data[i+1:i+1+block_size]

核驗版本與日期: Git master commit 71c3905 (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 46-48 Transformer model architecture.

安全降級(離線韌性):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

候選來源對比與遴選分析 (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者/提供方: Stanford University CS336 Staff | 原始來源鏈接 ↗

對應章節/時間戳: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

核驗版本與日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入選理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

先修背景:

Fluent Python, PyTorch, and linear algebra

安全降級(離線韌性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

候選來源對比與遴選分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

02 120 分鐘

複習練習:縮放、遮罩與多頭注意力(第 43-45 天)

獨立完成核心推導

先修要求

第 43 天的縮放點積注意力、第 44 天的因果遮罩、第 45 天的多頭注意力。閉卷完成,只在對答案時打開第 43-45 天的筆記。

學習目標

手算還原一次因果注意力輸出,並在不看筆記的情況下回想第 43-45 天關於形狀、參數和數值穩定性的要點。

實驗指南

這是提取練習:先憑記憶作答,再核對。1) 按第 43-44 天的方法計算 S = Q K^T / sqrt(d_k),加上因果遮罩(第 44 天),做帶最大值平移的逐列 softmax(第 45 天),再乘以 V。2) 追蹤第 45 天的多頭形狀:(B, T, d_model) -> (B, T, h, d_k) -> (B, h, T, d_k) -> 分數 (B, h, T, T) -> 再回到 (B, T, d_model)。3) 查資料前,先用一句話解釋每個要點。

實戰與預測記錄

1. Q = [[1, 1], [0, 2]],K = [[1, 1], [2, 0]],V = [[1, 0], [0, 1]],d_k = 2。計算縮放後的分數、因果注意力權重和 Out。若沒有遮罩,Out[0] 是多少?
2. B = 2,T = 5,d_model = 12,h = 3。給出 d_k,以及拆分頭之後的 Q、分數張量、串接後輸出的形狀。
3. d_model = 12 時,W^Q、W^K、W^V、W^O 含偏置共有多少參數?不含偏置呢?
4. 憑記憶回答:為什麼要除以 sqrt(d_k)(第 43 天)?為什麼 exp(15) 在 float16 下會出錯(第 45 天)?如果 token 1 改變,Out[0] 會怎樣(第 44 天)?

獨立掌握標準

不看筆記即可還原因果注意力輸出、多頭形狀和參數量,並用自己的話解釋 sqrt(d_k)、float16 和因果不變性。

權威來源與學術版權說明

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

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.

03 120 分鐘

複習實作:區塊結構、參數台帳與前向傳播(第 46-48 天)

Agent 輔助工程分析

先修要求

第 46 天的 LayerNorm、RMSNorm 與殘差;第 47 天的 FFN 與區塊參數統計;第 48 天的位置編碼、權重共享與完整前向傳播。

學習目標

把正規化、Pre-LN 區塊、FFN 和權重共享整合成一個小型 GPT 的參數台帳和形狀追蹤。

實驗指南

使用一個玩具 GPT:V = 100,上下文 16,d_model = 32,n_layer = 2,n_head = 4,d_ff = 4 * d_model,可學習的位置嵌入,帶權重和偏置的 LayerNorm,無偏置的線性層,輸出頭權重共享。1) 按第 46 天的方法手算 LayerNorm 和 RMSNorm。2) 寫出第 46 天的 Pre-LN 區塊公式和第 48 天的完整前向傳播。3) 按第 47 天的方法逐行建立參數台帳,再算出權重共享節省的參數(第 48 天)。

實戰與預測記錄

1. 對 x = [4, 0, -2, 2] 計算 LayerNorm(無 epsilon,增益 1,偏置 0)和 RMSNorm。
2. 寫出一個區塊中 Pre-LN 殘差的兩行,並用一句話說明為什麼 Pre-LN 比 Post-LN 訓練更穩定。
3. 依序計算該 GPT 的參數量:每區塊、全部區塊、嵌入、最終 LayerNorm、總計。不共享權重的輸出頭會多出多少?
4. 每個區塊的矩陣權重中,FFN 佔多少比例?
5. 對 B = 8、T = 16 追蹤從 idx 到 logits 的形狀,並指出取樣下一個 token 用的切片。

獨立掌握標準

能給出正規化數值、Pre-LN 公式、總計 28,608 的參數台帳(並解釋權重共享的差值),以及正確的端到端形狀追蹤。

權威來源與學術版權說明

linking arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

作者/提供方: Biao Zhang, Rico Sennrich (University of Edinburgh) | 原始來源鏈接 ↗

對應章節/時間戳: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

核驗版本與日期: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

入選理由:

Primary paper showing that mean-centering in LayerNorm can be discarded without performance loss, speeding up modern LLMs (LLaMA, Gemma).

先修背景:

Variance, standard deviation, and LayerNorm basics.

安全降級(離線韌性):

RMSNorm formulas and numerical comparisons are derived completely in the lesson.

候選來源對比與遴選分析 (2)
Ba et al. Layer Normalization (2016) ↗ compared_selected_for_day46 [Open Access]

Original LayerNorm formulation with mean-centering; RMSNorm is compared directly against it as an optimization.

Ioffe & Szegedy Batch Normalization (2015) ↗ compared_alternative [Open Access]

Batch-dependent statistics; unsuitable for autoregressive sequence modeling.

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 Model Architecture (3.1-3.5)

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

04 120 分鐘

第 7 週測評:找出小型 GPT 中的四個 bug(第 43-49 天)

完全獨立閉卷考核

先修要求

第 43-48 天以及第 49 天活動 1-3。閉卷,聲明不使用 AI。

學習目標

獨立找出、解釋並修復四個各自違反第 7 週某條規則的預埋 bug,並預測它們在訓練中的表現。

實驗指南

不執行程式碼,先通讀一遍。每個標記行都違反了第 7 週的一條規則:注意力縮放(第 43 天)、因果遮罩(第 44 天)、數值穩定性(第 45 天)、Pre-LN 殘差(第 46 天)或 (x, y) 位移(第 49 天)。

def attention(q, k, v):                      # q, k, v: (B, h, T, d_k)
T, d_model = q.size(-2), q.size(-1) * q.size(1)
scores = q @ k.transpose(-2, -1) / d_model # (A)
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=0) # (B)
scores = scores.masked_fill(mask, float('-inf'))
return scores.softmax(dim=-1) @ v

class Block(nn.Module):
def forward(self, x):
x = self.ln_1(x + self.attn(x)) # (C)
return x + self.mlp(self.ln_2(x))

x, y = chunk[:-1], chunk[:-1] # (D)

實戰與預測記錄

1. 對 (A)、(B)、(C)、(D) 各行:說明 bug、它違反的是哪一天的規則,以及修復方法。
2. 哪個 bug 會在第一次前向傳播就產生 NaN?為什麼?
3. 哪個 bug 會讓損失下降得異常快,而模型什麼有用的都沒學到?
4. 全部修復後,V = 100 時第一個損失的期望值是多少?

獨立掌握標準

在無輔助的情況下找出全部四個 bug,對應到出處的那一天,給出可行的修復,並正確預測 NaN 和損失驟降兩種症狀。

權威來源與學術版權說明

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 arXiv non-exclusive license / Open Access

Root Mean Square Layer Normalization

作者/提供方: Biao Zhang, Rico Sennrich (University of Edinburgh) | 原始來源鏈接 ↗

對應章節/時間戳: Section 4 RMSNorm (Equation 4) and Section 4.1 Invariance Analysis

核驗版本與日期: NeurIPS 2019 / arXiv:1910.07467v1 (Verified: 2026-10-30)

入選理由:

Primary paper showing that mean-centering in LayerNorm can be discarded without performance loss, speeding up modern LLMs (LLaMA, Gemma).

先修背景:

Variance, standard deviation, and LayerNorm basics.

安全降級(離線韌性):

RMSNorm formulas and numerical comparisons are derived completely in the lesson.

候選來源對比與遴選分析 (2)
Ba et al. Layer Normalization (2016) ↗ compared_selected_for_day46 [Open Access]

Original LayerNorm formulation with mean-centering; RMSNorm is compared directly against it as an optimization.

Ioffe & Szegedy Batch Normalization (2015) ↗ compared_alternative [Open Access]

Batch-dependent statistics; unsuitable for autoregressive sequence modeling.