ir.cc 19.3 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

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

25 26
#include "paddle/fluid/pybind/pybind_variant_caster.h"

27
#include "paddle/fluid/framework/program_desc.h"
28 29 30 31 32
#include "paddle/fluid/ir/dialect/paddle_dialect/interface/op_yaml_info.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/api_builder.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_dialect.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_type.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/utils/utils.h"
Z
zhangbo9674 已提交
33
#include "paddle/fluid/ir/transforms/inplace_pass.h"
34
#include "paddle/fluid/ir_adaptor/translator/translate.h"
35
#include "paddle/fluid/ir_adaptor/translator/utils.h"
36
#include "paddle/ir/core/block.h"
37
#include "paddle/ir/core/builtin_attribute.h"
38
#include "paddle/ir/core/program.h"
39 40
#include "paddle/ir/core/type.h"
#include "paddle/ir/core/value.h"
41 42
#include "paddle/ir/pass/pass.h"
#include "paddle/ir/pass/pass_manager.h"
L
Leo Chen 已提交
43
#include "paddle/ir/pass/pass_registry.h"
44
#include "paddle/ir/transforms/dead_code_elimination_pass.h"
45
#include "paddle/phi/core/enforce.h"
F
flame 已提交
46 47 48
#include "pybind11/stl.h"

namespace py = pybind11;
49 50
using ir::Block;
using ir::Operation;
51 52
using ir::OpOperand;
using ir::OpResult;
53 54
using ir::Pass;
using ir::PassManager;
55
using ir::Program;
56 57
using ir::Type;
using ir::Value;
58
using paddle::dialect::APIBuilder;
59
using paddle::dialect::DenseTensorType;
F
flame 已提交
60 61
using pybind11::return_value_policy;

L
Leo Chen 已提交
62
USE_PASS(dead_code_elimination);
Z
zhangbo9674 已提交
63
USE_PASS(inplace);
L
Leo Chen 已提交
64

