36 / 90

第36日:訓練ループ、学習率と工学失敗事例ギャラリー

完全なニューラルネットワーク訓練ループ(順伝播、損失、zero_grad、逆伝播、ステップ更新)を構築・実行し、学習率が収束軌跡に与える実際の影響を比較し、工学的不具合を診断し、独立習熟度テストに合格する。

モデル・事前学習とLoRA 480分の集中学習(8時間)
01 120 分

訓練ループの全容:順伝播、損失計算、勾配ゼロ化、逆伝播、ステップ更新

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の位置と省略の影響を書く。

独立習得基準

5段階の順序、2種類の更新方向と大きさ、zero_gradが必要な累積方針を説明できる。

公式ソースリソースと権利証跡

linking Modified BSD

PyTorch Documentation: Autograd Mechanics

著者・提供機関: PyTorch Contributors | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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と4例でη=0.05とη=5.0の40epochを独立に実行し、epoch 0/10/20/30/39の平均損失を記録する。

手順

リポジトリのルートで次のコマンドを実行する。各runは同じ9初期値と4例から開始する。epochごとに葉を、例ごとに内部グラフを再作成し、4例の勾配を累積して更新する。ログは更新前の平均損失。更新には平均でなく勾配の和を使い、規約変更は実効学習率を変える。

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. 局所曲率を無視した大きなstepが谷を越え発散を増幅する仕組みを書く。4. この実験から主張できない一般論を一つ挙げる。

独立習得基準

両runの損失表を再現し、偶然でなく過走の累積として説明し、結論をこの実験だけに限定する。

公式ソースリソースと権利証跡

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) | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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による入力の切り捨てを測定し、3つの故障を修正する。

手順

故障A:次のコマンドで同じグラフを2回反伝播し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. 同グラフ2回のw11.grad。2. b1=8.0でのtanh'(9.25)と勾配。3. zipのzと捨てられた999.0。

独立習得基準

3測定を再現し、症状・機構・最小修正を対応付け、葉だけのゼロ化が再利用グラフを直せない理由を述べる。

公式ソースリソースと権利証跡

linking MIT

CS231n: Backpropagation and Intuitions

著者・提供機関: Andrej Karpathy / Stanford University | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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を再現する。各epochで勾配が累積し損失が発散するrunについて症状・機構・修正を書く。独立クイズを受け、誤答ごとの回復リンクを記録する。

演習と予測記録

1. 5段階を書き、どの行の削除で古い勾配が累積するか示す。2. 損失2.1→10^30の原因をη過大、zero_grad欠如、飽和から2つ選び、区別する測定を設計する。3. 独立モードの3問で100%を達成する。

客観的知識チェック:訓練ループと失敗診断

理解度を確認するために次の質問に答えてください。提出前に申告する支援条件を選択してください。

申告する支援条件

注意:AI 不使用は正直な申告条件であり、監視を主張するものではありません。

1.

N1 の多層グラフで、ゼロ化せずに loss.backward() を 2 度目に呼び出すと、$w_{11}.grad$ が $2.0068$ の後に $4.0135$ になりました — ちょうど $2$ 倍です。なぜですか?

2.

観測された $\eta = 5.0$ の実行では、平均損失が 40 エポック以内に $10^{151}$ を超えて爆発しました。そのメカニズムは:

3.

スカラー Neuron 実装で、黙って起きる zip の形状バグを防ぐガードはどれですか?

受験履歴と証拠

    独立習得基準

    独立にループを書き、故障機構と修正を対応付け、独立クイズ100%を達成する。

    公式ソースリソースと権利証跡

    linking Modified BSD

    PyTorch Documentation: Autograd Mechanics

    著者・提供機関: PyTorch Contributors | オリジナル出所URL ↗

    該当セクション・タイムスタンプ: 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 | オリジナル出所URL ↗

    該当セクション・タイムスタンプ: 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.