ir.cc 16.7 KB
Newer Older
F
flame 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/pybind/ir.h"
16

W
WangZhen 已提交
17
#include <algorithm>
18
#include <memory>
F
flame 已提交
19 20
#include <string>
#include <unordered_map>
W
WangZhen 已提交
21
#include <unordered_set>
22
#include <utility>
23

F
flame 已提交
24
#include "paddle/fluid/framework/ir/graph.h"
W
WangZhen 已提交
25
#include "paddle/fluid/framework/ir/graph_helper.h"
W
WangZhen 已提交
26
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
F
flame 已提交
27
#include "paddle/fluid/framework/ir/node.h"
28
#include "paddle/fluid/framework/ir/pass.h"
F
flame 已提交
29
#include "paddle/fluid/framework/op_desc.h"
30
#include "paddle/fluid/framework/python_headers.h"
31
#include "paddle/fluid/framework/scope.h"
F
flame 已提交
32 33 34 35 36 37
#include "paddle/fluid/framework/var_desc.h"
#include "pybind11/stl.h"

namespace py = pybind11;
using paddle::framework::OpDesc;
using paddle::framework::ProgramDesc;
38
using paddle::framework::Scope;
F
flame 已提交
39
using paddle::framework::VarDesc;
40 41 42 43 44 45 46 47
using paddle::framework::ir::BuildOperationAdjList;
using paddle::framework::ir::Graph;
using paddle::framework::ir::GraphNum;
using paddle::framework::ir::GraphSafeRemoveNodes;
using paddle::framework::ir::HasCircle;
using paddle::framework::ir::Node;
using paddle::framework::ir::NodeComp;
using paddle::framework::ir::TopologySortOperations;
F
flame 已提交
48 49 50 51 52
using pybind11::return_value_policy;

