訓練循環全流程:前向、損失、梯度清零、反向、參數更新
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 的位置及刪除它的後果。
正梯度對應減小參數。全批次只在樣本循環之前清零一次;在每個樣本之前清零會丟棄之前樣本的貢獻,只有每個樣本隨後獨立step時才符合隨機更新。
隨機一步 Δb_o=-0.05×4.2511=-0.2126,從0.3到0.0874。全批次 Δb_o=-0.05×3.2111=-0.1606,到0.1394。η=0.05的40個epoch中平均損失從2.106到約0.13,這是一次玩具實驗而非一般保證。參數必須在每批反傳前 zero_grad;省略後舊葉子梯度污染本批結果。
寫對五步次序、兩種更新的方向與大小,並解釋需要 zero_grad 的累加約定。
權威來源資源與權利證明
PyTorch Documentation: Autograd Mechanics
對應章節 / 時間戳: 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)
Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.
Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.
Neural Networks and Deep Learning: How the backpropagation algorithm works
對應章節 / 時間戳: 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)
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.