55 / 90

第 55 天:檢查點結構、狀態字典與安全斷點續訓

原子化持久化 PyTorch 權重、緩衝區、優化器動量、調度器狀態與隨機種子,確保訓練無損續航。

模型與預訓練 480 分鐘有效研習(8 小時)
01 120 分鐘

模型狀態字典(state_dict)與張量序列化機制

Agent 輔助工程檢查

前置要求

完成第 54 天 Transformer 考核,掌握 PyTorch Module 核心原理。

學習目標

深入掌握 model.state_dict() 的底層字典映射結構、可學習參數與持久化緩衝區的區別,以及跨設備序列化(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 底層依賴 Python pickle 機制打包張量元數據與原始存儲區。
3. 對比保存完整 Python 模型對象與保存純 state_dict 的差異,領會官方標準推薦 state_dict 的解耦與版本穩定性優勢。
4. 實踐 map_location='cpu' 選項,消除在無 GPU 或不同卡號設備上加載權重時的 CUDA 報錯風險。

自主實作與記錄

實例化一個小型的 2 層 GPT 模型,將其 state_dict 持久化至 'ckpt_model.pt'。重新創建一個新的隨機初始化模型,使用 map_location='cpu' 恢復權重,並斷言兩者的每一個參數張量完全逐元素相等。

獨立掌握標準

能準確提取與序列化 state_dict,並在新建模型上達成 100% 精度參數還原。

權威來源資源與權利證明

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者 / 機構: Stanford University CS336 Staff | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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 分鐘

優化器狀態字典、學習率調度器與隨機狀態持久化

獨立掌握檢查(無 AI 輔助)

前置要求

第 55 天活動 1 基礎與 Adam 優化器數學原理。

學習目標

完整保存 Adam 一階與二階動量、步數計數器以及全局隨機種子狀態,徹底根除續訓初期的損失劇烈突變(Loss Spike)。

操作指引

1. 審查 optimizer.state_dict(),分析其由 'state'(包含各參數的 'step', 'exp_avg', 'exp_avg_sq')與 'param_groups' 組成的結構。
2. 理解為何僅保存模型權重會導致續訓災難:Adam 動量歸零將導致梯度更新方向與尺度劇烈震盪。
3. 將 torch.get_rng_state()、CUDA 隨機狀態與 Python/NumPy 隨機種子共同封入檢查點字典。
4. 設計標準化檢查點負載,涵蓋 step、model、optimizer、scheduler、best_val_loss 與 rng_states。

自主實作與記錄

使用 AdamW 運行 5 步訓練並保存完整檢查點。從檢查點載入全新的模型與優化器繼續執行第 6 步,驗證其計算出的損失與不中斷基準運行的第 6 步損失在浮點精度下完全一致。

獨立掌握標準

實現優化器與 RNG 狀態的無損恢復,斷點續訓損失與連續運行完全吻合。

權威來源資源與權利證明

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

作者 / 機構: PyTorch Documentation Team | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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. 認識直接覆寫目標文件 'ckpt.pt' 的致命隱患:寫入中途若遭遇斷電或 SIGKILL,現有健康檢查點即刻損毀且無法復原。
2. 掌握基於同目錄下臨時文件(如 'ckpt.pt.tmp')先全量落盤並執行 os.fsync,再使用 os.replace 原子覆蓋的安全範式。
3. 在檢查點頭部嵌入 'version': 1、'format': 'nanogpt-v1' 與 SHA-256 校驗和,確保反序列化前能夠驗證架構相容性。
4. 實現滾動快照保留機制(keep_last_n),新文件安全入庫後再清理陳舊快照。

自主實作與記錄

編寫 Python 函數 save_checkpoint_atomic(payload, filepath),通過同級臨時文件與 os.replace 落地原子寫。構造中斷測試驗證原始檢查點從未處於殘缺狀態。

獨立掌握標準

編寫出能抵抗斷電中斷且永不破壞已有有效檢查點的原子持久化函數。

權威來源資源與權利證明

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

作者 / 機構: PyTorch Documentation Team | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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 類,實現原子落盤、快照配額管理與 100% 精度連續損失軌跡驗證。

操作指引

1. 封裝 CheckpointManager(checkpoint_dir, max_to_keep=3) 類。
2. 實現 save(...) 與 load_latest(...) 接口,自動檢索最新有效快照,並維護歷史文件數量上限。
3. 編寫雙軌驗證測試:軌道 A 連續執行 20 步訓練;軌道 B 運行至第 10 步時保存並模擬進程退出,隨後載入快照續訓至第 20 步。
4. 對比軌道 A 與軌道 B 在第 11 至 20 步的 loss 數值,驗證兩者在 1e-6 浮點容差內完全重合。

自主實作與記錄

運行 CheckpointManager 驗證套件,確認快照輪轉邏輯無異常,斷點續訓損失軌跡與連續基準完全一致。

獨立掌握標準

構建出具備原子保存與自動快照清理的管理器,並通過完全重合的連續訓練損失軌跡驗證。

權威來源資源與權利證明

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

作者 / 機構: PyTorch Documentation Team | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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.