namespace paddle {
namespace pybind {
void BindGraph(py::module *m) {
53 54 55 56
  m->def("graph_safe_remove_nodes",
         [](Graph *graph, const std::unordered_set<const Node *> &nodes) {
           return GraphSafeRemoveNodes(graph, nodes);
         });
W
WangZhen 已提交
57 58
  m->def("has_circle", HasCircle);
  m->def("graph_num", GraphNum);
59 60 61 62
  m->def(
      "topology_sort", TopologySortOperations, return_value_policy::reference);
  m->def("build_adjacency_list",
         BuildOperationAdjList<NodeComp>,
W
WangZhen 已提交
63
         return_value_policy::reference);
F
flame 已提交
64
  py::class_<Graph, std::shared_ptr<Graph>>(
65 66
      *m,
      "Graph",
F
flame 已提交
67 68 69
      "The graph is a Directed Acyclic Single Static Assignment Graph, see "
      "`paddle::ir::Graph` for details.")
      .def(py::init<const ProgramDesc &>())
70
      .def(py::init<const ProgramDesc &, int64_t, int64_t>())
71
      .def("clone", &Graph::Clone)
F
flame 已提交
72
      .def("has", &Graph::Has)
73
      .def("get_bool", &Graph::Get<bool>)
F
flame 已提交
74 75 76 77
      .def("get_int", &Graph::Get<int>)
      .def("get_float", &Graph::Get<float>)
      .def("get_double", &Graph::Get<double>)
      .def("get_string", &Graph::Get<std::string>)
78 79
      .def("get_marked_nodes",
           &Graph::Get<std::unordered_set<const Node *>>,
80
           return_value_policy::reference)
F
flame 已提交
81
      .def("set",
82 83 84 85 86 87 88 89 90 91
           [](Graph &self, const std::string &attr_name, bool attr) {
             return self.Set(attr_name, new bool(attr));
           })
      .def("set",
           [](Graph &self, const std::string &attr_name, int attr) {
             return self.Set(attr_name, new int(attr));
           })
      .def("set",
           [](Graph &self,
              const std::string &attr_name,
F
flame 已提交
92 93 94 95 96 97 98 99 100 101 102
              const std::string &attr) {
             return self.Set(attr_name, new std::string(attr));
           })
      .def("set",
           [](Graph &self, const std::string &attr_name, float attr) {
             return self.Set(attr_name, new float(attr));
           })
      .def("set",
           [](Graph &self, const std::string &attr_name, double attr) {
             return self.Set(attr_name, new double(attr));
           })
W
WangZhen 已提交
103
      .def("set",
104 105
           [](Graph &self,
              const std::string &attr_name,
W
WangZhen 已提交
106 107 108 109
              const std::unordered_set<const Node *> &attr) {
             return self.Set(attr_name,
                             new std::unordered_set<const Node *>(attr));
           })
Z
Zeng Jinle 已提交
110
      .def("set",
111 112
           [](Graph &self,
              const std::string &attr_name,
Z
Zeng Jinle 已提交
113 114 115 116
              const std::unordered_set<std::string> &attr) {
             return self.Set(attr_name,
                             new std::unordered_set<std::string>(attr));
           })
117 118 119 120
      .def("set_not_owned",
           [](Graph &self, const std::string &attr_name, Scope &attr) {
             self.SetNotOwned<Scope>(attr_name, &attr);
           })
F
flame 已提交
121 122
      .def("erase", &Graph::Erase)
      .def("nodes", &Graph::Nodes, return_value_policy::reference)
123 124 125 126 127 128 129 130 131 132 133 134
      .def(
          "create_var_node",
          [](Graph &self, VarDesc &var_desc) {
            return self.CreateVarNode(&var_desc);
          },
          return_value_policy::reference)
      .def(
          "create_op_node",
          [](Graph &self, OpDesc &op_desc) {
            return self.CreateOpNode(&op_desc);
          },
          return_value_policy::reference)
135 136
      .def("create_control_dep_var",
           &Graph::CreateControlDepVar,
F
flame 已提交
137
           return_value_policy::reference)
138 139
      .def("create_empty_node",
           &Graph::CreateEmptyNode,
F
flame 已提交
140 141 142 143
           return_value_policy::reference)
      .def("release_nodes", &Graph::ReleaseNodes)
      .def("remove_node",
           [](Graph &self, Node &node) { return self.RemoveNode(&node); })
144 145
      .def(
          "retrieve_node", &Graph::RetrieveNode, return_value_policy::reference)
X
Xin Pan 已提交
146
      .def("resolve_hazard", &Graph::ResolveHazard)
147 148
      .def("origin_program_desc",
           &Graph::OriginProgram,
149 150 151 152 153 154 155 156 157
           return_value_policy::reference)
      .def("sub_graph_size", &Graph::SubGraphsSize)
      .def("get_sub_graph", [](Graph &self, int i) {
        /* Here we use a lambda function as an empty deleter to avoid the double
        free of smart pointer.
        Otherwise, this shared pointer will be free both in python and
        cpp scope, which will lead a core dumped. */
        return std::shared_ptr<Graph>(self.GetSubGraph(i), [](Graph *) {});
      });
F
flame 已提交
158 159 160 161 162 163
}

void BindNode(py::module *m) {
  py::class_<Node> node(*m, "Node");
  node.def("name", &Node::Name)
      .def("node_type", &Node::NodeType)
W
WangZhen 已提交
164 165
      .def("var", &Node::Var, return_value_policy::reference)
      .def("op", &Node::Op, return_value_policy::reference)
F
flame 已提交
166
      .def("id", &Node::id)
167
      .def("graph_id", &Node::GraphId)
168
      .def("original_desc_id", &Node::OriginalDescId)
F
flame 已提交
169 170 171
      .def("is_op", &Node::IsOp)
      .def("is_var", &Node::IsVar)
      .def("is_ctrl_var", &Node::IsCtrlVar)
W
WangZhen 已提交
172
      .def("clear_inputs", [](Node &self) { self.inputs.clear(); })
173
      .def("remove_input",
W
WangZhen 已提交
174
           [](Node &self, int node_id) {
W
WangZhen 已提交
175
             auto pos = std::find_if(
176 177
                 self.inputs.begin(),
                 self.inputs.end(),
W
WangZhen 已提交
178 179 180
                 [&node_id](const Node *n) { return n->id() == node_id; });
             if (pos != self.inputs.end()) {
               self.inputs.erase(pos);
W
WangZhen 已提交
181 182
             }
           })
183
      .def("remove_input",
W
WangZhen 已提交
184
           [](Node &self, Node &node) {
W
WangZhen 已提交
185 186 187 188
             auto pos =
                 std::find(self.inputs.begin(), self.inputs.end(), &node);
             if (pos != self.inputs.end()) {
               self.inputs.erase(pos);
W
WangZhen 已提交
189 190
             }
           })
191
      .def("append_input",
W
WangZhen 已提交
192
           [](Node &self, Node &node) { self.inputs.push_back(&node); })
W
WangZhen 已提交
193
      .def("clear_outputs", [](Node &self) { self.outputs.clear(); })
194
      .def("remove_output",
W
WangZhen 已提交
195
           [](Node &self, int node_id) {
W
WangZhen 已提交
196
             auto pos = std::find_if(
197 198
                 self.outputs.begin(),
                 self.outputs.end(),
W
WangZhen 已提交
199 200 201
                 [&node_id](const Node *n) { return n->id() == node_id; });
             if (pos != self.outputs.end()) {
               self.outputs.erase(pos);
W
WangZhen 已提交
202 203
             }
           })
204
      .def("remove_output",
W
WangZhen 已提交
205
           [](Node &self, Node &node) {
W
WangZhen 已提交
206 207 208 209
             auto pos =
                 std::find(self.outputs.begin(), self.outputs.end(), &node);
             if (pos != self.outputs.end()) {
               self.outputs.erase(pos);
W
WangZhen 已提交
210 211
             }
           })
212
      .def("append_output",
W
WangZhen 已提交
213
           [](Node &self, Node &node) { self.outputs.push_back(&node); })
214 215
      .def_readwrite("inputs", &Node::inputs)
      .def_readwrite("outputs", &Node::outputs);
F
flame 已提交
216 217 218 219 220

  py::enum_<Node::Type>(node, "Type")
      .value("Operation", Node::Type::kOperation)
      .value("Variable", Node::Type::kVariable)
      .export_values();
221 222 223 224 225 226 227

  py::enum_<Node::Dep>(node, "Dep")
      .value("Same", Node::Dep::kSame)
      .value("Before", Node::Dep::kBefore)
      .value("After", Node::Dep::kAfter)
      .value("NoDep", Node::Dep::kNoDep)
      .export_values();
F
flame 已提交
228
}
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

class PYBIND11_HIDDEN PassAttrGetterSetterRegistry {
 private:
  PassAttrGetterSetterRegistry() = default;
  DISABLE_COPY_AND_ASSIGN(PassAttrGetterSetterRegistry);

