protobuf.cc 10.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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/pybind/protobuf.h"
Y
Yu Yang 已提交
16
#include <deque>
Y
Yu Yang 已提交
17
#include <iostream>
18
#include "paddle/framework/backward.h"
F
fengjiayi 已提交
19 20 21 22
#include "paddle/framework/block_desc.h"
#include "paddle/framework/op_desc.h"
#include "paddle/framework/program_desc.h"
#include "paddle/framework/var_desc.h"
23

Y
Yu Yang 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// Cast boost::variant for PyBind.
// Copy from
// https://github.com/pybind/pybind11/issues/576#issuecomment-269563199
namespace pybind11 {
namespace detail {

// Can be replaced by a generic lambda in C++14
struct variant_caster_visitor : public boost::static_visitor<handle> {
  return_value_policy policy;
  handle parent;

  variant_caster_visitor(return_value_policy policy, handle parent)
      : policy(policy), parent(parent) {}

  template <class T>
  handle operator()(T const &src) const {
    return make_caster<T>::cast(src, policy, parent);
  }
};

template <class Variant>
struct variant_caster;

template <template <class...> class V, class... Ts>
struct variant_caster<V<Ts...>> {
  using Type = V<Ts...>;

Y
Yu Yang 已提交
51 52
  template <typename T>
  typename std::enable_if<
Y
Yu Yang 已提交
53
      !std::is_same<T, boost::detail::variant::void_>::value, bool>::type
Y
Yu Yang 已提交
54
  try_load(handle src, bool convert) {
Y
Yu Yang 已提交
55 56 57 58 59 60 61 62 63
    auto caster = make_caster<T>();
    if (!load_success_ && caster.load(src, convert)) {
      load_success_ = true;
      value = cast_op<T>(caster);
      return true;
    }
    return false;
  }

Y
Yu Yang 已提交
64 65 66 67 68 69 70
  template <typename T>
  typename std::enable_if<std::is_same<T, boost::detail::variant::void_>::value,
                          bool>::type
  try_load(handle src, bool convert) {
    return false;
  }

Y
Yu Yang 已提交
71 72 73 74 75 76
  bool load(handle src, bool convert) {
    auto unused = {false, try_load<Ts>(src, convert)...};
    (void)(unused);
    return load_success_;
  }

Y
Yu Yang 已提交
77
  static handle cast(Type const &src, return_value_policy policy,
Y
Yu Yang 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
                     handle parent) {
    variant_caster_visitor visitor(policy, parent);
    return boost::apply_visitor(visitor, src);
  }

  PYBIND11_TYPE_CASTER(Type, _("Variant"));
  bool load_success_{false};
};

// Add specialization for concrete variant type
template <class... Args>
struct type_caster<boost::variant<Args...>>
    : variant_caster<boost::variant<Args...>> {};

}  // namespace detail
}  // namespace pybind11

