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.