36 / 90

第 36 日:訓練循環、學習率與工程故障陳列室

構建並執行神經網絡訓練循環(前向、損失、zero_grad、反向傳播、參數更新),比較不同學習率對收斂軌跡的真實影響,診斷常見工程故障,並通過獨立掌握度考核。

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

訓練循環全流程:前向、損失、梯度清零、反向、參數更新

Agent輔助工程檢查

前置要求

第35日 N1 的九項梯度手算。

學習目標

解釋 forward、loss、zero_grad、backward、step 五步契約,區分全批次梯度和單樣本隨機更新。

操作指引

先預測再運行。每個 epoch 在樣本循環前清空參數梯度,每個樣本新建前向計算圖、計算平方 loss 並 backward 累加梯度;全部樣本之後 step 一次。zero_grad 只要在本批首次反傳前即可,下面將其放在 epoch 開頭。四樣本使用活動36-02的同一初始參數和數據,初始平均損失為2.106。

for epoch in range(EPOCHS):
    for p in model.parameters():
        p.grad = 0.0                 # 1. zero stale gradients
    total = 0.0
    for (x, y) in dataset:
        out = model(x)               # 2. forward
        loss = (out - y) ** 2        # 3. loss
        loss.backward()              # 4. backward (accumulates batch grads)
        total += loss.data
    for p in model.parameters():
        p.data -= lr * p.grad        # 5. step along -gradient
    log(epoch, total / len(dataset))

自主實作與記錄

1. 首樣本 b_o 梯度4.2511,η=0.05,預測隨機更新的方向與大小。2. 四樣本累加梯度為3.2111,預測全批次更新。3. 預測40個epoch後均值損失。4. 指出 zero_grad 的位置及刪除它的後果。

獨立掌握標準

寫對五步次序、兩種更新的方向與大小,並解釋需要 zero_grad 的累加約定。

權威來源資源與權利證明

linking Modified BSD

PyTorch Documentation: Autograd Mechanics

作者 / 機構: PyTorch Contributors | 原始出處連結 ↗

對應章節 / 時間戳: How autograd encodes the history

驗證版本與日期: PyTorch 2.5 Documentation (Verified: 2026-10-30)

入選理由:

Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.

來源前置條件:

Basic understanding of computational graphs and tensors.

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

The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.

對比候選資源與選型分析 (2)
TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

作者 / 機構: Michael Nielsen | 原始出處連結 ↗

對應章節 / 時間戳: Section: Learning with gradient descent

驗證版本與日期: Online book (Verified: 2026-10-30)

入選理由:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

來源前置條件:

Matrix multiplication and the multivariable chain rule from Days 19-24.

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

All four backprop equations and derivations are self-contained within the lesson text.

