imperative.cc 8.7 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
class Layer : public imperative::Layer {
 public:
  using imperative::Layer::Layer;  // Inherit constructors

38 39 40 41 42
  std::vector<std::shared_ptr<imperative::VarBase>> Forward(
      const std::vector<std::shared_ptr<imperative::VarBase>> &inputs)
      override {
    PYBIND11_OVERLOAD(std::vector<std::shared_ptr<imperative::VarBase>>, Layer,
                      Forward,
43 44 45 46 47 48 49 50 51 52 53
                      inputs);  // NOLINT
  }
};

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

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

54
// Bind Methods
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
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(); });

77 78
  py::class_<imperative::VarBase, std::shared_ptr<imperative::VarBase>>(
      m, "VarBase", R"DOC()DOC")
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
      .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<>())
142 143 144 145 146
      .def("forward",
           [](imperative::Layer &self,
              const std::vector<std::shared_ptr<imperative::VarBase>> &inputs) {
             return self.Forward(inputs);
           });
147 148

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

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

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

}  // namespace pybind
}  // namespace paddle