  using Getter = std::function<py::object(const framework::ir::Pass & /*pass*/,
                                          const std::string & /*attr_name*/)>;
  using Setter = std::function<void(const std::string & /*attr_name*/,
                                    const py::object & /*attr_value*/,
                                    framework::ir::Pass * /*pass*/)>;

  struct GetterSetter {
    Getter getter;
    Setter setter;
  };

 public:
  static PassAttrGetterSetterRegistry &Instance() {
    static PassAttrGetterSetterRegistry instance;
    return instance;
  }

  void Register(const std::string &attr_type, Getter getter, Setter setter) {
    PADDLE_ENFORCE_NOT_NULL(
254 255 256
        getter,
        platform::errors::InvalidArgument("getter of %s should not be nullptr",
                                          attr_type));
257
    PADDLE_ENFORCE_NOT_NULL(
258 259 260
        setter,
        platform::errors::InvalidArgument("setter of %s should not be nullptr",
                                          attr_type));
261 262 263 264
    GetterSetter getter_setter;
    getter_setter.getter = std::move(getter);
    getter_setter.setter = std::move(setter);
    PADDLE_ENFORCE_EQ(
265 266
        getter_setter_map_.emplace(attr_type, getter_setter).second,
        true,
267 268 269 270
        platform::errors::InvalidArgument(
            "getter and setter of %s have been set before", attr_type));
  }

271 272
  py::object Get(const framework::ir::Pass &pass,
                 const std::string &attr_name,
273 274 275
                 const std::string &attr_type) const {
    auto iter = getter_setter_map_.find(attr_type);
    PADDLE_ENFORCE_EQ(
276 277 278 279
        iter != getter_setter_map_.end(),
        true,
        platform::errors::InvalidArgument(
            "unsupported attribute type %s of %s", attr_type, attr_name));
280 281 282 283
    const auto &getter = iter->second.getter;
    return getter(pass, attr_name);
  }

284 285 286 287
  void Set(const std::string &attr_name,
           const std::string &attr_type,
           const py::object &attr_value,
           framework::ir::Pass *pass) const {
288 289
    auto iter = getter_setter_map_.find(attr_type);
    PADDLE_ENFORCE_EQ(
290 291 292 293
        iter != getter_setter_map_.end(),
        true,
        platform::errors::InvalidArgument(
            "unsupported attribute type %s of %s", attr_type, attr_name));
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    const auto &setter = iter->second.setter;
    setter(attr_name, attr_value, pass);
  }

