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.