蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

保存并重载真实模型、推理端点与可续训状态

PYTHONWindows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。verify-model-artifact-formats.py
verify-model-artifact-formats.py202 行
"""Compare Keras archives, legacy HDF5, SavedModel endpoints, and resumable checkpoints."""
from hashlib import file_digest
from pathlib import Path
from tempfile import TemporaryDirectory
import json
import platform

import h5py
import numpy as np
import tensorflow as tf
from tensorflow import keras


def digest(path):
    with path.open("rb") as stream:
        return file_digest(stream,"sha256").hexdigest()


def observe(cases,name,operation,inputs,expected,actual,measurements=None):
    assert actual==expected,(name,expected,actual)
    row=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
    if measurements is not None:
        row["measurements"]=measurements
    cases.append(row)


def fresh(width=12, compiled=True):
    model=keras.Sequential([keras.Input((3,),name="features"),keras.layers.Dense(width,activation="relu"),
                            keras.layers.Dense(3,activation="softmax")])
    if compiled:
        configure(model)
    return model


def configure(model):
    model.compile(optimizer=keras.optimizers.Adam(0.01),loss=keras.losses.SparseCategoricalCrossentropy(),
        metrics=[keras.metrics.SparseCategoricalAccuracy(name="accuracy")])


def match(model,values,reference):
    return bool(np.allclose(model(values,training=False).numpy(),reference,atol=1e-6))


def failure(function):
    try:
        function()
    except ValueError as exc:
        return str(exc)
    raise AssertionError("Expected ValueError for this incompatible format.")


@keras.utils.register_keras_serializable(package="BlueSkyTutorial")
class LinearFeatureMap(keras.layers.Layer):
    def __init__(self, units, gain=1., **kwargs):
        super().__init__(**kwargs)
        self.units=units
        self.gain=gain

    def build(self,input_shape):
        self.kernel=self.add_weight(name="kernel",shape=(int(input_shape[-1]),self.units),initializer="glorot_uniform")

    def call(self,inputs):
        return tf.matmul(inputs,self.kernel)*self.gain

    def get_config(self):
        return {**super().get_config(),"units":self.units,"gain":self.gain}