 private:
  std::unordered_map<std::string, GetterSetter> getter_setter_map_;
};

#define REGISTER_PASS_ATTR_GETTER_SETTER(attr_type_name, cpp_type)             \
  do {                                                                         \
    auto getter = [](const framework::ir::Pass &pass,                          \
                     const std::string &attr_name) -> py::object {             \
      auto attr_value = pass.Get<cpp_type>(attr_name);                         \
      return py::cast(attr_value);                                             \
    };                                                                         \
    auto setter = [](const std::string &attr_name,                             \
                     const py::object &attr_value,                             \
                     framework::ir::Pass *pass) {                              \
      PADDLE_ENFORCE_NOT_NULL(                                                 \
          pass, platform::errors::InvalidArgument("pass should be provided")); \
      try {                                                                    \
        const auto &cpp_attr_value = py::cast<cpp_type>(attr_value);           \
        pass->Set(attr_name, new cpp_type(cpp_attr_value));                    \
      } catch (py::cast_error &) {                                             \
        PADDLE_THROW(platform::errors::InvalidArgument(                        \
319 320
            "type error of attribute %s, expected to be %s",                   \
            attr_name,                                                         \
321 322 323
            attr_type_name));                                                  \
      }                                                                        \
    };                                                                         \
324 325
    PassAttrGetterSetterRegistry::Instance().Register(                         \
        attr_type_name, getter, setter);                                       \
326 327 328 329 330 331 332 333 334 335 336 337 338 339
  } while (0)

// NOTE: attr_types may be changed
static void SetAttrsToPass(
    const std::unordered_map<std::string, py::object> &attrs,
    std::unordered_map<std::string, std::string> *attr_types,
    framework::ir::Pass *pass) {
  for (const auto &name_and_value : attrs) {
    const auto &attr_name = name_and_value.first;
    const auto &attr_value = name_and_value.second;
    auto &attr_type = (*attr_types)[attr_name];
    if (attr_type.empty()) {
      attr_type = py::cast<std::string>(attr_value.get_type().attr("__name__"));
    }
340 341
    PassAttrGetterSetterRegistry::Instance().Set(
        attr_name, attr_type, attr_value, pass);
342 343 344
  }
}

345 346 347 348 349 350 351 352 353 354 355 356 357
static std::vector<std::string> GetPassNames(const py::object &names) {
  try {
    return {py::cast<std::string>(names)};
  } catch (py::cast_error &) {
    try {
      return py::cast<std::vector<std::string>>(names);
    } catch (py::cast_error &) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Pass names must be either str or list[str]"));
    }
  }
}

358 359 360 361 362 363 364 365
void BindPass(py::module *m) {
  // NOTE: pass_attr_types is a dict to indicate the type of each attribute.
  // Python has only one integral type "int", but C++ has many integral types.
  // If pass_attrs = {"nranks": 1} in Python, we cannot know whether the type
  // of "nranks" is size_t or int in C++. Therefore, users can set
  // pass_attr_types to indicate the type of "nranks" explicitly,
  // i.e. pass_attr_types = {"nranks": "size_t"} means that the type of
  // "nranks" is size_t in C++.
366
  REGISTER_PASS_ATTR_GETTER_SETTER("bool", bool);
367 368 369 370 371 372 373 374
  REGISTER_PASS_ATTR_GETTER_SETTER("int", int64_t);
  REGISTER_PASS_ATTR_GETTER_SETTER("long", int64_t);
  REGISTER_PASS_ATTR_GETTER_SETTER("size_t", size_t);
  REGISTER_PASS_ATTR_GETTER_SETTER("float32", float);
  // Python float is C++ double
  REGISTER_PASS_ATTR_GETTER_SETTER("float", double);
  REGISTER_PASS_ATTR_GETTER_SETTER("bytes", std::string);
  REGISTER_PASS_ATTR_GETTER_SETTER("str", std::string);
375
  REGISTER_PASS_ATTR_GETTER_SETTER("list[str]", std::vector<std::string>);
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
  m->def("apply_pass",
         [](framework::ProgramDesc *main_program,
            framework::ProgramDesc *startup_program,
            const py::object &py_pass_names,
            const std::unordered_map<std::string, py::object> &pass_attrs,
            std::unordered_map<std::string, std::string> pass_attr_types) {
           auto pass_names = GetPassNames(py_pass_names);
           std::vector<std::unique_ptr<framework::ir::Pass>> passes;
           std::vector<const framework::ir::Pass *> passes_not_owned;
           passes.reserve(pass_names.size());
           passes_not_owned.reserve(pass_names.size());
           for (const auto &name : pass_names) {
             auto pass = framework::ir::PassRegistry::Instance().Get(name);
             SetAttrsToPass(pass_attrs, &pass_attr_types, pass.get());
             passes.push_back(std::move(pass));
             passes_not_owned.push_back(passes.back().get());
           }

           framework::ir::Pass::ApplyPassesToProgram(
               passes_not_owned, main_program, startup_program);
           std::unordered_map<std::string, py::object> result_attrs;
           for (const auto &pass : passes) {
             for (const auto &name_and_value : pass_attrs) {
               const auto &attr_name = name_and_value.first;
               const auto &attr_type = pass_attr_types.at(attr_name);
               result_attrs[attr_name] =
                   PassAttrGetterSetterRegistry::Instance().Get(
                       *pass, attr_name, attr_type);
             }
           }
           return result_attrs;
         });
409 410
}

F
flame 已提交
411 412
}  // namespace pybind
}  // namespace paddle