TensorFlow 源码拆解

11 · 持久化与可观测性:模型如何离开进程

SavedModel、Checkpoint、Profiler 与调试工具的共同边界

SavedModel 保存的是可调用资产

SavedModel 以 protobuf、变量 checkpoint 和 assets 组成目录,核心是 Trackable object graph 与 SignatureDef。一个 signature 指向 ConcreteFunction 的输入输出,ConcreteFunction 又引用 FunctionDef、captured resources 和变量。这样加载方可以在不恢复原始 Python 类的情况下调用已导出的函数,但自定义 Python 行为若没有被 tracing/序列化覆盖就不会自动回来。

SavedModel/
  ├─ saved_model.pb          meta graph + signatures
  ├─ variables/              checkpoint shards + index
  └─ assets/                 vocabulary / external files

Checkpoint 与模型格式不同

Checkpoint 更接近 Trackable 对象图的变量快照,适合继续训练;SavedModel 更接近可部署的函数接口,适合服务/转换。Keras model.save、tf.train.Checkpoint 和 TFLite converter 的入口不同,但最终都必须处理变量、资源、函数签名和版本兼容。

Profiler 观察的是时间线

TensorFlow profiler 同时记录 Python、Executor、device stream、kernel、memory、input pipeline 和 collective 事件。单看 wall time 只能知道慢,时间线才能区分:

  • Python trace/retrace 多;
  • input pipeline 没供上;
  • device copy 或 host synchronization 多;
  • kernel 未融合/launch 太碎;
  • collective 等待或负载不均。

调试钩子与正确性

tf.debugging、check numerics、device placement logging、graph dumps、execution trace 和 C++ VLOG 属于不同层次。调试时尽量把观察点放在边界:Python 输入、ConcreteFunction signature、GraphDef、kernel selection、device output。过早把所有日志打开会改变异步时序和性能。

兼容性是多维的

模型可移植性至少包含:dtype/shape、op set、变量命名、资源类型、版本、硬件和序列化 schema。Release notes 中的 breaking change 可能只影响某个 API,却通过 SavedModel、Keras 或 TFLite 传播到下游。发布文档应与代码、API golden files、converter 和测试同时更新。

源码锚点

  • tensorflow/python/saved_model/:加载、保存、signature、builder。
  • tensorflow/python/trackable/:对象图与 checkpoint。
  • tensorflow/python/keras/saving/:Keras 到 SavedModel 的序列化。
  • tensorflow/core/profiler/:profiler 数据采集与事件模型。
  • tensorflow/python/profiler/:Python profiler API。
  • tensorflow/tools/graph_transforms/:图导出与转换工具。

最后一条主线

训练结束时,模型不是“一个 Python 对象”了,而是一组可被其他 runtime 重新解释的协议资产:签名告诉调用者怎么传参,函数库告诉 runtime 怎么调用,checkpoint 提供状态,assets 提供外部资源,schema 和版本共同定义兼容边界。

On this page