def main():
    keras.utils.set_random_seed(1907)
    rng=np.random.default_rng(1913)
    values=rng.normal(size=(24,3)).astype(np.float32)
    labels=np.argmax(values,axis=1).astype(np.int32)
    options=tf.data.Options()
    options.threading.private_threadpool_size=1
    dataset=tf.data.Dataset.from_tensor_slices((values,labels)).with_options(options).batch(8)
    cases=[]
    trained=fresh()
    trained.fit(dataset,epochs=3,verbose=0,shuffle=False)
    target=trained(values[:5],training=False).numpy()
    trained_steps=int(trained.optimizer.iterations)
    assert trained_steps==9

    with TemporaryDirectory(prefix="blue-sky-artifact-format-") as directory:
        root=Path(directory)
        modern=root/"classifier.keras"
        legacy=root/"classifier.h5"
        export=root/"serving"/"1"
        weights=root/"classifier.weights.h5"
        trained.save(modern)
        restored=keras.models.load_model(modern)
        observe(cases,"keras_archive_resume","Restore architecture, inference, compile configuration and Adam iteration state",
            {"input":[5,3],"initial_updates":9},[True,9,"Adam"],
            [match(restored,values[:5],target),int(restored.optimizer.iterations),type(restored.optimizer).__name__],
            {"sha256":digest(modern),"bytes":modern.stat().st_size})
        compared_original=trained.train_on_batch(values[:8],labels[:8])
        compared_reloaded=restored.train_on_batch(values[:8],labels[:8])
        observe(cases,"keras_next_update","Apply the same next update to live and .keras-restored models",
            {"batch_rows":8},[10,10,True,True],
            [int(trained.optimizer.iterations),int(restored.optimizer.iterations),
             match(restored,values[:5],trained(values[:5],training=False).numpy()),
             bool(np.allclose(compared_original,compared_reloaded,atol=1e-6))])
        target=trained(values[:5],training=False).numpy()

        legacy_path_errors=[failure(lambda:trained.save(root/"old_style")),
            failure(lambda:trained.save_weights(root/"custom.h5"))]
        observe(cases,"keras3_extension_errors","Check extension diagnostics for the old extensionless saves and weight filename",
            {"operations":["save without extension","save_weights with plain h5"]},[True,True],
            ["extension" in legacy_path_errors[0].lower(),".weights.h5" in legacy_path_errors[1]],legacy_path_errors)

        trained.export(export,format="tf_saved_model",verbose=False)
        names=sorted(path.relative_to(export).as_posix() for path in export.rglob("*") if path.is_file())
        loaded=tf.saved_model.load(export)
        served=loaded.serve(tf.constant(values[:5])).numpy()
        endpoint=loaded.signatures["serving_default"]
        inputs=endpoint.structured_input_signature[1]
        output=endpoint(**{next(iter(inputs)):tf.constant(values[:5])})
        nested=keras.Sequential([keras.Input((3,)),keras.layers.TFSMLayer(export,call_endpoint="serve")])
        observe(cases,"savedmodel_endpoint","Read the exported graph and run the serve signature and TFSMLayer on real tensors",
            {"model_version":1,"batch_shape":[5,3]},[True,True,True,True,True],
            ["saved_model.pb" in names,"variables/variables.index" in names,
             bool(np.allclose(served,target,atol=1e-6)),
             bool(np.allclose(next(iter(output.values())).numpy(),target,atol=1e-6)),
             match(nested,values[:5],target)],
            {"files":[dict(name=name,sha256=digest(export/name),bytes=(export/name).stat().st_size) for name in names],
             "endpoints":sorted(loaded.signatures),"named_inputs":list(inputs),
             "input_dtype":next(iter(inputs.values())).dtype.name})
        error=failure(lambda:keras.models.load_model(export))
        observe(cases,"keras_loader_rejects_savedmodel","Use the Keras whole-model loader on the SavedModel folder and inspect the diagnostic",
            {"format":"tf_saved_model"},[True],["SavedModel" in error],error)

        trained.save(legacy)
        with h5py.File(legacy,"r") as content:
            groups=sorted(content.keys())
        h5=keras.models.load_model(legacy,compile=False)
        configure(h5)
        h5_evaluation=h5.evaluate(dataset,verbose=0,return_dict=True)
        observe(cases,"legacy_hdf5_round_trip","Inspect HDF5 contents, load with compile=False and evaluate with an explicit fresh optimizer",
            {"extension":".h5"},[True,True,0,True],
            ["model_weights" in groups,match(h5,values[:5],target),int(h5.optimizer.iterations),
             bool(np.isfinite(list(h5_evaluation.values())).all())],
            {"groups":groups,"sha256":digest(legacy),"bytes":legacy.stat().st_size,"evaluation":h5_evaluation})

        trained.save_weights(weights)
        rebuilt=fresh(compiled=False)
        rebuilt.load_weights(weights)
        error=failure(lambda:fresh(width=4,compiled=False).load_weights(weights))
        observe(cases,"weight_file_matching_architecture","Restore weights into matching architecture and detect an incompatible hidden layer",
            {"width_saved":12,"width_mismatch":4},[True,True],
            [match(rebuilt,values[:5],target),"could not be loaded" in error],
            {"sha256":digest(weights),"bytes":weights.stat().st_size,
             "whole_model_bytes":modern.stat().st_size,"legacy_bytes":legacy.stat().st_size,
             "savedmodel_bytes":sum((export/name).stat().st_size for name in names)})

        callback_path=root/"latest.weights.h5"
        callback=keras.callbacks.ModelCheckpoint(callback_path,save_weights_only=True,save_freq="epoch")
        trained.fit(dataset,epochs=2,callbacks=[callback],verbose=0,shuffle=False)
        again=fresh(compiled=False)
        again.load_weights(callback_path)
        observe(cases,"epoch_weight_callback","Write a weights checkpoint after each epoch and compare the last saved weights",
            {"epochs":2},[True,True],[callback_path.is_file(),match(again,values[:5],trained(values[:5]).numpy())],
            {"sha256":digest(callback_path),"bytes":callback_path.stat().st_size})

        step=tf.Variable(7,dtype=tf.int64)
        checkpoint=tf.train.Checkpoint(model=trained,optimizer=trained.optimizer,step=step)
        manager=tf.train.CheckpointManager(checkpoint,str(root/"steps"),max_to_keep=2)
        saved=manager.save()
        resume=fresh()
        resume.optimizer.build(resume.trainable_variables)
        resumed_step=tf.Variable(0,dtype=tf.int64)
        resume_checkpoint=tf.train.Checkpoint(model=resume,optimizer=resume.optimizer,step=resumed_step)
        resume_checkpoint.restore(saved).assert_consumed()
        iterations=int(resume.optimizer.iterations)
        before=match(resume,values[:5],trained(values[:5]).numpy())
        trained.train_on_batch(values[:8],labels[:8])
        resume.train_on_batch(values[:8],labels[:8])
        observe(cases,"explicit_tracking_checkpoint","Restore model, optimizer slots and a custom training step then compare the next update",
            {"expected_optimizer_before":16,"custom_step":7},[16,7,True,True],
            [iterations,int(resumed_step),before,match(resume,values[:5],trained(values[:5]).numpy())],
            {"members":[path.name for path in (root/"steps").iterdir()]})

        custom=keras.Sequential([keras.Input((3,)),LinearFeatureMap(5,gain=.7)])
        custom_output=custom(values[:3],training=False).numpy()
        custom_archive=root/"custom.keras"
        custom.save(custom_archive)
        restored_custom=keras.models.load_model(custom_archive,safe_mode=True)
        custom_export=root/"custom-serving"
        custom.export(custom_export,verbose=False)
        loaded_custom=tf.saved_model.load(custom_export)
        observe(cases,"serialized_custom_layer","Keep constructor data in get_config and compare both .keras reload and graph export",
            {"units":5,"gain":.7},[5,.7,True,True],
            [restored_custom.layers[0].units,restored_custom.layers[0].gain,match(restored_custom,values[:3],custom_output),
             bool(np.allclose(loaded_custom.serve(tf.constant(values[:3])).numpy(),custom_output,atol=1e-6))],
            {"keras_archive_sha256":digest(custom_archive),"savedmodel_sha256":digest(custom_export/"saved_model.pb")})

    print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
        system=platform.system(),devices=[device.name for device in tf.config.list_physical_devices()],cases=cases)))


if __name__=="__main__":
    main()
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

入口文件:projects/tensorflow-save-load-lab/verify-model-artifact-formats.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 verify-model-artifact-formats.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip

下载课程关联工程包:TensorFlow

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a378.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习