57 / 90

第 57 天:系統容錯、損壞檢查點自癒與競價實例賬單防線

排查截斷破損檢查點、strict=False 局部權重與詞表擴充、SIGTERM 競價實例搶佔捕捉與雲端賬單止損。

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

損壞、截斷與不相容檢查點的精準診斷與自動回退

Agent 輔助工程檢查

前置要求

第 55 天檢查點基礎與 Python 異常處理機制。

學習目標

診斷非完整寫入造成的截斷文件(EOFError、UnpicklingError 反序列化崩潰),集成 SHA256 校驗和旁路驗證,並實現自動向後遍歷健康歷史快照的自癒回退管線。

操作指引

1. 探究進程非正常退出導致的半寫故障特徵:文件位元組數不為零,但末尾結構殘缺。
2. 直接調用 torch.load 會拋出 _pickle.UnpicklingError: pickle data was truncated 或 EOFError。
3. 實現旁路雜湊校驗機制:落盤時同步輸出 'ckpt.pt.sha256',加載前執行雜湊比對,快速剔除受損文件。
4. 構建多級自動回退機制:當最新快照(如 step 10000)校驗失敗或反序列化崩潰時,無縫降級嘗試 step 9000 快照並記錄告警日誌。

自主實作與記錄

編寫容錯加載函數 safe_load_checkpoint(checkpoint_dir),逆序掃描目錄下的所有快照,安全捕獲損壞異常,成功定位並加載最新可用的完整快照。

獨立掌握標準

在最新快照被截斷損壞的嚴苛測試下,系統能自動降級並成功從次新快照無縫恢復。

權威來源資源與權利證明

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.

02 120 分鐘

局部權重加載、詞表擴充與 strict 模式精細控制

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

前置要求

第 57 天活動 1 與 PyTorch 模組參數管理原理。

學習目標

掌握架構變更場景下 strict=False 的安全加載規範,細緻審計 missing_keys 與 unexpected_keys,並實現新增特殊 Token 時詞表嵌入權重的無縫擴充與相容保真。

操作指引

1. 深入分析 load_state_dict(..., strict=False) 返回的 NamedTuple:詳細審查 missing_keys(缺失鍵)與 unexpected_keys(冗餘鍵)。
2. 掌握詞表擴充(Vocabulary Expansion)標準範式:當引入新的控制符或特殊 Token 時,詞表大小由 V_old 擴展至 V_new。
3. 權重對齊與初始化:將舊模型 [V_old, d] 權重完整複製至新張量的前 V_old 行,新增的 Token 向量採用高斯分布(std=0.02)小方差初始化。
4. 規避隱蔽的靜默錯誤:嚴防因層命名拼寫細微差異導致關鍵層未被加載卻被 strict=False 靜默忽略的隱患。

自主實作與記錄

將一個詞表為 100 的小型模型擴展至 105 個 Token。使用 strict=False 加載原有權重,遷移舊詞向量並合理初始化新增的 5 個向量,斷言前 100 個 Token 的前向輸出與舊模型完全一致。

獨立掌握標準

成功完成詞表擴增且原有 Token 的模型輸出 logits 保持 100% 相同。

權威來源資源與權利證明

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

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

對應章節 / 時間戳: Warmstarting Model Using Parameters from a Different Model (strict=False)

驗證版本與日期: 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: init_from == 'resume' branch (strips the '_orig_mod.' prefix, then model.load_state_dict)

驗證版本與日期: 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 分鐘

雲端競價實例搶佔信號(SIGTERM)捕獲與賬單防禦機制

Agent 輔助工程檢查

前置要求

第 57 天活動 1,Linux POSIX 進程信號與雲端競價(Spot)經濟學。

學習目標

通過 Python signal 模組註冊 SIGTERM/SIGINT 系統信號處理器,在雲廠商回收競價 GPU 實例前觸發緊急原子持久化,徹底杜絕已消耗算力成果的蒸發與預算浪費。

操作指引

1. 洞察雲端競價(Spot/Preemptible)實例特性:享受高達 70%-90% 算力折扣,但在資源緊缺時雲廠商會通過 SIGTERM 發出回收預警(通常寬限 30 - 120 秒)。
2. 使用 Python signal.signal(signal.SIGTERM, sigterm_handler) 監聽系統終止信號。
3. 嚴禁在信號回調中執行繁重的 I/O 操作;標準做法是在回調中將全局退出標誌位置為 True,在當前訓練 step 計算結束後立即觸發緊急原子快照並返回 0 退出。
4. 權衡持久化頻次與磁盤 I/O 成本:步步存盤嚴重拖累 GPU 吞吐;頻次過低則單次中斷損失過大。制定智慧動態存盤策略。

自主實作與記錄

編寫包含 SIGTERM 監聽器的訓練循環腳本。模擬向主進程發送 kill -15 信號,驗證程序能夠捕獲信號、完整執行當前 step、落盤 emergency_ckpt.pt 並安全退出。

獨立掌握標準

成功捕獲系統級搶佔信號並在進程終止前可靠保存緊急檢查點。

權威來源資源與權利證明

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.

linking CC-BY 4.0

Transformer Math 101

作者 / 機構: Quentin Anthony, Stella Biderman, Hailey Schoelkopf | 原始出處連結 ↗

對應章節 / 時間戳: N/A

驗證版本與日期: EleutherAI Research Blog (Verified: 2026-10-30)

入選理由:

Widely cited, practical industry guide deriving 6ND compute FLOPs, activation memory, KV cache size, and VRAM estimation.

來源前置條件:

Transformer matrix dimensions and matrix multiplication FLOP counting.

安全回退方案(離線彈性):

The 6ND derivation (2ND forward, 4ND backward) and peak VRAM estimation models are fully worked out in the curriculum.

對比候選資源與選型分析 (2)

Rigorous academic formulation; Transformer Math 101 provides accessible step-by-step arithmetic equations.

Kaplan et al. Section 2.1 Compute Budgeting ↗ compared_alternative [Open Access]

Original 6ND approximation; EleutherAI expands on activation memory and KV cache.

04 120 分鐘

考核評估:搶佔崩潰與數據損壞注入模擬實戰演練

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

前置要求

第 57 天活動 1 至 3 全部內容。

學習目標

執行全流程混沌故障注入測試:模擬隨機 SIGTERM 搶佔殺進程與檢查點位元組損壞,全面驗證訓練管線的自動化自癒恢復能力。

操作指引

1. 編寫 30 步訓練測試驅動腳本。
2. 在第 10 步時注入 SIGTERM 信號,斷言緊急快照成功輸出且進程優雅退出。
3. 在第 20 步時主動破壞最新檢查點文件(向末尾寫入 512 位元組全零數據模擬磁盤壞塊)。
4. 再次啟動訓練程序,斷言系統能夠精準識別第 20 步快照損壞,安全回退至上一有效快照,並順利續訓完成全部 30 步,驗證最終損失正常收斂。

自主實作與記錄

運行自動化故障注入測試套件,確認系統全程無崩潰,成功從歷史快照自癒並達成預期訓練步數。

獨立掌握標準

在遭遇突發搶佔與檢查點物理損壞雙重故障下,系統均能零人工介入自動恢復並成功收斂。

權威來源資源與權利證明

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.