1# Copyright 2015 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"""A utility function for importing TensorFlow graphs."""
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import contextlib
21
22from tensorflow.core.framework import graph_pb2
23from tensorflow.python import tf2
24from tensorflow.python.client import pywrap_tf_session as c_api
25from tensorflow.python.framework import c_api_util
26from tensorflow.python.framework import device as pydev
27from tensorflow.python.framework import errors
28from tensorflow.python.framework import function
29from tensorflow.python.framework import op_def_registry
30from tensorflow.python.framework import ops
31from tensorflow.python.ops import control_flow_util
32from tensorflow.python.util import compat
33from tensorflow.python.util.deprecation import deprecated_args
34from tensorflow.python.util.tf_export import tf_export
35
36
37def _IsControlInput(input_name):
38  # Expected format: '^operation_name' (control input).
39  return input_name.startswith('^')
40
41
42def _ParseTensorName(tensor_name):
43  """Parses a tensor name into an operation name and output index.
44
45  This function will canonicalize tensor names as follows:
46
47  * "foo:0"       -> ("foo", 0)
48  * "foo:7"       -> ("foo", 7)
49  * "foo"         -> ("foo", 0)
50  * "foo:bar:baz" -> ValueError
51
52  Args:
53    tensor_name: The name of a tensor.
54
55  Returns:
56    A tuple containing the operation name, and the output index.
57
58  Raises:
59    ValueError: If `tensor_name' cannot be interpreted as the name of a tensor.
60  """
61  components = tensor_name.split(':')
62  if len(components) == 2:
63    # Expected format: 'operation_name:output_index'.
64    try:
65      output_index = int(components[1])
66    except ValueError:
67      raise ValueError('Cannot convert %r to a tensor name.' % (tensor_name,))
68    return components[0], output_index
69  elif len(components) == 1:
70    # Expected format: 'operation_name' (implicit 0th output).
71    return components[0], 0
72  else:
73    raise ValueError('Cannot convert %r to a tensor name.' % (tensor_name,))
74
75
76@contextlib.contextmanager
77def _MaybeDevice(device):
78  """Applies the given device only if device is not None or empty."""
79  if device:
80    with ops.device(device):
81      yield
82  else:
83    yield
84
85
86def _ProcessGraphDefParam(graph_def):
87  """Type-checks and possibly canonicalizes `graph_def`."""
88  if not isinstance(graph_def, graph_pb2.GraphDef):
89    # `graph_def` could be a dynamically-created message, so try a duck-typed
90    # approach
91    try:
92      old_graph_def = graph_def
93      graph_def = graph_pb2.GraphDef()
94      graph_def.MergeFrom(old_graph_def)
95    except TypeError:
96      raise TypeError('graph_def must be a GraphDef proto.')
97  else:
98    # If we're using the graph_def provided by the caller, modify graph_def
99    # in-place to add attr defaults to the NodeDefs (this is visible to the
100    # caller).
101    # NOTE(skyewm): this is undocumented behavior that at least meta_graph.py
102    # depends on. It might make sense to move this to meta_graph.py and have
103    # import_graph_def not modify the graph_def argument (we'd have to make sure
104    # this doesn't break anything else.)
105    for node in graph_def.node:
106      op_def = op_def_registry.get(node.op)
107      if op_def is None:
108        # Assume unrecognized ops are functions for now. TF_ImportGraphDef will
109        # report an error if the op is actually missing.
110        continue
111      _SetDefaultAttrValues(node, op_def)
112
113  return graph_def
114
115
116def _ProcessInputMapParam(input_map):
117  """Type-checks and possibly canonicalizes `input_map`."""
118  if input_map is None:
119    input_map = {}
120  else:
121    if not (isinstance(input_map, dict) and all(
122        isinstance(k, compat.bytes_or_text_types) for k in input_map.keys())):
123      raise TypeError('input_map must be a dictionary mapping strings to '
124                      'Tensor objects.')
125  return input_map
126
127
128def _ProcessReturnElementsParam(return_elements):
129  """Type-checks and possibly canonicalizes `return_elements`."""
130  if return_elements is None:
131    return None
132  if not all(
133      isinstance(x, compat.bytes_or_text_types) for x in return_elements):
134    raise TypeError('return_elements must be a list of strings.')
135  return tuple(compat.as_str(x) for x in return_elements)
136
137
138def _FindAttrInOpDef(attr_name, op_def):
139  for attr_def in op_def.attr:
140    if attr_name == attr_def.name:
141      return attr_def
142  return None
143
144
145def _RemoveDefaultAttrs(producer_op_list, graph_def):
146  """Removes unknown default attrs according to `producer_op_list`.
147
148  Removes any unknown attrs in `graph_def` (i.e. attrs that do not appear in
149  registered OpDefs) that have a default value in `producer_op_list`.
150
151  Args:
152    producer_op_list: OpList proto.
153    graph_def: GraphDef proto
154  """
155  producer_op_dict = {op.name: op for op in producer_op_list.op}
156  for node in graph_def.node:
157    # Remove any default attr values that aren't in op_def.
158    if node.op in producer_op_dict:
159      op_def = op_def_registry.get(node.op)
160      if op_def is None:
161        # Some custom op registrations won't show up here. That's OK, attribute
162        # stripping just won't be available.
163        continue
164      producer_op_def = producer_op_dict[node.op]
165      # We make a copy of node.attr to iterate through since we may modify
166      # node.attr inside the loop.
167      for key in list(node.attr):
168        if _FindAttrInOpDef(key, op_def) is None:
169          # No attr_def in consumer, look in producer.
170          attr_def = _FindAttrInOpDef(key, producer_op_def)
171          if (attr_def and attr_def.HasField('default_value') and
172              node.attr[key] == attr_def.default_value):
173            # Unknown attr had default value in producer, delete it so it can be
174            # understood by consumer.
175            del node.attr[key]
176
177
178def _ConvertInputMapValues(name, input_map):
179  """Ensures all input map values are tensors.
180
181  This should be called from inside the import name scope.
182
183  Args:
184    name: the `name` argument passed to import_graph_def
185    input_map: the `input_map` argument passed to import_graph_def.
186
187  Returns:
188    An possibly-updated version of `input_map`.
189
190  Raises:
191    ValueError: if input map values cannot be converted due to empty name scope.
192  """
193  if not all(isinstance(v, ops.Tensor) for v in input_map.values()):
194    if name == '':  # pylint: disable=g-explicit-bool-comparison
195      raise ValueError(
196          'tf.import_graph_def() requires a non-empty `name` if `input_map` '
197          'contains non-Tensor values. Try calling tf.convert_to_tensor() on '
198          '`input_map` values before calling tf.import_graph_def().')
199    with ops.name_scope('_inputs'):
200      input_map = {k: ops.convert_to_tensor(v) for k, v in input_map.items()}
201  return input_map
202
203
204def _PopulateTFImportGraphDefOptions(options, prefix, input_map,
205                                     return_elements,
206                                     validate_colocation_constraints):
207  """Populates the TF_ImportGraphDefOptions `options`."""
208  c_api.TF_ImportGraphDefOptionsSetPrefix(options, prefix)
209  c_api.TF_ImportGraphDefOptionsSetUniquifyNames(options, True)
210
211  for input_src, input_dst in input_map.items():
212    input_src = compat.as_str(input_src)
213    if input_src.startswith('^'):
214      src_name = compat.as_str(input_src[1:])
215      dst_op = input_dst._as_tf_output().oper  # pylint: disable=protected-access
216      c_api.TF_ImportGraphDefOptionsRemapControlDependency(
217          options, src_name, dst_op)
218    else:
219      src_name, src_idx = _ParseTensorName(input_src)
220      src_name = compat.as_str(src_name)
221      dst_output = input_dst._as_tf_output()  # pylint: disable=protected-access
222      c_api.TF_ImportGraphDefOptionsAddInputMapping(options, src_name, src_idx,
223                                                    dst_output)
224  for name in return_elements or []:
225    if ':' in name:
226      op_name, index = _ParseTensorName(name)
227      op_name = compat.as_str(op_name)
228      c_api.TF_ImportGraphDefOptionsAddReturnOutput(options, op_name, index)
229    else:
230      c_api.TF_ImportGraphDefOptionsAddReturnOperation(options,
231                                                       compat.as_str(name))
232
233  c_api.TF_ImportGraphDefOptionsSetValidateColocationConstraints(
234      options, validate_colocation_constraints)
235
236
237def _ProcessNewOps(graph):
238  """Processes the newly-added TF_Operations in `graph`."""
239  # Maps from a node to the names of the ops it's colocated with, if colocation
240  # is specified in the attributes.
241  colocation_pairs = {}
242
243  for new_op in graph._add_new_tf_operations(compute_devices=False):  # pylint: disable=protected-access
244    original_device = new_op.device
245    new_op._set_device('')  # pylint: disable=protected-access
246    colocation_names = _GetColocationNames(new_op)
247    if colocation_names:
248      colocation_pairs[new_op] = colocation_names
249      # Don't set a device for this op, since colocation constraints override
250      # device functions and the original device. Note that this op's device may
251      # still be set by the loop below.
252      # TODO(skyewm): why does it override the original device?
253    else:
254      with _MaybeDevice(original_device):
255        graph._apply_device_functions(new_op)  # pylint: disable=protected-access
256
257  # The following loop populates the device field of ops that are colocated
258  # with another op.  This is implied by the colocation attribute, but we
259  # propagate the device field for completeness.
260  for op, coloc_op_list in colocation_pairs.items():
261    coloc_device = None
262    # Find any device in the list of colocated ops that have a device, if it
263    # exists.  We assume that if multiple ops have devices, they refer to the
264    # same device.  Otherwise, a runtime error will occur since the colocation
265    # property cannot be guaranteed.  Note in TF2 colocations have been removed
266    # from the public API and will be considered a hint, so there is no runtime
267    # error.
268    #
269    # One possible improvement is to try to check for compatibility of all
270    # devices in this list at import time here, which would require
271    # implementing a compatibility function for device specs in python.
272    for coloc_op_name in coloc_op_list:
273      try:
274        coloc_op = graph._get_operation_by_name_unsafe(coloc_op_name)  # pylint: disable=protected-access
275      except KeyError:
276        # Do not error in TF2 if the colocation cannot be guaranteed
277        if tf2.enabled() or control_flow_util.EnableControlFlowV2(graph):
278          continue
279
280        raise ValueError('Specified colocation to an op that '
281                         'does not exist during import: %s in %s' %
282                         (coloc_op_name, op.name))
283      if coloc_op.device:
284        coloc_device = pydev.DeviceSpec.from_string(coloc_op.device)
285        break
286    if coloc_device:
287      op._set_device(coloc_device)  # pylint: disable=protected-access
288
289
290def _GetColocationNames(op):
291  """Returns names of the ops that `op` should be colocated with."""
292  colocation_names = []
293  try:
294    class_values = op.get_attr('_class')
295  except ValueError:
296    # No _class attr
297    return
298  for val in class_values:
299    val = compat.as_str(val)
300    if val.startswith('loc:@'):
301      colocation_node_name = val[len('loc:@'):]
302      if colocation_node_name != op.name:
303        colocation_names.append(colocation_node_name)
304  return colocation_names
305
306
307def _GatherReturnElements(requested_return_elements, graph, results):
308  """Returns the requested return elements from results.
309
310  Args:
311    requested_return_elements: list of strings of operation and tensor names
312    graph: Graph
313    results: wrapped TF_ImportGraphDefResults
314
315  Returns:
316    list of `Operation` and/or `Tensor` objects
317  """
318  return_outputs = c_api.TF_ImportGraphDefResultsReturnOutputs(results)
319  return_opers = c_api.TF_ImportGraphDefResultsReturnOperations(results)
320
321  combined_return_elements = []
322  outputs_idx = 0
323  opers_idx = 0
324  for name in requested_return_elements:
325    if ':' in name:
326      combined_return_elements.append(
327          graph._get_tensor_by_tf_output(return_outputs[outputs_idx]))  # pylint: disable=protected-access
328      outputs_idx += 1
329    else:
330      combined_return_elements.append(
331          graph._get_operation_by_tf_operation(return_opers[opers_idx]))  # pylint: disable=protected-access
332      opers_idx += 1
333  return combined_return_elements
334
335
336def _SetDefaultAttrValues(node_def, op_def):
337  """Set any default attr values in `node_def` that aren't present."""
338  assert node_def.op == op_def.name
339  for attr_def in op_def.attr:
340    key = attr_def.name
341    if attr_def.HasField('default_value'):
342      value = node_def.attr[key]
343      if value is None or value.WhichOneof('value') is None:
344        node_def.attr[key].CopyFrom(attr_def.default_value)
345
346
347@tf_export('graph_util.import_graph_def', 'import_graph_def')
348@deprecated_args(None, 'Please file an issue at '
349                 'https://github.com/tensorflow/tensorflow/issues if you depend'
350                 ' on this feature.', 'op_dict')
351def import_graph_def(graph_def,
352                     input_map=None,
353                     return_elements=None,
354                     name=None,
355                     op_dict=None,
356                     producer_op_list=None):
357  """Imports the graph from `graph_def` into the current default `Graph`.
358
359  This function provides a way to import a serialized TensorFlow
360  [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
361  protocol buffer, and extract individual objects in the `GraphDef` as
362  `tf.Tensor` and `tf.Operation` objects. Once extracted,
363  these objects are placed into the current default `Graph`. See
364  `tf.Graph.as_graph_def` for a way to create a `GraphDef`
365  proto.
366
367  Args:
368    graph_def: A `GraphDef` proto containing operations to be imported into
369      the default graph.
370    input_map: A dictionary mapping input names (as strings) in `graph_def`
371      to `Tensor` objects. The values of the named input tensors in the
372      imported graph will be re-mapped to the respective `Tensor` values.
373    return_elements: A list of strings containing operation names in
374      `graph_def` that will be returned as `Operation` objects; and/or
375      tensor names in `graph_def` that will be returned as `Tensor` objects.
376    name: (Optional.) A prefix that will be prepended to the names in
377      `graph_def`. Note that this does not apply to imported function names.
378      Defaults to `"import"`.
379    op_dict: (Optional.) Deprecated, do not use.
380    producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped)
381      list of `OpDef`s used by the producer of the graph. If provided,
382      unrecognized attrs for ops in `graph_def` that have their default value
383      according to `producer_op_list` will be removed. This will allow some more
384      `GraphDef`s produced by later binaries to be accepted by earlier binaries.
385
386  Returns:
387    A list of `Operation` and/or `Tensor` objects from the imported graph,
388    corresponding to the names in `return_elements`,
389    and None if `returns_elements` is None.
390
391  Raises:
392    TypeError: If `graph_def` is not a `GraphDef` proto,
393      `input_map` is not a dictionary mapping strings to `Tensor` objects,
394      or `return_elements` is not a list of strings.
395    ValueError: If `input_map`, or `return_elements` contains names that
396      do not appear in `graph_def`, or `graph_def` is not well-formed (e.g.
397      it refers to an unknown tensor).
398  """
399  del op_dict
400  return _import_graph_def_internal(
401      graph_def,
402      input_map=input_map,
403      return_elements=return_elements,
404      name=name,
405      producer_op_list=producer_op_list)
406
407
408def import_graph_def_for_function(  # pylint: disable=invalid-name
409    graph_def, name=None):
410  """Like import_graph_def but does not validate colocation constraints."""
411  return _import_graph_def_internal(
412      graph_def, validate_colocation_constraints=False, name=name)
413
414
415def _import_graph_def_internal(  # pylint: disable=invalid-name
416    graph_def,
417    input_map=None,
418    return_elements=None,
419    validate_colocation_constraints=True,
420    name=None,
421    producer_op_list=None):
422  """Imports the graph from `graph_def` into the current default `Graph`.
423
424  This function provides a way to import a serialized TensorFlow
425  [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
426  protocol buffer, and extract individual objects in the `GraphDef` as
427  `tf.Tensor` and `tf.Operation` objects. Once extracted,
428  these objects are placed into the current default `Graph`. See
429  `tf.Graph.as_graph_def` for a way to create a `GraphDef`
430  proto.
431
432  Args:
433    graph_def: A `GraphDef` proto containing operations to be imported into the
434      default graph.
435    input_map: A dictionary mapping input names (as strings) in `graph_def` to
436      `Tensor` objects. The values of the named input tensors in the imported
437      graph will be re-mapped to the respective `Tensor` values.
438    return_elements: A list of strings containing operation names in `graph_def`
439      that will be returned as `Operation` objects; and/or tensor names in
440      `graph_def` that will be returned as `Tensor` objects.
441    validate_colocation_constraints: Whether to validate colocation constraints.
442    name: (Optional.) A prefix that will be prepended to the names in
443      `graph_def`. Note that this does not apply to imported function names.
444      Defaults to `"import"`.
445    producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped)
446      list of `OpDef`s used by the producer of the graph. If provided,
447      unrecognized attrs for ops in `graph_def` that have their default value
448      according to `producer_op_list` will be removed. This will allow some more
449      `GraphDef`s produced by later binaries to be accepted by earlier binaries.
450
451  Returns:
452    A list of `Operation` and/or `Tensor` objects from the imported graph,
453    corresponding to the names in `return_elements`,
454    and None if `returns_elements` is None.
455
456  Raises:
457    TypeError: If `graph_def` is not a `GraphDef` proto,
458      `input_map` is not a dictionary mapping strings to `Tensor` objects,
459      or `return_elements` is not a list of strings.
460    ValueError: If `input_map`, or `return_elements` contains names that
461      do not appear in `graph_def`, or `graph_def` is not well-formed (e.g.
462      it refers to an unknown tensor).
463  """
464  graph_def = _ProcessGraphDefParam(graph_def)
465  input_map = _ProcessInputMapParam(input_map)
466  return_elements = _ProcessReturnElementsParam(return_elements)
467
468  if producer_op_list is not None:
469    # TODO(skyewm): make a copy of graph_def so we're not mutating the argument?
470    _RemoveDefaultAttrs(producer_op_list, graph_def)
471
472  graph = ops.get_default_graph()
473  with ops.name_scope(name, 'import', input_map.values()) as scope:
474    # Save unique prefix generated by name_scope
475    if scope:
476      assert scope.endswith('/')
477      prefix = scope[:-1]
478    else:
479      prefix = ''
480
481    # Generate any input map tensors inside name scope
482    input_map = _ConvertInputMapValues(name, input_map)
483
484  scoped_options = c_api_util.ScopedTFImportGraphDefOptions()
485  options = scoped_options.options
486  _PopulateTFImportGraphDefOptions(options, prefix, input_map, return_elements,
487                                   validate_colocation_constraints)
488
489  # _ProcessNewOps mutates the new operations. _mutation_lock ensures a
490  # Session.run call cannot occur between creating the TF_Operations in the
491  # TF_GraphImportGraphDefWithResults call and mutating the them in
492  # _ProcessNewOps.
493  with graph._mutation_lock():  # pylint: disable=protected-access
494    with c_api_util.tf_buffer(graph_def.SerializeToString()) as serialized:
495      try:
496        results = c_api.TF_GraphImportGraphDefWithResults(
497            graph._c_graph, serialized, options)  # pylint: disable=protected-access
498        results = c_api_util.ScopedTFImportGraphDefResults(results)
499      except errors.InvalidArgumentError as e:
500        # Convert to ValueError for backwards compatibility.
501        raise ValueError(str(e))
502
503    # Create _DefinedFunctions for any imported functions.
504    #
505    # We do this by creating _DefinedFunctions directly from `graph_def`, and
506    # adding them to `graph`. Adding an existing function to a TF_Graph is a
507    # no-op, so this only has the effect of updating the Python state (usually
508    # _DefinedFunction.add_to_graph also adds the function to the TF_Graph).
509    #
510    # TODO(skyewm): fetch the TF_Functions directly from the TF_Graph
511    # TODO(skyewm): avoid sending serialized FunctionDefs back to the TF_Graph
512
513    _ProcessNewOps(graph)
514
515  if graph_def.library and graph_def.library.function:
516    functions = function.from_library(graph_def.library)
517    for f in functions:
518      f.add_to_graph(graph)
519
520  # Treat input mappings that don't appear in the graph as an error, because
521  # they are likely to be due to a typo.
522  missing_unused_input_keys = (
523      c_api.TF_ImportGraphDefResultsMissingUnusedInputMappings_wrapper(
524          results.results))
525  if missing_unused_input_keys:
526    missing_unused_input_keys = [
527        compat.as_str(s) for s in missing_unused_input_keys
528    ]
529    raise ValueError(
530        'Attempted to map inputs that were not found in graph_def: [%s]' %
531        ', '.join(missing_unused_input_keys))
532
533  if return_elements is None:
534    return None
535  else:
536    return _GatherReturnElements(return_elements, graph, results.results)
537