Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a TF2 keras model with custom signature defs

I have a Keras (sequential) model that could be saved with custom signature defs in Tensorflow 1.13 as follows:

from tensorflow.saved_model.utils import build_tensor_info
from tensorflow.saved_model.signature_def_utils import predict_signature_def, build_signature_def

model = Sequential() // with some layers

builder = tf.saved_model.builder.SavedModelBuilder(export_path)

score_signature = predict_signature_def(
    inputs={'waveform': model.input},
    outputs={'scores': model.output})

metadata = build_signature_def(
    outputs={'other_variable': build_tensor_info(tf.constant(1234, dtype=tf.int64))})

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  builder.add_meta_graph_and_variables(
      sess=sess,
      tags=[tf.saved_model.tag_constants.SERVING],
      signature_def_map={'score': score_signature, 'metadata': metadata})
  builder.save()

Migrating the model to TF2 keras was cool :), but I can't figure out how to save the model with the same signature as above. Should I be using the new tf.saved_model.save() or tf.keras.experimental.export_saved_model()? How should the above code be written in TF2?

Key requirements:

  • The model has a score signature and a metadata signature
  • The metadata signature contains 1 or more constants
like image 666
Antony Harfield Avatar asked Jun 19 '19 04:06

Antony Harfield


People also ask

What is the use of saved model in keras?

SavedModel is the more comprehensive save format that saves the model architecture, weights, and the traced Tensorflow subgraphs of the call functions. This enables Keras to restore both built-in layers as well as custom objects. # Create a simple model. # Train the model. # Calling `save ('my_model')` creates a SavedModel folder `my_model`.

How can I save all the losses and metrics in keras?

A set of losses and metrics (defined by compiling the model or calling add_loss () or add_metric () ). The Keras API makes it possible to save all of these pieces to disk at once, or to only selectively save some of them: Saving everything into a single archive in the TensorFlow SavedModel format (or in the older Keras H5 format).

What are scoped names in keras?

Scoped names include the model/layer names, such as "dense_1/kernel:0". It is recommended that you use the layer properties to access specific variables, e.g. model.get_layer ("dense_1").kernel. Keras SavedModel uses tf.saved_model.save to save the model and all trackable objects attached to the model (e.g. layers and variables).

What does save_traces=false do in keras?

When loading, the custom objects must be passed to the custom_objects argument. save_traces=False reduces the disk space used by the SavedModel and saving time. Keras H5 format Keras also supports saving a single HDF5 file containing the model's architecture, weights values, and compile () information.


1 Answers

The solution is to create a tf.Module with functions for each signature definition:

class MyModule(tf.Module):
  def __init__(self, model, other_variable):
    self.model = model
    self._other_variable = other_variable

  @tf.function(input_signature=[tf.TensorSpec(shape=(None, None, 1), dtype=tf.float32)])
  def score(self, waveform):
    result = self.model(waveform)
    return { "scores": results }

  @tf.function(input_signature=[])
  def metadata(self):
    return { "other_variable": self._other_variable }

And then save the module (not the model):

module = MyModule(model, 1234)
tf.saved_model.save(module, export_path, signatures={ "score": module.score, "metadata": module.metadata })

Tested with Keras model on TF2.

like image 138
Antony Harfield Avatar answered Oct 30 '22 22:10

Antony Harfield