xref: /aosp_15_r20/external/tensorflow/tensorflow/python/saved_model/load_options.py (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1# Copyright 2020 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"""Options for saving SavedModels."""
16
17from tensorflow.python.saved_model import save_options
18from tensorflow.python.util.tf_export import tf_export
19
20
21@tf_export("saved_model.LoadOptions", v1=[])
22class LoadOptions(object):
23  """Options for loading a SavedModel.
24
25  This function may be used in the `options` argument in functions that
26  load a SavedModel (`tf.saved_model.load`, `tf.keras.models.load_model`).
27  """
28
29  # Define object attributes in __slots__ for improved memory and performance.
30  __slots__ = ("allow_partial_checkpoint", "experimental_io_device",
31               "experimental_skip_checkpoint", "experimental_variable_policy")
32
33  def __init__(self,
34               allow_partial_checkpoint=False,
35               experimental_io_device=None,
36               experimental_skip_checkpoint=False,
37               experimental_variable_policy=None):
38    """Creates an object that stores options for SavedModel loading.
39
40    *When to set `allow_partial_checkpoint=True`?*
41
42    This can be used when loading a Keras model (`tf.keras.models.load_model`)
43    with custom objects. When new variables are added to the custom object
44    class, loading will fail the assertion check that all loaded variables have
45    been restored, because the SavedModel checkpoint only contains the variables
46    that were in original the custom object.
47    See the following example:
48
49    ```
50    class Custom(tf.keras.Model):
51      def __init__(self):
52        super(Custom, self).__init__()
53        self.v = tf.Variable(...)
54
55      def call(self, inputs):
56        return ...
57
58    model = Custom()
59    model.save(...)
60    ```
61
62    After saving, say that `Custom` is updated to include an additional
63    variable.
64
65    ```
66    class Custom(tf.keras.Model):
67      def __init__(self):
68        super(Custom, self).__init__()
69        self.v = tf.Variable(...)
70        self.w = tf.Variable(...)
71
72      def call(self, inputs):
73        return ...
74    ```
75
76    `tf.keras.models.load_model(path, custom_objects={'Custom': Custom})` fails
77    to load since `Custom.w` does not exist in the SavedModel checkpoint. To
78    acknowledge that there are variables that are not restored from the
79    checkpoint and successfully load the model, call:
80
81    ```
82    tf.keras.models.load_model(
83      path, custom_objects={'Custom': Custom},
84      options=tf.saved_model.LoadOptions(allow_partial_checkpoint=True))
85    ```
86
87    Args:
88      allow_partial_checkpoint: bool. Defaults to `False`. When enabled, allows
89        the SavedModel checkpoint to not entirely match the loaded object.
90      experimental_io_device: string. Applies in a distributed setting.
91        Tensorflow device to use to access the filesystem. If `None` (default)
92        then for each variable the filesystem is accessed from the CPU:0 device
93        of the host where that variable is assigned. If specified, the
94        filesystem is instead accessed from that device for all variables.
95        This is for example useful if you want to load from a local directory,
96        such as "/tmp" when running in a distributed setting. In that case
97        pass a device for the host where the "/tmp" directory is accessible.
98      experimental_skip_checkpoint: bool. Defaults to `False`. If set to `True`,
99        checkpoints will not be restored. Note that this in the majority of
100        cases will generate an unusable model.
101      experimental_variable_policy: string. The policy to apply to variables
102        when loading. This is either a `saved_model.experimental.VariablePolicy`
103        enum instance or one of its value strings (case is not important). See
104        that enum documentation for details. A value of `None` corresponds to
105        the default policy.
106
107    Example:
108
109      load_options = tf.saved_model.LoadOptions(experimental_io_device=
110        '/job:localhost')
111      restoredmodel = tf.keras.models.load_model(saved_model_path,
112                                                 options=load_options)
113
114    """
115    self.experimental_io_device = experimental_io_device
116    self.allow_partial_checkpoint = allow_partial_checkpoint
117    self.experimental_skip_checkpoint = experimental_skip_checkpoint
118    self.experimental_variable_policy = (
119        save_options.VariablePolicy.from_obj(experimental_variable_policy))
120