1# Copyright 2017 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"""Provides a proper python API for the symbols exported through swig."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21from tensorflow.core.framework import graph_pb2
22from tensorflow.core.protobuf import config_pb2
23from tensorflow.python import _pywrap_tf_optimizer as tf_opt
24from tensorflow.python.grappler import cluster as gcluster
25
26
27def OptimizeGraph(config_proto,
28                  metagraph,
29                  verbose=True,
30                  graph_id=b'graph_to_optimize',
31                  cluster=None,
32                  strip_default_attributes=False):
33  """Optimize the provided metagraph.
34
35  For best results, the signature_def field in `metagraph` should be populated
36  with information about input (feed) and output (fetch) tensors.
37
38  Args:
39    config_proto: a ConfigProto protobuf.
40    metagraph: a MetagraphDef protobuf.
41    verbose: whether to log optimization results.
42    graph_id: a string identifying this graph.
43    cluster: a grappler cluster object representing hardware resources
44        available to run this graph.
45    strip_default_attributes: whether graph node attributes having default
46        values should be removed after all the optimization passes. This
47        option is useful if the resulting graph will be executed by an older
48        process that might not know some of the recently added attributes.
49  """
50  if not isinstance(config_proto, config_pb2.ConfigProto):
51    raise TypeError('Expected config_proto to be a ConfigProto, saw type %s' %
52                    type(config_proto))
53  if cluster is None:
54    cluster = gcluster.Cluster()
55  out_graph = tf_opt.TF_OptimizeGraph(cluster.tf_cluster,
56                                      config_proto.SerializeToString(),
57                                      metagraph.SerializeToString(), verbose,
58                                      graph_id, strip_default_attributes)
59  return graph_pb2.GraphDef().FromString(out_graph)
60