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 
16 #include <memory>
17 #include <stdexcept>
18 #include <string>
19 #include <unordered_map>
20 
21 #include "pybind11/pybind11.h"
22 #include "tensorflow/core/common_runtime/device.h"
23 #include "tensorflow/core/common_runtime/device_factory.h"
24 #include "tensorflow/core/framework/device_attributes.pb.h"
25 #include "tensorflow/core/framework/device_base.h"
26 #include "tensorflow/core/framework/graph.pb.h"
27 #include "tensorflow/core/framework/graph_def_util.h"
28 #include "tensorflow/core/grappler/clusters/cluster.h"
29 #include "tensorflow/core/grappler/clusters/utils.h"
30 #include "tensorflow/core/grappler/grappler_item.h"
31 #include "tensorflow/core/grappler/grappler_item_builder.h"
32 #include "tensorflow/core/grappler/optimizers/meta_optimizer.h"
33 #include "tensorflow/core/protobuf/config.pb.h"
34 #include "tensorflow/core/protobuf/device_properties.pb.h"
35 #include "tensorflow/core/protobuf/meta_graph.pb.h"
36 #include "tensorflow/core/public/session_options.h"
37 #include "tensorflow/python/lib/core/pybind11_status.h"
38 
39 namespace py = pybind11;
40 
DetectDevices(std::unordered_map<std::string,tensorflow::DeviceProperties> * device_map)41 void DetectDevices(
42     std::unordered_map<std::string, tensorflow::DeviceProperties>* device_map) {
43   tensorflow::SessionOptions options;
44   std::vector<std::unique_ptr<tensorflow::Device>> devices;
45   if (!tensorflow::DeviceFactory::AddDevices(options, "", &devices).ok()) {
46     return;
47   }
48 
49   for (const std::unique_ptr<tensorflow::Device>& device : devices) {
50     tensorflow::DeviceProperties& prop = (*device_map)[device->name()];
51     prop = tensorflow::grappler::GetDeviceInfo(device->parsed_name());
52 
53     // Overwrite the memory limit since users might have requested to use only a
54     // fraction of the available device memory.
55     const tensorflow::DeviceAttributes& attr = device->attributes();
56     prop.set_memory_size(attr.memory_limit());
57   }
58 }
59 
PYBIND11_MODULE(_pywrap_tf_optimizer,m)60 PYBIND11_MODULE(_pywrap_tf_optimizer, m) {
61   m.def(
62       "TF_OptimizeGraph",
63       [](tensorflow::grappler::Cluster* cluster,
64          const py::bytes& serialized_config_proto,
65          const py::bytes& serialized_metagraph, bool verbose,
66          const std::string& graph_id,
67          bool strip_default_attributes) -> py::bytes {
68         tensorflow::ConfigProto config_proto;
69         if (!config_proto.ParseFromString(
70                 std::string(serialized_config_proto))) {
71           throw std::invalid_argument(
72               "The ConfigProto could not be parsed as a valid protocol buffer");
73         }
74         tensorflow::MetaGraphDef metagraph;
75         if (!metagraph.ParseFromString(std::string(serialized_metagraph))) {
76           throw std::invalid_argument(
77               "The MetaGraphDef could not be parsed as a valid protocol "
78               "buffer");
79         }
80 
81         tensorflow::grappler::ItemConfig item_config;
82         // This disables graph optimizations in the older graph optimizer, which
83         // tend to overlap / be redundant with those in Grappler.
84         item_config.apply_optimizations = false;
85         item_config.ignore_user_placement = false;
86         std::unique_ptr<tensorflow::grappler::GrapplerItem> grappler_item =
87             tensorflow::grappler::GrapplerItemFromMetaGraphDef(
88                 graph_id, metagraph, item_config);
89         if (!grappler_item) {
90           throw std::invalid_argument(
91               "Failed to import metagraph, check error log for more info.");
92         }
93 
94         tensorflow::DeviceBase* cpu_device = nullptr;
95         tensorflow::GraphDef out_graph;
96         tensorflow::grappler::MetaOptimizer optimizer(cpu_device, config_proto);
97 
98         MaybeRaiseRegisteredFromStatus(
99             optimizer.Optimize(cluster, *grappler_item, &out_graph));
100         if (strip_default_attributes) {
101           tensorflow::StripDefaultAttributes(*tensorflow::OpRegistry::Global(),
102                                              out_graph.mutable_node());
103         }
104         if (verbose) {
105           optimizer.PrintResult();
106         }
107         return out_graph.SerializeAsString();
108       });
109 }
110