• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""Helpers to manipulate a tensor graph in python.
16"""
17
18import copy
19import re
20
21from tensorflow.core.framework import graph_pb2
22from tensorflow.core.framework import node_def_pb2
23from tensorflow.python.framework import _proto_comparators
24from tensorflow.python.framework import dtypes
25from tensorflow.python.framework import ops
26from tensorflow.python.util import deprecation
27from tensorflow.python.util import lazy_loader
28from tensorflow.python.util.tf_export import tf_export
29
30tf_export(v1=["GraphDef"])(graph_pb2.GraphDef)
31
32# A normal import here would generate circular dependencies.
33convert_to_constants = lazy_loader.LazyLoader(
34    "convert_to_constants", globals(),
35    "tensorflow.python.framework.convert_to_constants")
36
37_VARIABLE_OPS = {
38    "Assign",
39    "AssignAdd",
40    "AssignSub",
41    "Queue",
42    "ScatterAdd",
43    "ScatterSub",
44    "ScatterUpdate",
45    "TruncatedNormal",
46    "Variable",
47    "VariableV2",
48}
49
50_CONTROL_FLOW_OP_NAMES_OR_IDENTITY = [
51    "Switch",
52    "Enter",
53    "Exit",
54    "Identity",
55    "Merge",
56    "NextIteration",
57]
58
59_DEPRECATION_MSG = (
60    "This API was designed for TensorFlow v1. See "
61    "https://www.tensorflow.org/guide/migrate for instructions on how to "
62    "migrate your code to TensorFlow v2.")
63
64
65def _is_variable_op(op):
66  """Returns true if 'op' refers to a Variable node."""
67  return op in _VARIABLE_OPS
68
69# GraphDef protobuf docstring.
70graph_pb2.GraphDef.__doc__ = """\
71A protobuf containing the graph of operations.
72
73@compatibility(TF2)
74This API is not available in TensorFlow 2.x.
75
76You should not need to use `GraphDef`s directly in TF2. To load `GraphDef`s in
77TF2, use SavedModel. The SavedModel contains the `GraphDef`.
78
79Before:
80
81```python
82with tf.io.gfile.GFile('/tmp/graph.pb', 'rb') as f:
83  graph_def = tf.compat.v1.GraphDef()
84  graph_def.ParseFromString(f.read())
85```
86
87After:
88
89```python
90tf.saved_model.load('/tmp/saved_model')
91```
92
93If you would like to create a `GraphDef` in TF2, use `tf.function` and
94`get_concrete_function`.
95
96>>> @tf.function
97>>> def f(x):
98>>>   return x
99>>>
100>>> graph_def = f.get_concrete_function(1.).graph.as_graph_def()
101>>> print(graph_def)
102
103@end_compatibility
104
105"""
106
107
108@deprecation.deprecated(
109    date=None,
110    instructions=_DEPRECATION_MSG)
111@tf_export(v1=["graph_util.must_run_on_cpu"])
112def must_run_on_cpu(node, pin_variables_on_cpu=False):
113  """Returns True if the given node_def must run on CPU, otherwise False.
114
115  Args:
116    node: The node to be assigned to a device. Could be either an ops.Operation
117      or NodeDef.
118    pin_variables_on_cpu: If True, this function will return False if node_def
119      represents a variable-related op.
120
121  Returns:
122    True if the given node must run on CPU, otherwise False.
123  """
124
125  if isinstance(node, ops.Operation):
126    node_def = node.node_def
127  else:
128    assert isinstance(node, node_def_pb2.NodeDef)
129    node_def = node
130
131  # If the op is a variable-related op, should we pin it on CPU?
132  if pin_variables_on_cpu and _is_variable_op(node_def.op):
133    return True
134
135  # Constant operations producing a string or int32 must run on CPU.
136  if node_def.op == "Const":
137    # Get the value of the 'dtype' attr
138    dtype = node_def.attr["dtype"].type
139    if dtype == dtypes.string or dtype == dtypes.int32:
140      return True
141
142  if node_def.op in ["DynamicStitch", "ParallelDynamicStitch"]:
143    dtype = node_def.attr["T"].type
144    if dtype == dtypes.int32:
145      # DynamicStitch on GPU only works for int32 values.
146      return True
147
148  if node_def.op in ["Cast"]:
149    dtype = node_def.attr["SrcT"].type
150    if dtype == dtypes.int32:
151      # Cast on GPU does not works for int32 values.
152      return True
153  return False
154
155
156################################################################################
157#
158# device functions for use in with g.device(...)
159#
160################################################################################
161
162
163def _node_name(n):
164  if n.startswith("^"):
165    return n[1:]
166  else:
167    return n.split(":")[0]
168
169
170def _get_colocated_node_name(colocated_node_name):
171  """Decodes colocated node name and returns it without loc:@ prepended."""
172  colocated_node_decoded = colocated_node_name.decode("utf-8")
173  if colocated_node_decoded.startswith("loc:@"):
174    return colocated_node_decoded[5:]
175  return colocated_node_decoded
176
177
178def _extract_graph_summary(graph_def):
179  """Extracts useful information from the graph and returns them."""
180  name_to_input_name = {}  # Keyed by the dest node name.
181  name_to_node = {}  # Keyed by node name.
182
183  # Keeps track of node sequences. It is important to still output the
184  # operations in the original order.
185  name_to_seq_num = {}  # Keyed by node name.
186  seq = 0
187  for node in graph_def.node:
188    n = _node_name(node.name)
189    name_to_node[n] = node
190    name_to_input_name[n] = [_node_name(x) for x in node.input]
191    # Prevent colocated nodes from being lost.
192    if "_class" in node.attr:
193      for colocated_node_name in node.attr["_class"].list.s:
194        name_to_input_name[n].append(
195            _get_colocated_node_name(colocated_node_name))
196    name_to_seq_num[n] = seq
197    seq += 1
198  return name_to_input_name, name_to_node, name_to_seq_num
199
200
201def _assert_nodes_are_present(name_to_node, nodes):
202  """Assert that nodes are present in the graph."""
203  for d in nodes:
204    assert d in name_to_node, "%s is not in graph" % d
205
206
207def _bfs_for_reachable_nodes(target_nodes, name_to_input_name):
208  """Breadth first search for reachable nodes from target nodes."""
209  nodes_to_keep = set()
210  # Breadth first search to find all the nodes that we should keep.
211  next_to_visit = list(target_nodes)
212  while next_to_visit:
213    node = next_to_visit[0]
214    del next_to_visit[0]
215    if node in nodes_to_keep:
216      # Already visited this node.
217      continue
218    nodes_to_keep.add(node)
219    if node in name_to_input_name:
220      next_to_visit += name_to_input_name[node]
221  return nodes_to_keep
222
223
224@deprecation.deprecated(
225    date=None,
226    instructions=_DEPRECATION_MSG)
227@tf_export(v1=["graph_util.extract_sub_graph"])
228def extract_sub_graph(graph_def, dest_nodes):
229  """Extract the subgraph that can reach any of the nodes in 'dest_nodes'.
230
231  Args:
232    graph_def: A graph_pb2.GraphDef proto.
233    dest_nodes: An iterable of strings specifying the destination node names.
234  Returns:
235    The GraphDef of the sub-graph.
236
237  Raises:
238    TypeError: If 'graph_def' is not a graph_pb2.GraphDef proto.
239  """
240
241  if not isinstance(graph_def, graph_pb2.GraphDef):
242    raise TypeError("graph_def must be a graph_pb2.GraphDef proto, but got "
243                    f"type {type(graph_def)}.")
244
245  if isinstance(dest_nodes, str):
246    raise TypeError("dest_nodes must be an iterable of strings, but got "
247                    f"type {type(dest_nodes)}.")
248
249  name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(
250      graph_def)
251  _assert_nodes_are_present(name_to_node, dest_nodes)
252
253  nodes_to_keep = _bfs_for_reachable_nodes(dest_nodes, name_to_input_name)
254
255  nodes_to_keep_list = sorted(
256      list(nodes_to_keep), key=lambda n: name_to_seq_num[n])
257  # Now construct the output GraphDef
258  out = graph_pb2.GraphDef()
259  for n in nodes_to_keep_list:
260    out.node.extend([copy.deepcopy(name_to_node[n])])
261  out.library.CopyFrom(graph_def.library)
262  out.versions.CopyFrom(graph_def.versions)
263
264  return out
265
266
267@deprecation.deprecated(
268    date=None,
269    instructions=_DEPRECATION_MSG)
270@tf_export(v1=["graph_util.tensor_shape_from_node_def_name"])
271def tensor_shape_from_node_def_name(graph, input_name):
272  """Convenience function to get a shape from a NodeDef's input string."""
273  # To get a tensor, the name must be in the form <input>:<port>, for example
274  # 'Mul:0'. The GraphDef input strings don't always have the port specified
275  # though, so if there isn't a colon we need to add a default ':0' to the end.
276  if ":" not in input_name:
277    canonical_name = input_name + ":0"
278  else:
279    canonical_name = input_name
280  tensor = graph.get_tensor_by_name(canonical_name)
281  shape = tensor.get_shape()
282  return shape
283
284
285@deprecation.deprecated(
286    date=None,
287    instructions=_DEPRECATION_MSG)
288@tf_export(v1=["graph_util.convert_variables_to_constants"])
289def convert_variables_to_constants(sess,
290                                   input_graph_def,
291                                   output_node_names,
292                                   variable_names_whitelist=None,
293                                   variable_names_blacklist=None):
294  """Replaces all the variables in a graph with constants of the same values.
295
296  If you have a trained graph containing Variable ops, it can be convenient to
297  convert them all to Const ops holding the same values. This makes it possible
298  to describe the network fully with a single GraphDef file, and allows the
299  removal of a lot of ops related to loading and saving the variables.
300
301  Args:
302    sess: Active TensorFlow session containing the variables.
303    input_graph_def: GraphDef object holding the network.
304    output_node_names: List of name strings for the result nodes of the graph.
305    variable_names_whitelist: The set of variable names to convert (by default,
306                              all variables are converted).
307    variable_names_blacklist: The set of variable names to omit converting
308                              to constants.
309
310  Returns:
311    GraphDef containing a simplified version of the original.
312
313  Raises:
314    RuntimeError: if a DT_RESOURCE op is found whose ancestor Variables are both
315      denylisted AND whitelisted for freezing.
316  """
317  ret = convert_to_constants.convert_variables_to_constants_from_session_graph(
318      session=sess,
319      graph_def=input_graph_def,
320      output_node_names=output_node_names,
321      variable_names_allowlist=variable_names_whitelist,
322      variable_names_denylist=variable_names_blacklist)
323  # The previous code logic generated an empty versions field, we clear it here
324  # to maintain backwards compatibility.
325  ret.versions.Clear()
326  return ret
327
328
329@deprecation.deprecated(
330    date=None,
331    instructions=_DEPRECATION_MSG)
332@tf_export(v1=["graph_util.remove_training_nodes"])
333def remove_training_nodes(input_graph, protected_nodes=None):
334  """Prunes out nodes that aren't needed for inference.
335
336  There are nodes like Identity and CheckNumerics that are only useful
337  during training, and can be removed in graphs that will be used for
338  nothing but inference. Here we identify and remove them, returning an
339  equivalent graph. To be specific, CheckNumerics nodes are always removed, and
340  Identity nodes that aren't involved in control edges are spliced out so that
341  their input and outputs are directly connected.
342
343  Args:
344    input_graph: Model to analyze and prune.
345    protected_nodes: An optional list of names of nodes to be kept
346      unconditionally. This is for example useful to preserve Identity output
347      nodes.
348
349  Returns:
350    A list of nodes with the unnecessary ones removed.
351  """
352  if not protected_nodes:
353    protected_nodes = []
354
355  types_to_remove = {"CheckNumerics": True}
356
357  input_nodes = input_graph.node
358  names_to_remove = {}
359  for node in input_nodes:
360    if node.op in types_to_remove and node.name not in protected_nodes:
361      names_to_remove[node.name] = True
362
363  nodes_after_removal = []
364  for node in input_nodes:
365    if node.name in names_to_remove:
366      continue
367    new_node = node_def_pb2.NodeDef()
368    new_node.CopyFrom(node)
369    input_before_removal = node.input
370    del new_node.input[:]
371    for full_input_name in input_before_removal:
372      input_name = re.sub(r"^\^", "", full_input_name)
373      if input_name in names_to_remove:
374        continue
375      new_node.input.append(full_input_name)
376    nodes_after_removal.append(new_node)
377
378  types_to_splice = {"Identity": True}
379  control_input_names = set()
380  node_names_with_control_input = set()
381  for node in nodes_after_removal:
382    for node_input in node.input:
383      if "^" in node_input:
384        control_input_names.add(node_input.replace("^", ""))
385        node_names_with_control_input.add(node.name)
386
387  names_to_splice = {}
388  for node in nodes_after_removal:
389    if node.op in types_to_splice and node.name not in protected_nodes:
390      # We don't want to remove nodes that have control edge inputs, because
391      # they might be involved in subtle dependency issues that removing them
392      # will jeopardize.
393      if node.name not in node_names_with_control_input:
394        names_to_splice[node.name] = node.input[0]
395
396  # We also don't want to remove nodes which are used as control edge inputs.
397  names_to_splice = {name: value for name, value in names_to_splice.items()
398                     if name not in control_input_names}
399
400  nodes_after_splicing = []
401  for node in nodes_after_removal:
402    if node.name in names_to_splice:
403      continue
404    new_node = node_def_pb2.NodeDef()
405    new_node.CopyFrom(node)
406    input_before_removal = node.input
407    del new_node.input[:]
408    for full_input_name in input_before_removal:
409      input_name = re.sub(r"^\^", "", full_input_name)
410      while input_name in names_to_splice:
411        full_input_name = names_to_splice[input_name]
412        input_name = re.sub(r"^\^", "", full_input_name)
413      new_node.input.append(full_input_name)
414    nodes_after_splicing.append(new_node)
415
416  output_graph = graph_pb2.GraphDef()
417  output_graph.node.extend(nodes_after_splicing)
418  return output_graph
419
420
421@tf_export("__internal__.graph_util.graph_defs_equal", v1=[])
422def graph_defs_equal(graph_def_1: graph_pb2.GraphDef,
423                     graph_def_2: graph_pb2.GraphDef,
424                     treat_nan_as_equal: bool = False) -> bool:
425  """Returns True iff the graph def arguments are structurally equivalent.
426
427  The notion of equivalence encoded here checks that the set of NodeDefs in
428  the GraphDef's function library and main graph body are identical.
429  Additionally, it checks that the functions in the function library are equal
430  as sets.
431
432  Example usage:
433
434  ```
435  with tf.Graph().as_default() as g1:
436    tf.constant(1)
437
438  with tf.Graph().as_default() as g2:
439    tf.constant(2)
440
441  with tf.Graph().as_default() as g3:
442    tf.constant(1)
443
444  assert tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(),
445                                                     g3.as_graph_def())
446
447  assert not tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(),
448                                                         g2.as_graph_def())
449  ```
450
451  Args:
452    graph_def_1: Instance of `graph_pb2.GraphDef` to compare.
453    graph_def_2: Instance of `graph_pb2.GraphDef` to compare.
454    treat_nan_as_equal: Boolean indicating whether or not to treat nan
455      floating-point values as equal. This is crucial for any equivalence
456      relation defined over GraphDefs, to ensure symmetry.
457
458  Returns:
459    Boolean indicating structural equivalence as described above.
460
461  Raises:
462    TypeError: If either of the GraphDefs are not instances of
463      `graph_pb2.GraphDef`.
464  """
465  if not isinstance(graph_def_1, graph_pb2.GraphDef):
466    raise TypeError("graph_def_1 must be a graph_pb2.GraphDef proto, but got "
467                    f"type {type(graph_def_1)}.")
468  if not isinstance(graph_def_2, graph_pb2.GraphDef):
469    raise TypeError("graph_def_2 must be a graph_pb2.GraphDef proto, but got "
470                    f"type {type(graph_def_2)}.")
471  options = _proto_comparators.ProtoComparisonOptions(treat_nan_as_equal)
472  return _proto_comparators.EqualsGraphDef(graph_def_1.SerializeToString(),
473                                           graph_def_2.SerializeToString(),
474                                           options)
475