95
namespace paddle {
96
namespace pybind {
97

F
fengjiayi 已提交
98 99
using namespace paddle::framework;  // NOLINT

Y
Yu Yang 已提交
100 101 102 103 104 105 106 107 108
template <typename T>
static py::bytes SerializeMessage(T &self) {
  // Check IsInitialized in Python
  std::string retv;
  PADDLE_ENFORCE(self.Proto()->SerializePartialToString(&retv),
                 "Cannot serialize message");
  return retv;
}

Y
Yu Yang 已提交
109
// Bind Methods
F
fengjiayi 已提交
110
void BindProgramDesc(py::module &m) {
F
fengjiayi 已提交
111
  py::class_<ProgramDescBind>(m, "ProgramDesc", "")
112
      .def(py::init<>())
Y
Yu Yang 已提交
113 114 115 116
      .def("__init__",
           [](ProgramDescBind &self, const ProgramDescBind &other) {
             new (&self) ProgramDescBind(other);
           })
117 118 119 120 121
      .def("__init__",
           [](ProgramDescBind &self, const py::bytes &binary_str) {
             std::string str(binary_str);
             new (&self) ProgramDescBind(str);
           })
F
fengjiayi 已提交
122
      .def("append_block", &ProgramDescBind::AppendBlock,
123
           py::return_value_policy::reference)
124
      .def("append_backward",
125
           [](ProgramDescBind &program_desc, const VarDescBind &target,
126
              const std::unordered_set<std::string> &no_grad_vars) {
Q
qiaolongfei 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139
             ParamGradInfoMap param_grad_map =
                 AppendBackward(program_desc, target, no_grad_vars);
             std::unordered_map<
                 std::string, std::tuple<std::string /* grad_var_name */,
                                         int /* block_idx */, int /* op_idx */>>
                 retv;
             for (auto it = param_grad_map.begin(); it != param_grad_map.end();
                  ++it) {
               const auto &grad_info = it->second;
               retv[it->first] = std::make_tuple(
                   grad_info.name_, grad_info.block_idx_, grad_info.op_idx_);
             }
             return retv;
140
           })
141 142
      .def("block", &ProgramDescBind::MutableBlock,
           py::return_value_policy::reference)
143
      .def("num_blocks", &ProgramDescBind::Size)
Y
Yu Yang 已提交
144
      .def("serialize_to_string", SerializeMessage<ProgramDescBind>)
145 146 147 148 149 150
      .def("parse_from_string",
           [](ProgramDescBind &program_desc, const std::string &data) {
             ProgramDesc *desc = program_desc.Proto();
             PADDLE_ENFORCE(desc->ParseFromString(data),
                            "Fail to parse ProgramDesc from string. This could "
                            "be a bug of Paddle.");
151
           });
152 153
}

F
fengjiayi 已提交
154
void BindBlockDesc(py::module &m) {
F
fengjiayi 已提交
155 156 157 158
  py::class_<BlockDescBind>(m, "BlockDesc", "")
      .def_property_readonly("id", &BlockDescBind::ID)
      .def_property_readonly("parent", &BlockDescBind::Parent)
      .def("append_op", &BlockDescBind::AppendOp,
F
fengjiayi 已提交
159
           py::return_value_policy::reference)
F
update  
fengjiayi 已提交
160 161 162 163
      .def("append_allocated_op",
           [](BlockDescBind &self, OpDescBind *op_desc) {
             self.AppendAllocatedOp(std::unique_ptr<OpDescBind>(op_desc));
           })
F
fengjiayi 已提交
164
      .def("prepend_op", &BlockDescBind::PrependOp,
165
           py::return_value_policy::reference)
D
dongzhihong 已提交
166
      .def("var",
F
fengjiayi 已提交
167
           [](BlockDescBind &self, py::bytes byte_name) {
F
fengjiayi 已提交
168
             std::string name = byte_name;
D
dongzhihong 已提交
169
             return self.Var(name);
F
fengjiayi 已提交
170
           },
Y
Yu Yang 已提交
171
           py::return_value_policy::reference)
Q
Qiao Longfei 已提交
172 173 174 175 176
      .def("has_var",
           [](BlockDescBind &self, py::bytes byte_name) {
             std::string name = byte_name;
             return self.HasVar(name);
           })
D
Dong Zhihong 已提交
177
      .def("find_var",
F
fengjiayi 已提交
178
           [](BlockDescBind &self, py::bytes byte_name) {
F
fengjiayi 已提交
179
             std::string name = byte_name;
D
Dong Zhihong 已提交
180
             return self.FindVar(name);
F
fengjiayi 已提交
181
           },
F
fengjiayi 已提交
182
           py::return_value_policy::reference)
F
fengjiayi 已提交
183
      .def("all_vars", &BlockDescBind::AllVars,
F
fengjiayi 已提交
184
           py::return_value_policy::reference)
185 186
      .def("op_size", &BlockDescBind::OpSize)
      .def("op", &BlockDescBind::Op, py::return_value_policy::reference)
Y
Yu Yang 已提交
187
      .def("serialize_to_string", SerializeMessage<BlockDescBind>);
188 189
}

F
fengjiayi 已提交
190
void BindVarDsec(py::module &m) {
F
fengjiayi 已提交
191
  py::enum_<DataType>(m, "DataType", "")
F
Fix bug  
fengjiayi 已提交
192 193 194 195 196 197 198 199
      .value("BOOL", DataType::BOOL)
      .value("INT16", DataType::INT16)
      .value("INT32", DataType::INT32)
      .value("INT64", DataType::INT64)
      .value("FP16", DataType::FP16)
      .value("FP32", DataType::FP32)
      .value("FP64", DataType::FP64);

Y
Yu Yang 已提交
200 201
  py::class_<VarDescBind> var_desc(m, "VarDesc", "");
  var_desc
F
fengjiayi 已提交
202
      .def("name",
F
fengjiayi 已提交
203
           [](const VarDescBind &self) {
F
fengjiayi 已提交
204 205 206 207
             py::bytes name = self.Name();
             return name;
           },
           py::return_value_policy::reference)
F
fengjiayi 已提交
208
      .def("set_shape", &VarDescBind::SetShape)
F
fengjiayi 已提交
209
      .def("set_dtype", &VarDescBind::SetDataType)
F
fengjiayi 已提交
210
      .def("shape", &VarDescBind::Shape, py::return_value_policy::reference)
F
fengjiayi 已提交
211
      .def("dtype", &VarDescBind::GetDataType)
Y
Stash  
Yu Yang 已提交
212
      .def("lod_level", &VarDescBind::GetLodLevel)
Y
Yu Yang 已提交
213 214
      .def("set_lod_level", &VarDescBind::SetLoDLevel)
      .def("type", &VarDescBind::GetType)
215
      .def("set_type", &VarDescBind::SetType)
Y
Yu Yang 已提交
216
      .def("serialize_to_string", SerializeMessage<VarDescBind>)
217 218
      .def("persistable", &VarDescBind::Persistable)
      .def("set_persistable", &VarDescBind::SetPersistable);
Y
Yu Yang 已提交
219 220 221

  py::enum_<VarDesc::VarType>(var_desc, "VarType", "")
      .value("LOD_TENSOR", VarDesc::LOD_TENSOR)
Y
Yu Yang 已提交
222 223
      .value("SELECTED_ROWS", VarDesc::SELECTED_ROWS)
      .value("FEED_MINIBATCH", VarDesc::FEED_MINIBATCH)
Y
Yu Yang 已提交
224
      .value("FETCH_LIST", VarDesc::FETCH_LIST)
Y
Yu Yang 已提交
225
      .value("STEP_SCOPES", VarDesc::STEP_SCOPES)
Y
Yu Yang 已提交
226 227
      .value("LOD_RANK_TABLE", VarDesc::LOD_RANK_TABLE)
      .value("LOD_TENSOR_ARRAY", VarDesc::LOD_TENSOR_ARRAY);
228 229
}

F
fengjiayi 已提交
230
void BindOpDesc(py::module &m) {
F
fengjiayi 已提交
231
  py::enum_<AttrType>(m, "AttrType", "")
Y
Yu Yang 已提交
232 233 234 235 236 237 238 239 240 241
      .value("INT", AttrType::INT)
      .value("INTS", AttrType::INTS)
      .value("FLOAT", AttrType::FLOAT)
      .value("FLOATS", AttrType::FLOATS)
      .value("STRING", AttrType::STRING)
      .value("STRINGS", AttrType::STRINGS)
      .value("BOOL", AttrType::BOOLEAN)
      .value("BOOLS", AttrType::BOOLEANS)
      .value("BLOCK", AttrType::BLOCK);

F
fengjiayi 已提交
242
  py::class_<OpDescBind> op_desc(m, "OpDesc", "");
F
update  
fengjiayi 已提交
243 244 245 246 247 248 249 250
  op_desc
      .def("__init__",
           [](OpDescBind &self, const std::string &type,
              const VariableNameMap &inputs, const VariableNameMap &outputs,
              const AttributeMap &attrs) {
             new (&self) OpDescBind(type, inputs, outputs, attrs);
           })
      .def("type", &OpDescBind::Type)
F
fengjiayi 已提交
251 252 253 254 255
      .def("set_type", &OpDescBind::SetType)
      .def("input", &OpDescBind::Input)
      .def("input_names", &OpDescBind::InputNames)
      .def("output", &OpDescBind::Output)
      .def("output_names", &OpDescBind::OutputNames)
F
update  
fengjiayi 已提交
256
      .def("set_input", &OpDescBind::SetInput)
F
fengjiayi 已提交
257
      .def("set_output", &OpDescBind::SetOutput)
F
update  
fengjiayi 已提交
258 259 260 261
      .def("input_arg_names", &OpDescBind::InputArgumentNames)
      .def("output_arg_names", &OpDescBind::OutputArgumentNames)
      .def("rename_input", &OpDescBind::RenameInput)
      .def("rename_output", &OpDescBind::RenameOutput)
F
fengjiayi 已提交
262 263 264 265 266 267
      .def("has_attr", &OpDescBind::HasAttr)
      .def("attr_type", &OpDescBind::GetAttrType)
      .def("attr_names", &OpDescBind::AttrNames)
      .def("set_attr", &OpDescBind::SetAttr)
      .def("attr", &OpDescBind::GetAttr)
      .def("set_block_attr", &OpDescBind::SetBlockAttr)
268
      .def("block_attr", &OpDescBind::GetBlockAttr)
F
fengjiayi 已提交
269
      .def("check_attrs", &OpDescBind::CheckAttrs)
270
      .def("infer_shape", &OpDescBind::InferShape)
Q
QI JUN 已提交
271
      .def("infer_var_type", &OpDescBind::InferVarType)
Y
Yu Yang 已提交
272
      .def("serialize_to_string", SerializeMessage<OpDescBind>);
273
}
Y
Yu Yang 已提交
274

275
}  // namespace pybind
276
}  // namespace paddle