55 / 90

第55日: チェックポイント、状態辞書と安全な学習再開

PyTorchの重み、バッファ、オプティマイザ状態、スケジューラ、乱数シードのアトミック保存と再開。

モデルと事前学習 480 分(8時間)
01 120 分

モデル状態辞書(state_dict)とテンソル直列化の基礎

Agent支援エンジニアリングチェック

前提条件

第54日Transformer評価課題の完了およびPyTorchモジュールの基礎知識。

学習目標

model.state_dict() の内部構造、パラメータと登録バッファの違い、torch.save/torch.load におけるCPU/CUDAマッピングの仕組みを理解する。

手順

参照資料: この活動に割り当てられた既存の読解・練習時間内で、CS336 Assignment 1: Basics (Spring 2025 tagged release) の tests/test_serialization.py: test_checkpointing; model, optimizer and iteration state を参照し、ローカル課題とのつながりを一つ自分の言葉で説明する。既存の演習と合格基準は維持し、外部資料が開けない場合は本コース独自の説明を使う。1. model.state_dict() を確認し、キーがサブモジュールの階層(例: 'blocks.0.attn.c_attn.weight')に対応していることを確認します。
2. torch.save は内部で pickle を使用し、テンソルメタデータとストレージポインタを記録します。
3. モデルオブジェクト全体の保存と state_dict 保存を比較し、コードの結合度低減とアーキテクチャ安定性の観点から公式が state_dict を推奨する理由を把握します。
4. GPUで保存した重みをロードする際の map_location='cpu' の必須性を確認します。

演習と予測記録

小さな2層GPTモデルを作成し、その state_dict を 'ckpt_model.pt' に保存してください。新しいモデルインスタンスに map_location='cpu' を指定してロードし、torch.equal() で全テンソルが完全一致することを確認してください。

独立習得基準

状態辞書を正確にシリアライズし、新規インスタンスへ完全一致でロードできる。

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

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

該当セクション・タイムスタンプ: tests/test_serialization.py: test_checkpointing; model, optimizer and iteration state

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

PyTorch Tutorial: Saving and Loading Models

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

該当セクション・タイムスタンプ: What is a state_dict?

検証バージョンと日付: PyTorch 2.x Documentation (Verified: 2026-10-30)

選定理由:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

ソース前提知識:

Python, PyTorch tensors and nn.Module basics.

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

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

比較対象候補リソースと選定評価 (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

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.

ソース前提知識:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

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

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

比較対象候補リソースと選定評価 (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

02 120 分

オプティマイザ状態辞書、学習率スケジューラ、および乱数生成器(RNG)の連続性

独立習得チェック(AI 支援なし)

前提条件

第55日アクティビティ1およびAdamオプティマイザの定式化理解。

学習目標

Adamの1次・2次モーメント、ステップ数、および乱数シード状態を保存し、再開時の損失急上昇(ロススパイク)を防止する。

手順

1. optimizer.state_dict() を調査し、各パラメータIDに対して 'step', 'exp_avg' (1次モーメント), 'exp_avg_sq' (2次モーメント) が保持されていることを確認します。
2. オプティマイザ状態を保存しない場合、モーメントがゼロ初期化され、再開直後に深刻な学習の乱れが生じる理由を学びます。
3. torch.get_rng_state() および torch.cuda.get_rng_state_all() をチェックポイントに含める手順を確認します。
4. モデル、オプティマイザ、スケジューラ、step、best_val_loss を統合した完全な辞書構造を設計します。

演習と予測記録

AdamWで5ステップ学習を行い、完全なチェックポイント辞書を保存してください。新規モデルとオプティマイザに復元し、ステップ6の損失値が中断なしの基準実行と完全に一致することを検証してください。

独立習得基準

オプティマイザ状態と乱数状態を復元し、再開ステップにおける損失完全一致を実証できる。

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

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

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

該当セクション・タイムスタンプ: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

検証バージョンと日付: PyTorch 2.x Documentation (Verified: 2026-10-30)

選定理由:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

ソース前提知識:

Python, PyTorch tensors and nn.Module basics.

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

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

比較対象候補リソースと選定評価 (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

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.

ソース前提知識:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

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

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

比較対象候補リソースと選定評価 (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

03 120 分

アトミックなチェックポイント保存、ファイルロックとバージョン整合性保護

Agent支援エンジニアリングチェック

前提条件

第55日アクティビティ1および2、ファイルシステムのアトミック操作知識。

学習目標

一時ファイルへの書き込みとアトミックなリネーム(os.replace)により、クラッシュ時の書き込み途絶によるファイル破損を防ぐ。

手順

1. 直接 torch.save(..., 'ckpt.pt') を行うと、書き込み中にプロセスが強制終了した場合にファイルが破損し復旧不能になるリスクを認識します。
2. 'ckpt.pt.tmp' に保存し、os.fsync でディスクにフラッシュ後、os.replace でアトミックに置換する手法を学びます。
3. 'version': 1 スキーマヘッダを付与し、将来のモデル仕様変更に対する後方互換性を担保します。
4. 最新N個のローリング保存と世代管理ポリシーを設計します。

演習と予測記録

一時ファイルを作成して書き込み、アトミックに置換する save_checkpoint_atomic(payload, filepath) 関数を実装してください。

独立習得基準

書き込み中断時にもターゲットファイルが破損しないアトミック保存処理を実装できる。

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

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

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

該当セクション・タイムスタンプ: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

検証バージョンと日付: PyTorch 2.x Documentation (Verified: 2026-10-30)

選定理由:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

ソース前提知識:

Python, PyTorch tensors and nn.Module basics.

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

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

比較対象候補リソースと選定評価 (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

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.

ソース前提知識:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

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

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

比較対象候補リソースと選定評価 (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

04 120 分

評価課題: 堅牢なチェックポイントマネージャの実装と学習再開の検証

独立習得チェック(AI 支援なし)

前提条件

第55日アクティビティ1〜3の全習得。

学習目標

アトミック保存、スナップショット世代管理、および損失曲線の一致性を検証する CheckpointManager クラスを完成させる。

手順

1. CheckpointManager(checkpoint_dir, max_to_keep=3) クラスを設計します。
2. save(...) と load_latest(...) メソッドを実装し、最新の健全なチェックポイントを探索して復元できるようにします。
3. 合成データで20ステップの訓練テストを実行します。ステップ10で保存して中断し、新規プロセスで再開してステップ20まで進めます。
4. 中断なしの基準実行と比較し、ステップ11〜20の損失値が浮点許容誤差(1e-6)内で完全一致することを検証します。

演習と予測記録

作成した CheckpointManager の検証スクリプトを実行し、世代ローテーションと損失値の一致を確認してください。

独立習得基準

中断なし実行と完全に同一の損失曲線を再現するチェックポイントマネージャを構築できる。

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

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

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

該当セクション・タイムスタンプ: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

検証バージョンと日付: PyTorch 2.x Documentation (Verified: 2026-10-30)

選定理由:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

ソース前提知識:

Python, PyTorch tensors and nn.Module basics.

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

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

比較対象候補リソースと選定評価 (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

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.

ソース前提知識:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

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

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

比較対象候補リソースと選定評価 (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.