51 / 90

第51日:事前学習ループの実行:損失追跡、チェックポイント保存と障害診断

順伝播・損失・逆伝播・更新の完全ループを統合し、訓練/検証損失の評価、チェックポイントの永続化と損失発散診断を実践する。

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

事前学習の中核反復ステップ:順伝播、損失、逆伝播と勾配クリッピング

Agent支援工学分析

前提条件

第49日のデータローダーおよび第50日のAdamWオプティマイザ。

学習目標

標準的な5ステップの訓練反復を実行し、set_to_none=True によるメモリ解放とグローバルL2ノルムクリッピングを適用する。

手順

参照資料: この活動に割り当てられた既存の読解・練習時間内で、CS336 Assignment 1: Basics (Spring 2025 tagged release) の tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping を参照し、ローカル課題とのつながりを一つ自分の言葉で説明する。既存の演習と合格基準は維持し、外部資料が開けない場合は本コース独自の説明を使う。各訓練反復において:(1) optimizer.zero_grad(set_to_none=True) で勾配を解放;(2) logits, loss = model(x, y) で順伝播とクロスエントロピーを算出;(3) loss.backward() で勾配を累積;(4) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) でL2ノルムを1.0以下に抑制;(5) optimizer.step() で重みを更新する。勾配クリッピングが外れ値バッチによる重み崩壊を防ぐ機序を考察せよ。

演習と予測記録

1. 1ステップの訓練反復を実行する完全なPythonコードを示せ。
2. クリッピング前の全パラメータ勾配ノルムが ||g||_2 = 5.0、max_norm = 1.0 の場合、各勾配に乗じられる縮小率はいくらか?
3. なぜ optimizer.zero_grad(set_to_none=True) は通常の zero_grad() よりも明確に優れているのか?

独立習得基準

標準的な5ステップ訓練コードを記述し、クリッピング倍率を正確に計算し、set_to_none=True のメモリ的利点を説明できること。

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

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

該当セクション・タイムスタンプ: tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping

検証バージョンと日付: 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.

linking MIT

nanoGPT: train.py pretraining loop

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

該当セクション・タイムスタンプ: train.py: training loop (while True): forward under ctx, scaler.scale(loss).backward(), clip_grad_norm_(grad_clip), scaler.step(optimizer)

検証バージョンと日付: 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.

02 120 分

訓練損失・検証損失の推定と過学習の監視

コア導出の自立実施

前提条件

活動01およびPyTorchの自動微分機構。

学習目標

torch.no_grad() および model.eval() の下で estimate_loss 関数を実装し、過学習を診断する。

手順

単一バッチの訓練損失には分散が含まれる。汎化性能を正確に評価するため、一定間隔(例: 250ステップ毎)でtrainとvalからそれぞれ200バッチをサンプリングして損失平均を算出する。model.eval() でDropoutを無効化し、torch.no_grad() で計算グラフの保持を防ぐ。

演習と予測記録

1. estimate_loss(model, eval_iters) のPythonコードを示せ。
2. estimate_loss 内で torch.no_grad() を省略した場合に生じる重大なGPU障害は何か?
3. 訓練損失と検証損失の乖離傾向からどのように過学習を判定するか?

独立習得基準

evalモードとno_gradを正しく設定した損失推定関数を自立実装し、過学習シグナルを同定できること。

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

linking MIT

nanoGPT: train.py pretraining loop

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

該当セクション・タイムスタンプ: train.py: estimate_loss() averages eval_iters batches per split; run every eval_interval

検証バージョンと日付: 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 | オリジナル出所URL ↗

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

03 120 分

チェックポイントのシリアライズ、アトミック保存と訓練再開

Agent支援工学分析

前提条件

活動01および02。

学習目標

モデル重み、AdamWモメンタム状態、反復ステップ数、最良検証損失を永続化し、寸分の狂いもない再開ロジックを実装する。

手順

参照資料: この活動に割り当てられた既存の読解・練習時間内で、CS336 Assignment 1: Basics (Spring 2025 tagged release) の tests/adapters.py: run_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing を参照し、ローカル課題とのつながりを一つ自分の言葉で説明する。既存の演習と合格基準は維持し、外部資料が開けない場合は本コース独自の説明を使う。長時間の事前学習はノードのプリエンプション等で中断される。チェックポイントには model.state_dict()、optimizer.state_dict()、iter_num、best_val_loss、config を保存する。破損を防ぐため、一時ファイルに保存した後に os.replace でアトミックにリネームする。

演習と予測記録

1. アトミック保存パターンを含むチェックポイント保存コードを示せ。
2. チェックポイントからモデル・オプティマイザ・ステップ数を復元する再開コードを示せ。
3. 再開時にモデル重みのみを復元し、optimizer.state_dict() の読み込みを怠った場合に生じる異常は何か?

独立習得基準

アトミックなチェックポイント保存・復元処理を正しく記述し、オプティマイザ状態喪失の弊害を明晰に説明できること。

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

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

該当セクション・タイムスタンプ: tests/adapters.py: run_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing

検証バージョンと日付: 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.

linking MIT

nanoGPT: train.py pretraining loop

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

該当セクション・タイムスタンプ: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

検証バージョンと日付: 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.

04 120 分

事前学習ループの実行と異常診断テスト

完全自立閉本テスト

前提条件

活動01〜03の完了。

学習目標

自立して事前学習スクリプトを実行し、観測された指標を誠実に記録し、NaNや損失停滞などの異常を診断する。

手順

閉本環境で代表的な訓練異常を診断せよ:(1) 突然の損失NaN発散;(2) ln(V) ≈ 10.8 での持続的停滞。小規模データセット上で50ステップの参照実行を行い、根拠のない収束保証を避けつつ実測された損失低下を報告せよ。

演習と予測記録

1. 訓練損失が NaN に転落する主な3大原因と各対策を述べよ。
2. 数百ステップ経過しても損失が約10.8のまま変動しない場合、どのサブシステムが故障しているか?
3. 小規模トークンデータセット上で50ステップ実行した際の損失推移の特徴を客観的に報告せよ。

独立習得基準

事前学習の代表的異常原因を正しく特定し、根拠のない誇張を排して実測訓練ダイナミクスを客観的に論述できること。

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

linking MIT

nanoGPT: train.py pretraining loop

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

該当セクション・タイムスタンプ: train.py: config defaults, get_lr(it) and the training loop (while True)

検証バージョンと日付: 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 arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

著者・提供機関: Ilya Loshchilov, Frank Hutter | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 2 Decoupling the Weight Decay from the Gradient-Based Update (Algorithm 2, AdamW)

検証バージョンと日付: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

選定理由:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

ソース前提知識:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

安全フォールバック(オフライン回復性):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

比較対象候補リソースと選定評価 (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.