1# Copyright 2019 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Classes and functions implementing to Model SavedModel serialization.""" 16 17from tensorflow.python.keras.saving import saving_utils 18from tensorflow.python.keras.saving.saved_model import constants 19from tensorflow.python.keras.saving.saved_model import layer_serialization 20from tensorflow.python.keras.saving.saved_model import save_impl 21 22 23class ModelSavedModelSaver(layer_serialization.LayerSavedModelSaver): 24 """Model SavedModel serialization.""" 25 26 @property 27 def object_identifier(self): 28 return constants.MODEL_IDENTIFIER 29 30 def _python_properties_internal(self): 31 metadata = super(ModelSavedModelSaver, self)._python_properties_internal() 32 # Network stateful property is dependent on the child layers. 33 metadata.pop('stateful') 34 metadata['is_graph_network'] = self.obj._is_graph_network # pylint: disable=protected-access 35 metadata['save_spec'] = self.obj._get_save_spec(dynamic_batch=False) # pylint: disable=protected-access 36 37 metadata.update( 38 saving_utils.model_metadata( 39 self.obj, include_optimizer=True, require_config=False)) 40 return metadata 41 42 def _get_serialized_attributes_internal(self, serialization_cache): 43 default_signature = None 44 45 # Create a default signature function if this is the only object in the 46 # cache (i.e. this is the root level object). 47 if len(serialization_cache[constants.KERAS_CACHE_KEY]) == 1: 48 default_signature = save_impl.default_save_signature(self.obj) 49 50 # Other than the default signature function, all other attributes match with 51 # the ones serialized by Layer. 52 objects, functions = ( 53 super(ModelSavedModelSaver, self)._get_serialized_attributes_internal( 54 serialization_cache)) 55 functions['_default_save_signature'] = default_signature 56 return objects, functions 57 58 59class SequentialSavedModelSaver(ModelSavedModelSaver): 60 61 @property 62 def object_identifier(self): 63 return constants.SEQUENTIAL_IDENTIFIER 64