對比候選資源與選型分析 (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

Modular computational graph view; used as secondary source on Days 35-36.

02 120 分鐘

真實訓練觀察:微型數據集上的學習率效應對比

獨立掌握檢查

前置要求

活動36-01的訓練循環與第34日 N1。

學習目標

獨立運行同一 N1 四樣本實驗,比較η=0.05與η=5.0的40個epoch,在0/10/20/30/39記錄均值損失。

操作指引

在倉庫根目錄執行以下命令。兩次運行恢復相同九個初始權重與四個樣本。每個epoch重新建立參數葉子,每個樣本重建內部圖;四個梯度累加後更新。日誌記錄更新前的均值損失;更新用梯度之和,不是均值,改變約定會改變有效學習率。

python3 - <<'EOF'
from projects.autograd.engine import Value
initial = [0.5, -0.25, 0.1, -0.5, 1.0, -0.2, 1.0, -2.0, 0.3]
data = [((2.0,-1.0),1.0), ((0.5,0.5),-1.0), ((-1.0,1.0),-1.0), ((1.0,1.0),1.0)]
for lr in (0.05, 5.0):
    params = initial[:]
    for epoch in range(40):
        W = [Value(v) for v in params]  # Fresh leaves start with zero gradients.
        total = 0.0
        for (x1, x2), y in data:
            a1 = (W[0]*x1 + W[1]*x2 + W[2]).tanh()
            a2 = (W[3]*x1 + W[4]*x2 + W[5]).tanh()
            loss = (a1*W[6] + a2*W[7] + W[8] - y)**2
            loss.backward()  # Fresh interior graph, shared batch parameter leaves.
            total += loss.data
        if epoch in (0, 10, 20, 30, 39):
            print(lr, epoch, total / len(data))
        params = [p.data - lr*p.grad for p in W]  # Sum-gradient update, not mean.
EOF

自主實作與記錄

1. 報告η=0.05在epoch 0、10、20、30、39的損失。2. 報告η=5.0對應數值。3. 從局部曲率解釋步長過大如何越過谷底並放大發散。4. 給出本次玩具實驗不能支持的一條一般性結論。

獨立掌握標準

兩次運行重現同一損失表,解釋複合過沖而不是歸因於隨機失敗,並限定結論只適用於本實驗。

權威來源資源與權利證明

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

What is backpropagation really doing? (Chapter 3, Deep Learning)

作者 / 機構: Grant Sanderson (3Blue1Brown) | 原始出處連結 ↗

對應章節 / 時間戳: The Intuition for Backpropagation

驗證版本與日期: Online video and article (Verified: 2026-10-30)

入選理由:

Visual and geometric intuition for how nudging weights impacts the final cost function.

來源前置條件:

Basic derivative intuition from Days 16-18.

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

The lesson derives the network gradient equations step by step without requiring video playback.

對比候選資源與選型分析 (2)
StatQuest Neural Networks Part 3 ↗ compared_alternative [Proprietary]

Step-by-step arithmetic without calculus notation; 3Blue1Brown provides the calculus-visual link needed.

Khan Academy Multivariable Chain Rule ↗ compared_alternative [CC BY-NC-SA 3.0]

Pure math focus; 3Blue1Brown contextualizes the chain rule specifically for neural network graphs.

linking MIT

micrograd: A tiny scalar-valued autograd engine

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

對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

入選理由:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

來源前置條件:

Python object-oriented programming and operator overloading from Day 31.

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

The local projects/autograd engine is runnable offline and matches micrograd semantics.

對比候選資源與選型分析 (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

03 120 分鐘

故障陳列室:飽和死區、遺漏 zero_grad 與靜默形狀截斷

Agent輔助工程檢查

前置要求

活動36-02的實際本地訓練觀察。

學習目標

測量並修復重複反傳的舊梯度、tanh 飽和、zip 靜默丟輸入三種不同故障。

操作指引

故障A:執行下方同一計算圖反傳兩次的命令,測量w11.grad。故障B:僅將b1設為8.0使z1=9.25,記錄tanh導數及隱藏權重梯度。故障C:計算 sum(w*x for w,x in zip([0.5,-0.25], [2.0,-1.0,999.0])),指出額外輸入如何被丟棄。

python3 - <<'EOF'
import sys; sys.path.insert(0, '.')
from projects.autograd.engine import Value
x1, x2 = Value(2.0), Value(-1.0)
W = [Value(v) for v in (0.5,-0.25,0.1, -0.5,1.0,-0.2, 1.0,-2.0,0.3)]
a1 = (x1*W[0]+x2*W[1]+W[2]).tanh(); a2 = (x1*W[3]+x2*W[4]+W[5]).tanh()
loss = (a1*W[6]+a2*W[7]+W[8]-1.0)**2
loss.backward(); print('after 1st:', W[0].grad)
loss.backward(); print('after 2nd:', W[0].grad)
EOF

自主實作與記錄

每個故障都記錄數值、機制與最小修復:1. 同圖兩次反傳的w11.grad。2. b1=8.0時 tanh'(9.25) 與隱藏權重梯度。3. zip求和的z及丟棄的輸入999.0。

獨立掌握標準

復現三種測量,將症狀、機制、最小修復逐一對應,且能解釋只清葉子為何不能修復複用的圖。

權威來源資源與權利證明

linking MIT

CS231n: Backpropagation and Intuitions

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

對應章節 / 時間戳: Patterns in backward flow

驗證版本與日期: Course notes (Verified: 2026-10-30)

入選理由:

Modular local-gradient interpretation (gate operations: add, multiply, max) and gradient flow intuition.

來源前置條件:

Multivariable calculus and basic Python.

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

Local gate definitions and circuit flow diagrams in the lesson provide full coverage.

對比候選資源與選型分析 (2)

Raw circuit view; CS231n notes are more structured with explicit gate derivations.

Fast.ai Practical Deep Learning for Coders ↗ compared_alternative [GPL-3.0]

Top-down approach; CS231n bottom-up modular view matches our first-principles curriculum.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

作者 / 機構: Michael Nielsen | 原始出處連結 ↗

對應章節 / 時間戳: Saturation and unstable gradients

驗證版本與日期: Online book (Verified: 2026-10-30)

入選理由:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

來源前置條件:

Matrix multiplication and the multivariable chain rule from Days 19-24.

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

All four backprop equations and derivations are self-contained within the lesson text.

對比候選資源與選型分析 (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

Modular computational graph view; used as secondary source on Days 35-36.

04 120 分鐘

獨立掌握度考核:診斷、修復與技術原理解釋

獨立掌握檢查

前置要求

活動36-01至36-03。

學習目標

獨立寫出 MLP 訓練循環、診斷一個植入的故障並修復,完成客觀測驗。

操作指引

不使用AI:默寫 zero_grad→forward→loss→backward→step。某次運行每輪梯度不斷累加且損失發散,寫出症狀、機制和修復;獨立完成測驗,為錯點選擇補救鏈接。

自主實作與記錄

1. 寫出五步循環,指出刪除哪行造成舊梯度累加。2. 損失2.1→10^30時,在η過大、遺漏zero_grad、飽和中選擇最可能的兩個原因,並設計區分測量。3. 獨立模式完成三題並達100%。

客觀知識檢測:訓練迴圈與故障診斷

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

聲明輔助條件

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

1.

在 N1 的多層計算圖上,未清零就第二次呼叫 loss.backward(),使 $w_{11}.grad$ 在 $2.0068$ 之後變成 $4.0135$——恰好 $2$ 倍。為什麼?

2.

在觀測到的 $\eta = 5.0$ 執行中,平均損失在 40 個 epoch 內爆炸到超過 $10^{151}$。其機制是:

3.

哪一種防護可以阻止純量 Neuron 實作中 zip 的靜默形狀 bug?

作答應證與歷史記錄

    獨立掌握標準

    獨立正確寫出循環、對應故障機制與修復,並在獨立測驗取得100%。

    權威來源資源與權利證明

    linking Modified BSD

    PyTorch Documentation: Autograd Mechanics

    作者 / 機構: PyTorch Contributors | 原始出處連結 ↗

    對應章節 / 時間戳: How autograd encodes the history

    驗證版本與日期: PyTorch 2.5 Documentation (Verified: 2026-10-30)

    入選理由:

    Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.

    來源前置條件:

    Basic understanding of computational graphs and tensors.

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

    The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.

    對比候選資源與選型分析 (2)
    TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

    Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

    JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

    Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

    linking MIT

    micrograd: A tiny scalar-valued autograd engine

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

    對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

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

    入選理由:

    Deepest bottom-up mechanical clarity for backpropagation engine and computational graph visualization.

    來源前置條件:

    High-school calculus (derivatives) and basic Python syntax

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

    Authored mathematical derivations, interactive Pyodide engine, and local tests provide complete offline study without video streaming.

    對比候選資源與選型分析 (2)
    PyTorch Autograd Internals ↗ compared_alternative [Modified BSD]

    Normative production documentation, but micrograd's pure Python implementation provides far superior initial clarity.

    3Blue1Brown: What is Backpropagation? ↗ compared_alternative [3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions]

    High visual quality, pairs cleanly as optional supplementary visual reference.