破損・途絶・互換性のないチェックポイントの診断と自動フォールバック
Agent支援エンジニアリングチェック
前提条件
第55日チェックポイント知識および例外処理の仕組み。
学習目標
書き込み途中で中断した不完全ファイルの破損(EOFError、UnpicklingError)を検出し、SHA256ハッシュ検証および過去の健全なスナップショットへの自動フォールバックを実装する。
手順
1. 書き込み途絶によるファイル障害モード(非ゼロサイズだが途中で切断されたpickleデータ)を学習します。
2. 不完全なチェックポイントに対する torch.load は _pickle.UnpicklingError や EOFError を送出します。
3. 'ckpt.pt.sha256' ハッシュファイルの併用により、ロード前に破損を瞬時に検知する仕組みを実装します。
4. 最新スナップショットが破損している場合に、1世代前の健全なスナップショットへ自動的にフォールバックするロジックを構築します。
演習と予測記録
意図的に末尾を切り詰めた破損チェックポイントが存在する状況下で、過去の健全なチェックポイントを自動検出して安全にロードする safe_load_checkpoint 関数を実装してください。
スナップショットを逆順(sorted(files, reverse=True))に走査します。.sha256 ファイルがあれば先にハッシュを検証し、torch.load を try/except (EOFError, RuntimeError, Exception) で囲んで、失敗したファイルはスキップします。
import os, torch, hashlib
def safe_load_checkpoint(ckpt_dir):
files = sorted([f for f in os.listdir(ckpt_dir) if f.startswith('ckpt_') and f.endswith('.pt')], reverse=True)
for fname in files:
path = os.path.join(ckpt_dir, fname)
try:
if os.path.exists(path + '.sha256'):
with open(path, 'rb') as f:
digest = hashlib.sha256(f.read()).hexdigest()
with open(path + '.sha256') as f:
if f.read().split()[0] != digest:
raise ValueError('sha256 mismatch')
ckpt = torch.load(path, map_location='cpu')
print(f'Successfully recovered from {fname}')
return ckpt
except Exception as e:
print(f'Skipping corrupted checkpoint {fname}: {e}')
raise RuntimeError('No valid checkpoint found in directory')
破損ファイルを安全にスキップし、直近の健全なチェックポイントから復旧できる。
公式ソースリソースと権利証跡
PyTorch Tutorial: Saving and Loading Models
該当セクション・タイムスタンプ: 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 trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.
Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.
nanoGPT: train.py pretraining loop
該当セクション・タイムスタンプ: 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)
High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.
High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.