訓練ループの全容:順伝播、損失計算、勾配ゼロ化、逆伝播、ステップ更新
Agent支援エンジニアリングチェック
前提条件
第35日のN1全9勾配の手計算。
学習目標
forward、loss、zero_grad、backward、stepの5段階を説明し、全バッチと単一例の確率的更新を区別する。
手順
実行前に予測する。各epochで例のループ前にパラメータ勾配をゼロ化し、各例で新しい順伝播グラフを作り、二乗lossとbackwardを計算して勾配を累積する。全例の後で一度stepする。zero_gradはバッチ内最初の反伝播より前に置く。下記ではepochの先頭に置く。活動36-02と同じ4例、初期値を使い、初期平均損失は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. 40epoch後の平均損失を予測する。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の40epochで平均損失は2.106から約0.13になるが、一つの玩具実験で一般保証ではない。毎バッチの反伝播前にzero_gradを行わないと古い葉の勾配が混入する。
5段階の順序、2種類の更新方向と大きさ、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.