F
flame 已提交
65 66 67
namespace paddle {
namespace pybind {

68 69 70 71
PyTypeObject *g_ir_opresult_pytype = nullptr;

void BindOpsAPI(pybind11::module *module);

72
void BindProgram(py::module *m) {
73
  py::class_<Program, std::shared_ptr<Program>> program(*m, "Program", R"DOC(
Y
YuanRisheng 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    Create Python Program. Program is an abstraction of model structure, divided into
    computational graphs and weights. The Program has a main block that stores the computational
    graphs.

    A set of Program usually contains startup program and main program.
    A startup program is set to contain some initial work, eg. initialize the ``Parameter``, and the main
    program will contain the network structure and vars for train.

    A set of Program can be used for test or train, in train program ,
    Paddle will contain all content to build a train network,  in test
    program Paddle will prune some content which is irrelevant to test, eg.
    backward ops and vars.

    **Notes**:
        **we have** :ref:`api_paddle_static_default_startup_program` **and** :ref:`api_paddle_static_default_main_program`
        **by default, a pair of them will shared the parameters. The** :ref:`api_paddle_static_default_startup_program` **only run once to initialize parameters,**
        :ref:`api_paddle_static_default_main_program` **run in every mini batch and adjust the weights.**

    Returns:
        Program: An empty Program.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.static as static

            paddle.enable_static()

            main_program = static.Program()
            startup_program = static.Program()
            with static.program_guard(main_program=main_program, startup_program=startup_program):
                x = static.data(name="x", shape=[-1, 784], dtype='float32')
                y = static.data(name="y", shape=[-1, 1], dtype='int32')
                z = static.nn.fc(name="fc", x=x, size=10, activation="relu")

            print("main program is: {}".format(main_program))
            print("start up program is: {}".format(startup_program))
  )DOC");
113 114 115 116 117
  program
      .def(
          "__init__",
          [](Program &self) { new (&self) Program(ir::IrContext::Instance()); })
      .def("__str__",
118
           [](const std::shared_ptr<Program> &self) {
119
             std::ostringstream print_stream;
120
             self->Print(print_stream);
121 122
             return print_stream.str();
           })
123 124 125 126 127 128 129 130 131 132 133 134
      .def("parameters_num",
           [](const std::shared_ptr<Program> &self) {
             return self->parameters_num();
           })
      .def(
          "block",
          [](std::shared_ptr<Program> self) { return self->block(); },
          return_value_policy::reference)
      .def(
          "block",
          [](const std::shared_ptr<Program> &self) { return self->block(); },
          return_value_policy::reference);
F
flame 已提交
135
}
136

137
void BindBlock(py::module *m) {
Y
YuanRisheng 已提交
138 139 140 141 142 143 144
  py::class_<Block> block(*m, "Block", R"DOC(
    In IR, a Block has a list of Operation and can represent a sub computational graph.

    Notes:
        The constructor of Block should not be invoked directly. You can
        use `Program.block()` to get a block.
  )DOC");
145
  block.def("front", &Block::front, return_value_policy::reference)
146 147
      .def("get_parent_program",
           [](Block &self) { return self.GetParentOp()->GetParentProgram(); })
148 149 150 151 152 153 154 155 156
      .def_property_readonly(
          "ops",
          [](Block &self) -> py::list {
            py::list op_list;
            for (auto iter = self.begin(); iter != self.end(); iter++) {
              op_list.append(*iter);
            }
            return op_list;
          })
Y
YuanRisheng 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
      .def(
          "remove_op",
          [](Block &self, Operation *op) {
            auto op_iter = std::find(self.begin(), self.end(), op);
            self.erase(op_iter);
          },
          R"DOC(
        Remove the specific position operator.

        Args:
            index(int): the position that the operator to insert.

        Returns:
            None

      )DOC");
173 174
}

175
void BindOperation(py::module *m) {
Y
YuanRisheng 已提交
176 177 178 179 180 181 182 183 184 185
  py::class_<Operation> op(*m, "Operation", R"DOC(
    In IR, all the operation are represented by Operation, and Operation
    is regarded as a build in an instruction of a Block. Users can call
    python api to describe their neural network.

    Notes:
        The constructor of operator should not be invoked directly. Use
        python api, for example: paddle.mean for building mean operation.

  )DOC");
186
  op.def("name", &Operation::name)
187
      .def("get_parent_block",
188 189
           py::overload_cast<>(&Operation::GetParent),
           return_value_policy::reference)
190
      .def("get_parent_block",
191 192
           py::overload_cast<>(&Operation::GetParent, py::const_),
           return_value_policy::reference)
193
      .def("num_operands", &Operation::num_operands)
194
      .def("num_results", &Operation::num_results)
195
      .def("operand", &Operation::operand)
196
      .def("result", &Operation::result)
197
      .def("operand_source", &Operation::operand_source)
198 199
      .def("operands", &Operation::operands)
      .def("results", &Operation::results)
200 201 202 203 204 205 206 207 208
      .def("attrs",
           [](Operation &self) -> py::dict {
             py::dict attrs_dict;
             for (auto &pair : self.attributes()) {
               attrs_dict[pair.first.c_str()] =
                   paddle::dialect::GetAttributeData(pair.second);
             }
             return attrs_dict;
           })
209 210 211 212 213 214 215 216
      .def("operands_source",
           [](Operation &self) -> py::list {
             py::list op_list;
             for (uint32_t i = 0; i < self.num_operands(); i++) {
               op_list.append(self.operand_source(i));
             }
             return op_list;
           })
217 218 219 220 221 222
      .def("get_input_names",
           [](Operation &self) -> py::list {
             py::list op_list;
             paddle::dialect::OpYamlInfoInterface yaml_interface =
                 self.dyn_cast<paddle::dialect::OpYamlInfoInterface>();
             auto inputs_info = std::get<0>(yaml_interface.GetOpInfo());
223
             for (auto &input_info : inputs_info) {
224 225 226 227 228 229 230 231 232 233
               op_list.append(input_info.name);
             }
             return op_list;
           })
      .def("get_attr_names",
           [](Operation &self) -> py::list {
             py::list op_list;
             paddle::dialect::OpYamlInfoInterface yaml_interface =
                 self.dyn_cast<paddle::dialect::OpYamlInfoInterface>();
             auto attrs_info = std::get<1>(yaml_interface.GetOpInfo());
234
             for (auto &attr_info : attrs_info) {
235 236 237 238 239 240 241 242 243 244
               op_list.append(attr_info.name);
             }
             return op_list;
           })
      .def("get_output_names",
           [](Operation &self) -> py::list {
             py::list op_list;
             paddle::dialect::OpYamlInfoInterface yaml_interface =
                 self.dyn_cast<paddle::dialect::OpYamlInfoInterface>();
             auto outputs_info = std::get<2>(yaml_interface.GetOpInfo());
245
             for (auto &output_info : outputs_info) {
246 247 248 249 250 251 252 253 254 255 256
               op_list.append(output_info.name);
             }
             return op_list;
           })
      .def("replace_all_uses_with",
           [](Operation &self, const std::vector<OpResult> &op_results) {
             self.ReplaceAllUsesWith(op_results);
           });
}

void BindValue(py::module *m) {
Y
YuanRisheng 已提交
257 258 259 260 261 262 263 264 265
  py::class_<Value> value(*m, "Value", R"DOC(
    Value class represents the SSA value in the IR system. It is a directed edge
    and a base class.

    Notes:
        The constructor of Value should not be invoked directly. Value can be automatically constructed
        when build network.

  )DOC");
266 267 268 269
  value
      .def("get_defining_op",
           &Value::GetDefiningOp,
           return_value_policy::reference)
270
      .def("first_use", &Value::first_use, return_value_policy::reference)
271 272
      .def("has_one_use", &Value::HasOneUse)
      .def("use_empty", &Value::use_empty)
X
xiaoguoguo626807 已提交
273 274 275 276 277 278 279
      .def("__eq__", &Value::operator==)
      .def("__eq__",
           [](Value &self, OpResult &other) {
             return self.impl() == other.value_impl();
           })
      .def("__hash__",
           [](const Value &self) { return std::hash<ir::Value>{}(self); });
280 281 282
}

void BindOpOperand(py::module *m) {
Y
YuanRisheng 已提交
283 284 285 286 287 288 289 290 291 292
  py::class_<OpOperand> op_operand(*m,
                                   "OpOperand",
                                   R"DOC(
    OpOperand class represents the op_operand (input) of operation.

    Notes:
        The constructor of OpOperand should not be invoked directly. OpOperand can be automatically constructed
        when build network.

  )DOC");
293 294 295
  op_operand
      .def("source",
           [](OpOperand &self) { return self.source().dyn_cast<OpResult>(); })
296 297 298 299 300
      .def("set_source",
           [](OpOperand &self, const OpResult &result) {
             self.set_source(result);
           })
      .def("owner", &OpOperand::owner, return_value_policy::reference);
301 302
}

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
bool GetStopGradient(const OpResult &self) {
  auto *defining_op = self.owner();
  if (defining_op->HasAttribute(kAttrStopGradients)) {
    auto stop_gradients = defining_op->attribute(kAttrStopGradients)
                              .dyn_cast<ir::ArrayAttribute>()
                              .AsVector();
    return stop_gradients[self.GetResultIndex()]
        .dyn_cast<ir::BoolAttribute>()
        .data();
  } else {
    return false;
  }
}

void SetStopGradient(const OpResult &self, bool stop_gradient) {
  auto *defining_op = self.owner();
  std::vector<ir::Attribute> stop_gradients;
  if (defining_op->HasAttribute(kAttrStopGradients)) {
    stop_gradients = defining_op->attribute(kAttrStopGradients)
                         .dyn_cast<ir::ArrayAttribute>()
                         .AsVector();
  } else {
    stop_gradients = std::vector<ir::Attribute>(
        defining_op->num_results(),
        ir::BoolAttribute::get(ir::IrContext::Instance(), false));
  }
  stop_gradients[self.GetResultIndex()] =
      ir::BoolAttribute::get(ir::IrContext::Instance(), stop_gradient);
  defining_op->set_attribute(
      kAttrStopGradients,
      ir::ArrayAttribute::get(ir::IrContext::Instance(), stop_gradients));
}

336
void BindOpResult(py::module *m) {
Y
YuanRisheng 已提交
337 338 339 340 341 342 343
  py::class_<OpResult> op_result(*m, "OpResult", R"DOC(
    OpResult class represents the value(output) defined by a result of operation.

    Notes:
        The constructor of OpResult should not be invoked directly. OpResult can be automatically constructed
        when build network.
  )DOC");
344
  g_ir_opresult_pytype = reinterpret_cast<PyTypeObject *>(op_result.ptr());
345 346 347 348 349 350 351 352 353
  op_result.def("__eq__", &OpResult::operator==)
      .def("__eq__",
           [](OpResult &self, Value &other) {
             return self.value_impl() == other.impl();
           })
      .def("__hash__",
           [](OpResult &self) {
             return std::hash<ir::Value>{}(self.dyn_cast<ir::Value>());
           })
354 355 356
      .def("get_defining_op",
           &OpResult::GetDefiningOp,
           return_value_policy::reference)
357
      .def("first_use", &OpResult::first_use, return_value_policy::reference)
358
      .def("has_one_use", &Value::HasOneUse)
359 360
      .def("use_empty", &OpResult::use_empty)
      .def("type", &OpResult::type)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
      .def_property(
          "stop_gradient",
          [](OpResult &self) { return GetStopGradient(self); },
          [](OpResult &self, bool stop_gradient) {
            SetStopGradient(self, stop_gradient);
          })
      .def_property(
          "shape",
          [](OpResult &self) {
            if (self.type().isa<DenseTensorType>()) {
              return phi::vectorize(
                  self.type().dyn_cast<DenseTensorType>().dims());
            } else {
              PADDLE_THROW(phi::errors::InvalidArgument(
                  "Currently, we can only get shape for dense tensor."));
            }
          },
          [](OpResult &self, const std::vector<int> &shape) {
            PADDLE_THROW(phi::errors::InvalidArgument(
                "can't set shape when building static graph"));
          })
      .def_property(
          "dtype",
          [](OpResult &self) {
            if (self.type().isa<DenseTensorType>()) {
              return paddle::dialect::TransToPhiDataType(
                  self.type().dyn_cast<DenseTensorType>().dtype());
            } else {
              PADDLE_THROW(phi::errors::InvalidArgument(
                  "Currently, we can only get dtype for dense tensor."));
            }
          },
          [](OpResult &self, phi::DataType dtype) {
            PADDLE_THROW(phi::errors::InvalidArgument(
                "can't set dtype when building static graph"));
          });
397 398 399 400 401
}

void BindType(py::module *m) {
  py::class_<Type> ir_type(*m, "Type");
  ir_type.def("__eq__", [](Type &self, Type &other) { return self == other; })
402 403 404 405 406
      .def("__str__", [](Type &self) {
        std::ostringstream print_stream;
        print_stream << self;
        return print_stream.str();
      });
407 408 409
}

void BindUtils(pybind11::module *m) {
410 411 412 413 414 415 416 417
  m->def("set_global_program",
         [](Program *program) { APIBuilder::Instance().SetProgram(program); });
  m->def("set_insertion_point",
         [](Operation *op) { APIBuilder::Instance().SetInsertionPoint(op); });
  m->def("reset_insertion_point_to_start",
         []() { APIBuilder::Instance().ResetInsertionPointToStart(); });
  m->def("reset_insertion_point_to_end",
         []() { APIBuilder::Instance().ResetInsertionPointToEnd(); });
418 419 420 421
  m->def("register_paddle_dialect", []() {
    ir::IrContext::Instance()
        ->GetOrRegisterDialect<paddle::dialect::PaddleDialect>();
  });
422 423 424 425 426 427 428 429
  m->def(
      "translate_to_new_ir",
      [](const ::paddle::framework::ProgramDesc &legacy_program) {
        std::shared_ptr<Program> ret =
            std::move(paddle::TranslateLegacyProgramToProgram(legacy_program));
        return ret;
      },
      R"DOC(
Y
YuanRisheng 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        Convert Fluid Program to New IR Program.

        Args:

            legacy_program (ProgramDesc): The Fluid Program that will be converted.

        Returns:
            Program: The New IR Program

        Raises:
            PreconditionNotMet: If legacy_program has multi block will raise error.

        Examples:
            .. code-block:: python

                import paddle
                from paddle import ir
                paddle.enable_static()

                x = paddle.randn([4, 4])
                main_program, start_program = (
                    paddle.static.Program(),
                    paddle.static.Program(),
                )
                with paddle.static.program_guard(main_program, start_program):
                    x_s = paddle.static.data('x', [4, 4], x.dtype)
                    x_s.stop_gradient = False
                    y_s = paddle.matmul(x_s, x_s)
                    z_s = paddle.add(y_s, y_s)
                    k_s = paddle.tanh(z_s)
                newir_program = ir.translate_to_new_ir(main_program.desc)

                print(newir_program)

      )DOC");
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  m->def(
      "check_unregistered_ops",
      [](const framework::ProgramDesc &legacy_program) {
        ir::IrContext *ctx = ir::IrContext::Instance();
        return paddle::translator::CheckUnregisteredOperation(ctx,
                                                              legacy_program);
      },
      R"DOC(
      Check unregistered operators in paddle dialect.

      Args:
        legacy_program (ProgramDesc): The Fluid Program that need checked.
      Returns:
        list[str] : List of unregistered operators in paddle dialect, the name is expressed by origin op name.
    )DOC");
480 481
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
void BindIrPass(pybind11::module *m) {
  py::class_<Pass, std::shared_ptr<Pass>> pass(*m,
                                               "Pass",
                                               R"DOC(
    Pass class.

  )DOC");
  pass.def("name", &Pass::name)
      .def("opt_level",
           [](const Pass &self) { return self.pass_info().opt_level; })
      .def("dependents",
           [](const Pass &self) { return self.pass_info().dependents; });
}

void BindPassManager(pybind11::module *m) {
  py::class_<PassManager, std::shared_ptr<PassManager>> pass_manager(
      *m,
      "PassManager",
      R"DOC(
    A class that manages all passes.

  )DOC");
  pass_manager
      .def(
          "__init__",
          [](PassManager &self, uint8_t opt_level) {
            new (&self) PassManager(ir::IrContext::Instance(), opt_level);
          },
          py::arg("opt_level") = 2)
      .def("add_pass",
512
           [](PassManager &self, const std::string &pass_name) {
L
Leo Chen 已提交
513 514
             self.AddPass(
                 std::move(ir::PassRegistry::Instance().Get(pass_name)));
515 516 517 518 519 520 521 522 523 524 525 526 527
           })
      .def("passes",
           [](PassManager &self) {
             std::vector<std::string> pass_names;
             for (const auto &pass : self.passes()) {
               pass_names.emplace_back(pass->name());
             }
             return pass_names;
           })
      .def("run", [](PassManager &self, Program *p) { self.Run(p); })
      .def("empty", &PassManager::Empty);
}

528 529 530 531 532 533 534 535 536 537
void BindNewIR(pybind11::module *module) {
  auto ir_module = module->def_submodule("ir");
  BindProgram(&ir_module);
  BindBlock(&ir_module);
  BindOperation(&ir_module);
  BindValue(&ir_module);
  BindOpOperand(&ir_module);
  BindOpResult(&ir_module);
  BindType(&ir_module);
  BindUtils(&ir_module);
538 539
  BindIrPass(&ir_module);
  BindPassManager(&ir_module);
540 541
  auto ops_modules = ir_module.def_submodule("ops");
  BindOpsAPI(&ops_modules);
542 543
}

F
flame 已提交
544 545
}  // namespace pybind
}  // namespace paddle