1# Copyright 2018 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"""Functions to convert SavedModel to frozen GraphDefs.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21from tensorflow.lite.python import util 22from tensorflow.core.framework import types_pb2 23from tensorflow.python.client import session 24from tensorflow.python.framework import ops 25from tensorflow.python.platform import tf_logging as logging 26from tensorflow.python.saved_model import constants 27from tensorflow.python.saved_model import loader 28 29 30def _log_tensor_details(tensor_info): 31 """Log tensor details: name, shape, and type.""" 32 for key in tensor_info: 33 val = tensor_info[key] 34 dtype = types_pb2.DataType.Name(val.dtype) 35 if val.tensor_shape.unknown_rank: 36 shape = "unknown_rank" 37 else: 38 dims = [str(dim.size) for dim in val.tensor_shape.dim] 39 shape = "({})".format(", ".join(dims)) 40 41 logging.info("Tensor's key in saved_model's tensor_map: %s", key) 42 logging.info(" tensor name: %s, shape: %s, type: %s", val.name, shape, 43 dtype) 44 45 46def get_meta_graph_def(saved_model_dir, tag_set): 47 """Validate saved_model and extract MetaGraphDef. 48 49 Args: 50 saved_model_dir: saved_model path to convert. 51 tag_set: Set of tag(s) of the MetaGraphDef to load. 52 53 Returns: 54 The meta_graph_def used for tflite conversion. 55 56 Raises: 57 ValueError: No valid MetaGraphDef for given tag_set. 58 """ 59 with session.Session(graph=ops.Graph()) as sess: 60 return loader.load(sess, tag_set, saved_model_dir) 61 62 63def get_signature_def(meta_graph, signature_key): 64 """Get the signature def from meta_graph with given signature_key. 65 66 Args: 67 meta_graph: meta_graph_def. 68 signature_key: signature_def in the meta_graph_def. 69 70 Returns: 71 The signature_def used for tflite conversion. 72 73 Raises: 74 ValueError: Given signature_key is not valid for this meta_graph. 75 """ 76 signature_def_map = meta_graph.signature_def 77 signature_def_keys = set(signature_def_map.keys()) 78 logging.info( 79 "The given SavedModel MetaGraphDef contains SignatureDefs with the " 80 "following keys: %s", signature_def_keys) 81 if signature_key not in signature_def_keys: 82 raise ValueError("No '{}' in the SavedModel\'s SignatureDefs. Possible " 83 "values are '{}'.".format(signature_key, 84 ",".join(signature_def_keys))) 85 return signature_def_map[signature_key] 86 87 88def get_inputs_outputs(signature_def): 89 """Get inputs and outputs from SignatureDef. 90 91 Args: 92 signature_def: SignatureDef in the meta_graph_def for conversion. 93 94 Returns: 95 The inputs and outputs in the graph for conversion. 96 """ 97 inputs_tensor_info = signature_def.inputs 98 outputs_tensor_info = signature_def.outputs 99 logging.info("input tensors info: ") 100 _log_tensor_details(inputs_tensor_info) 101 logging.info("output tensors info: ") 102 _log_tensor_details(outputs_tensor_info) 103 104 def gather_names(tensor_info): 105 return [tensor_info[key].name for key in tensor_info] 106 107 inputs = gather_names(inputs_tensor_info) 108 outputs = gather_names(outputs_tensor_info) 109 return inputs, outputs 110 111 112def _get_tensors(graph, signature_def_tensor_names=None, 113 user_tensor_names=None): 114 """Gets the tensors associated with the tensor names. 115 116 Either signature_def_tensor_names or user_tensor_names should be provided. If 117 the user provides tensors, the tensors associated with the user provided 118 tensor names are provided. Otherwise, the tensors associated with the names in 119 the SignatureDef are provided. 120 121 Args: 122 graph: GraphDef representing graph. 123 signature_def_tensor_names: Tensor names stored in either the inputs or 124 outputs of a SignatureDef. (default None) 125 user_tensor_names: Tensor names provided by the user. (default None) 126 127 Returns: 128 List of tensors. 129 130 Raises: 131 ValueError: 132 signature_def_tensors and user_tensor_names are undefined or empty. 133 user_tensor_names are not valid. 134 """ 135 tensors = [] 136 if user_tensor_names: 137 # Sort the tensor names. 138 user_tensor_names = sorted(user_tensor_names) 139 140 tensors = util.get_tensors_from_tensor_names(graph, user_tensor_names) 141 elif signature_def_tensor_names: 142 tensors = [ 143 graph.get_tensor_by_name(name) 144 for name in sorted(signature_def_tensor_names) 145 ] 146 else: 147 # Throw ValueError if signature_def_tensors and user_tensor_names are both 148 # either undefined or empty. 149 raise ValueError( 150 "Specify either signature_def_tensor_names or user_tensor_names") 151 152 return tensors 153 154 155def freeze_saved_model(saved_model_dir, input_arrays, input_shapes, 156 output_arrays, tag_set, signature_key): 157 """Converts a SavedModel to a frozen graph. 158 159 Args: 160 saved_model_dir: SavedModel directory to convert. 161 input_arrays: List of input tensors to freeze graph with. Uses input arrays 162 from SignatureDef when none are provided. 163 input_shapes: Dict of strings representing input tensor names to list of 164 integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). 165 Automatically determined when input shapes is None (e.g., {"foo" : None}). 166 output_arrays: List of output tensors to freeze graph with. Uses output 167 arrays from SignatureDef when none are provided. 168 tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to 169 analyze. All tags in the tag set must be present. 170 signature_key: Key identifying SignatureDef containing inputs and outputs. 171 172 Returns: 173 frozen_graph_def: Frozen GraphDef. 174 in_tensors: List of input tensors for the graph. 175 out_tensors: List of output tensors for the graph. 176 graph: `Graph` object. 177 178 Raises: 179 ValueError: 180 SavedModel doesn't contain a MetaGraphDef identified by tag_set. 181 signature_key is not in the MetaGraphDef. 182 assets/ directory is in the MetaGraphDef. 183 input_shapes does not match the length of input_arrays. 184 input_arrays or output_arrays are not valid. 185 """ 186 # Read SignatureDef. 187 meta_graph = get_meta_graph_def(saved_model_dir, tag_set) 188 signature_def = get_signature_def(meta_graph, signature_key) 189 inputs, outputs = get_inputs_outputs(signature_def) 190 191 # Check SavedModel for assets directory. 192 collection_def = meta_graph.collection_def 193 if constants.ASSETS_KEY in collection_def: 194 raise ValueError("SavedModels with assets/ directory are not supported.") 195 196 graph = ops.Graph() 197 with session.Session(graph=graph) as sess: 198 loader.load(sess, meta_graph.meta_info_def.tags, saved_model_dir) 199 200 # Gets input and output tensors. 201 # TODO(zhixianyan): Use TFLite supported Op list to filter outputs. 202 in_tensors = _get_tensors(graph, inputs, input_arrays) 203 out_tensors = _get_tensors(graph, outputs, output_arrays) 204 util.set_tensor_shapes(in_tensors, input_shapes) 205 206 frozen_graph_def = util.freeze_graph(sess, in_tensors, out_tensors) 207 return frozen_graph_def, in_tensors, out_tensors, sess.graph 208