imperative.cc 8.6 KB
Newer Older
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/imperative.h"
16 17 18 19 20

#include <pybind11/chrono.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
21
#include <memory>
22

23
#include "paddle/fluid/framework/block_desc.h"
24 25
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/imperative/profiler.h"
26
#include "paddle/fluid/imperative/tracer.h"
M
minqiyang 已提交
27
#include "paddle/fluid/imperative/type_defs.h"
28

29 30
#include "paddle/fluid/pybind/pybind_boost_headers.h"

31 32 33
namespace paddle {
namespace pybind {

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
class Layer : public imperative::Layer {
 public:
  using imperative::Layer::Layer;  // Inherit constructors

  std::vector<imperative::VarBase *> Forward(
      const std::vector<imperative::VarBase *> &inputs) override {
    PYBIND11_OVERLOAD(std::vector<imperative::VarBase *>, Layer, Forward,
                      inputs);  // NOLINT
  }
};

class PYBIND11_HIDDEN PyOpBase : public imperative::OpBase {
 public:
  using imperative::OpBase::OpBase;  // Inherit constructors

  PyOpBase(const std::string &name) : OpBase(name) {}
};

52
// Bind Methods
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
void BindImperative(pybind11::module *m_ptr) {
  namespace py = ::pybind11;

  auto &m = *m_ptr;

  py::class_<imperative::detail::BackwardStrategy> backward_strategy(
      m, "BackwardStrategy", R"DOC()DOC");
  backward_strategy.def(py::init())
      .def_property("sort_sum_gradient",
                    [](const imperative::detail::BackwardStrategy &self) {
                      return self.sorted_sum_gradient_;
                    },
                    [](imperative::detail::BackwardStrategy &self,
                       bool sorted_sum_gradient) {
                      self.sorted_sum_gradient_ = sorted_sum_gradient;
                    });

  m.def("start_imperative_gperf_profiler",
        []() { imperative::StartProfile(); });

  m.def("stop_imperative_gperf_profiler", []() { imperative::StopProfile(); });

  py::class_<imperative::VarBase>(m, "VarBase", R"DOC()DOC")
      .def(
          py::init<const std::string &, paddle::framework::proto::VarType::Type,
                   const std::vector<int64_t>, const paddle::platform::CPUPlace,
                   bool, bool>())
      .def(
          py::init<const std::string &, paddle::framework::proto::VarType::Type,
                   const std::vector<int64_t>,
                   const paddle::platform::CUDAPlace, bool, bool>())
      .def("_run_backward",
           [](imperative::VarBase &self,
              const imperative::detail::BackwardStrategy &bckst) {
             self.RunBackward(bckst);
           })
      .def("_grad_name", &imperative::VarBase::GradName)
      .def("_grad_value", &imperative::VarBase::GradValue)
      .def("_clear_gradient", &imperative::VarBase::ClearGradient)
      .def("_grad_ivar",
           [](const imperative::VarBase &self) { return self.grads_; },
           py::return_value_policy::reference)
      .def("_copy_to",
           [](const imperative::VarBase &self, const platform::CPUPlace &place,
              bool blocking) {
             return self.NewVarBase(place, blocking).release();
           },
           py::return_value_policy::take_ownership)
      .def("_copy_to",
           [](const imperative::VarBase &self, const platform::CUDAPlace &place,
              bool blocking) {
             return self.NewVarBase(place, blocking).release();
           },
           py::return_value_policy::take_ownership)
      .def("value",
           [](const imperative::VarBase &self) { return self.var_.get(); },
           py::return_value_policy::reference)
      .def_property("name", &imperative::VarBase::Name,
                    &imperative::VarBase::SetName)
      .def_property_readonly("shape", &imperative::VarBase::Shape)
      .def_property_readonly("dtype", &imperative::VarBase::DataType)
      .def_property("persistable", &imperative::VarBase::IsPersistable,
                    &imperative::VarBase::SetPersistable)
      .def_property("stop_gradient", &imperative::VarBase::IsStopGradient,
                    &imperative::VarBase::SetStopGradient);

  py::class_<imperative::OpBase, PyOpBase>(m, "OpBase", R"DOC()DOC")
      .def(py::init<const std::string &>())
      .def("register_backward_hooks",
           [](imperative::OpBase &self, const py::object &callable) {
             self.RegisterBackwardHooks(callable);
           })
      .def_property("_trace_id",
                    [](const imperative::OpBase &self) {
                      py::gil_scoped_release release;
                      return self.trace_id_;
                    },
                    [](imperative::OpBase &self, int trace_id) {
                      py::gil_scoped_release release;
                      self.trace_id_ = trace_id;
                    },
                    py::return_value_policy::reference)
      .def_property_readonly("type", &imperative::OpBase::Type);

  py::class_<imperative::Layer, Layer /* <--- trampoline*/> layer(m, "Layer");
  layer.def(py::init<>())
      .def("forward", [](imperative::Layer &self,
                         const std::vector<imperative::VarBase *> &inputs) {
        return self.Forward(inputs);
      });

  py::class_<imperative::Tracer>(*m, "Tracer", "")
145
      .def("__init__",
146
           [](imperative::Tracer &self, framework::BlockDesc *root_block) {
M
minqiyang 已提交
147
             new (&self) imperative::Tracer(root_block);
148
           })
M
minqiyang 已提交
149
      .def("trace",
150 151 152
           [](imperative::Tracer &self, imperative::OpBase *op,
              const imperative::VarBasePtrMap &inputs,
              imperative::VarBasePtrMap *outputs,
153
              framework::AttributeMap attrs_map,
M
minqiyang 已提交
154 155
              const platform::CPUPlace expected_place,
              const bool stop_gradient = false) {
156
             py::gil_scoped_release release;
157
             return self.Trace(op, inputs, outputs, attrs_map, expected_place,
M
minqiyang 已提交
158
                               stop_gradient);
M
minqiyang 已提交
159
           })
160 161 162 163 164 165 166 167 168 169
      .def("trace", [](imperative::Tracer &self, imperative::OpBase *op,
                       const imperative::VarBasePtrMap &inputs,
                       imperative::VarBasePtrMap *outputs,
                       framework::AttributeMap attrs_map,
                       const platform::CUDAPlace expected_place,
                       const bool stop_gradient = false) {
        py::gil_scoped_release release;
        return self.Trace(op, inputs, outputs, attrs_map, expected_place,
                          stop_gradient);
      });
170 171

  // define parallel context
172 173 174
  py::class_<imperative::ParallelStrategy> parallel_strategy(
      m, "ParallelStrategy", "");
  parallel_strategy.def(py::init())
175 176
      .def_property(
          "nranks",
177 178
          [](const imperative::ParallelStrategy &self) { return self.nranks_; },
          [](imperative::ParallelStrategy &self, int nranks) {
179 180 181
            self.nranks_ = nranks;
          })
      .def_property("local_rank",
182
                    [](const imperative::ParallelStrategy &self) {
183 184
                      return self.local_rank_;
                    },
185
                    [](imperative::ParallelStrategy &self, int local_rank) {
186 187 188 189
                      self.local_rank_ = local_rank;
                    })
      .def_property(
          "trainer_endpoints",
190
          [](const imperative::ParallelStrategy &self) {
191 192
            return self.trainer_endpoints_;
          },
193
          [](imperative::ParallelStrategy &self, std::vector<std::string> eps) {
194 195 196
            self.trainer_endpoints_ = eps;
          })
      .def_property("current_endpoint",
197
                    [](const imperative::ParallelStrategy &self) {
198 199
                      return self.current_endpoint_;
                    },
200 201
                    [](imperative::ParallelStrategy &self,
                       const std::string &ep) { self.current_endpoint_ = ep; });
202
#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
203 204
  py::class_<imperative::NCCLParallelContext> nccl_ctx(m,
                                                       "NCCLParallelContext");
205 206

  nccl_ctx
207 208 209
      .def(py::init<const imperative::ParallelStrategy &,
                    const platform::CUDAPlace &>())
      .def("init", [](imperative::NCCLParallelContext &self) { self.Init(); });
210
#endif
211 212 213 214
}

}  // namespace pybind
}  // namespace paddle