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

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/pybind/protobuf.h"
Y
Yu Yang 已提交
16
#include <deque>
Y
Yu Yang 已提交
17
#include <iostream>
L
Luo Tao 已提交
18 19
#include <string>
#include <tuple>
Y
Yi Wang 已提交
20 21 22 23 24
#include "paddle/fluid/framework/backward.h"
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/var_desc.h"
25

Y
Yu Yang 已提交
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 51 52
// 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 已提交
53 54
  template <typename T>
  typename std::enable_if<
Y
Yu Yang 已提交
55
      !std::is_same<T, boost::detail::variant::void_>::value, bool>::type
Y
Yu Yang 已提交
56
  try_load(handle src, bool convert) {
Y
Yu Yang 已提交
57 58 59 60 61 62 63 64 65
    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 已提交
66 67 68 69 70 71 72
  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 已提交
73 74 75 76 77 78
  bool load(handle src, bool convert) {
    auto unused = {false, try_load<Ts>(src, convert)...};
    (void)(unused);
    return load_success_;
  }

Y
Yu Yang 已提交
79
  static handle cast(Type const &src, return_value_policy policy,
Y
Yu Yang 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
                     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

97
namespace paddle {
98
namespace pybind {
99

F
fengjiayi 已提交
100 101
using namespace paddle::framework;  // NOLINT

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

Y
Yu Yang 已提交
111
// Bind Methods
L
Luo Tao 已提交
112
void BindProgramDesc(py::module &m) {  // NOLINT
Y
Yu Yang 已提交
113
  py::class_<ProgramDesc>(m, "ProgramDesc", "")
114
      .def(py::init<>())
Y
Yu Yang 已提交
115
      .def("__init__",
Y
Yu Yang 已提交
116 117
           [](ProgramDesc &self, const ProgramDesc &other) {
             new (&self) ProgramDesc(other);
Y
Yu Yang 已提交
118
           })
119
      .def("__init__",
Y
Yu Yang 已提交
120
           [](ProgramDesc &self, const py::bytes &binary_str) {
121
             std::string str(binary_str);
Y
Yu Yang 已提交
122
             new (&self) ProgramDesc(str);
123
           })
Y
Yu Yang 已提交
124
      .def("append_block", &ProgramDesc::AppendBlock,
125
           py::return_value_policy::reference)
126
      .def("append_backward",
Y
Yu Yang 已提交
127
           [](ProgramDesc &program_desc, const VarDesc &target,
128
              const std::unordered_set<std::string> &no_grad_vars) {
Q
qiaolongfei 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141
             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;
142
           })
Y
Yu Yang 已提交
143
      .def("block", &ProgramDesc::MutableBlock,
144
           py::return_value_policy::reference)
Y
Yu Yang 已提交
145 146
      .def("num_blocks", &ProgramDesc::Size)
      .def("serialize_to_string", SerializeMessage<ProgramDesc>)
147
      .def("parse_from_string",
Y
Yu Yang 已提交
148
           [](ProgramDesc &program_desc, const std::string &data) {
149
             proto::ProgramDesc *desc = program_desc.Proto();
150 151 152
             PADDLE_ENFORCE(desc->ParseFromString(data),
                            "Fail to parse ProgramDesc from string. This could "
                            "be a bug of Paddle.");
153
           });
154 155
}

L
Luo Tao 已提交
156
void BindBlockDesc(py::module &m) {  // NOLINT
Y
Yu Yang 已提交
157 158 159
  py::class_<BlockDesc>(m, "BlockDesc", "")
      .def_property_readonly("id", &BlockDesc::ID)
      .def_property_readonly("parent", &BlockDesc::Parent)
Y
Yu Yang 已提交
160 161
      .def("get_forward_block_idx", &BlockDesc::ForwardBlockID)
      .def("set_forward_block_idx", &BlockDesc::SetForwardBlockID)
Y
Yu Yang 已提交
162
      .def("append_op", &BlockDesc::AppendOp,
F
fengjiayi 已提交
163
           py::return_value_policy::reference)
Y
Yu Yang 已提交
164
      .def("prepend_op", &BlockDesc::PrependOp,
165
           py::return_value_policy::reference)
166 167
      .def("insert_op", &BlockDesc::InsertOp,
           py::return_value_policy::reference)
T
typhoonzero 已提交
168
      .def("remove_op", &BlockDesc::RemoveOp)
D
dongzhihong 已提交
169
      .def("var",
Y
Yu Yang 已提交
170
           [](BlockDesc &self, py::bytes byte_name) {
F
fengjiayi 已提交
171
             std::string name = byte_name;
D
dongzhihong 已提交
172
             return self.Var(name);
F
fengjiayi 已提交
173
           },
Y
Yu Yang 已提交
174
           py::return_value_policy::reference)
Q
Qiao Longfei 已提交
175
      .def("has_var",
Y
Yu Yang 已提交
176
           [](BlockDesc &self, py::bytes byte_name) {
Q
Qiao Longfei 已提交
177 178
             std::string name = byte_name;
             return self.HasVar(name);
T
wip  
typhoonzero 已提交
179 180
           },
           py::return_value_policy::reference)
T
typhoonzero 已提交
181
      .def("rename_var",
T
wip  
typhoonzero 已提交
182 183
           [](BlockDesc &self, const py::bytes &byte_name,
              const py::bytes &byte_name_new) {
T
typhoonzero 已提交
184 185
             std::string name = byte_name;
             std::string new_name = byte_name_new;
T
wip  
typhoonzero 已提交
186
             self.RenameVar(name, new_name);
Q
Qiao Longfei 已提交
187
           })
F
fengjiayi 已提交
188
      .def("has_var_recursive",
189
           [](BlockDesc &self, py::bytes byte_name) {
F
fengjiayi 已提交
190 191 192
             std::string name = byte_name;
             return self.HasVarRecursive(name);
           })
D
Dong Zhihong 已提交
193
      .def("find_var",
Y
Yu Yang 已提交
194
           [](BlockDesc &self, py::bytes byte_name) {
F
fengjiayi 已提交
195
             std::string name = byte_name;
D
Dong Zhihong 已提交
196
             return self.FindVar(name);
F
fengjiayi 已提交
197
           },
F
fengjiayi 已提交
198
           py::return_value_policy::reference)
F
fengjiayi 已提交
199
      .def("find_var_recursive",
200
           [](BlockDesc &self, py::bytes byte_name) {
F
fengjiayi 已提交
201 202 203 204
             std::string name = byte_name;
             return self.FindVarRecursive(name);
           },
           py::return_value_policy::reference)
L
Luo Tao 已提交
205 206 207 208 209 210
      .def("remove_var",
           [](BlockDesc &self, py::bytes byte_name) {
             std::string name = byte_name;
             return self.RemoveVar(name);
           },
           py::return_value_policy::reference)
Y
Yu Yang 已提交
211 212 213 214
      .def("all_vars", &BlockDesc::AllVars, py::return_value_policy::reference)
      .def("op_size", &BlockDesc::OpSize)
      .def("op", &BlockDesc::Op, py::return_value_policy::reference)
      .def("serialize_to_string", SerializeMessage<BlockDesc>);
215 216
}

L
Luo Tao 已提交
217
void BindVarDsec(py::module &m) {  // NOLINT
Y
Yu Yang 已提交
218
  py::class_<VarDesc> var_desc(m, "VarDesc", "");
Y
Yu Yang 已提交
219
  var_desc
F
fengjiayi 已提交
220
      .def("name",
T
wip  
typhoonzero 已提交
221
           [](VarDesc &self) {
F
fengjiayi 已提交
222 223 224 225
             py::bytes name = self.Name();
             return name;
           },
           py::return_value_policy::reference)
226
      .def("set_name", &VarDesc::SetName)
Y
Yu Yang 已提交
227
      .def("set_shape", &VarDesc::SetShape)
F
fengjiayi 已提交
228
      .def("set_shapes", &VarDesc::SetShapes)
Y
Yu Yang 已提交
229
      .def("set_dtype", &VarDesc::SetDataType)
F
fengjiayi 已提交
230
      .def("set_dtypes", &VarDesc::SetDataTypes)
231
      .def("set_capacity", &VarDesc::SetCapacity)
F
fengjiayi 已提交
232 233
      .def("shape", &VarDesc::GetShape, py::return_value_policy::reference)
      .def("shapes", &VarDesc::GetShapes, py::return_value_policy::reference)
234
      .def("dtype", &VarDesc::GetDataType, py::return_value_policy::reference)
F
fengjiayi 已提交
235
      .def("dtypes", &VarDesc::GetDataTypes, py::return_value_policy::reference)
236
      .def("lod_level", &VarDesc::GetLoDLevel)
F
fengjiayi 已提交
237 238
      .def("lod_levels", &VarDesc::GetLoDLevels,
           py::return_value_policy::reference)
Y
Yu Yang 已提交
239
      .def("set_lod_level", &VarDesc::SetLoDLevel)
F
fengjiayi 已提交
240
      .def("set_lod_levels", &VarDesc::SetLoDLevels)
Y
Yu Yang 已提交
241 242 243 244 245
      .def("type", &VarDesc::GetType)
      .def("set_type", &VarDesc::SetType)
      .def("serialize_to_string", SerializeMessage<VarDesc>)
      .def("persistable", &VarDesc::Persistable)
      .def("set_persistable", &VarDesc::SetPersistable);
Y
Yu Yang 已提交
246

247
  py::enum_<proto::VarType::Type>(var_desc, "VarType", "")
248 249 250 251 252 253 254
      .value("BOOL", proto::VarType::BOOL)
      .value("INT16", proto::VarType::INT16)
      .value("INT32", proto::VarType::INT32)
      .value("INT64", proto::VarType::INT64)
      .value("FP16", proto::VarType::FP16)
      .value("FP32", proto::VarType::FP32)
      .value("FP64", proto::VarType::FP64)
255 256 257 258 259 260 261
      .value("LOD_TENSOR", proto::VarType::LOD_TENSOR)
      .value("SELECTED_ROWS", proto::VarType::SELECTED_ROWS)
      .value("FEED_MINIBATCH", proto::VarType::FEED_MINIBATCH)
      .value("FETCH_LIST", proto::VarType::FETCH_LIST)
      .value("STEP_SCOPES", proto::VarType::STEP_SCOPES)
      .value("LOD_RANK_TABLE", proto::VarType::LOD_RANK_TABLE)
      .value("LOD_TENSOR_ARRAY", proto::VarType::LOD_TENSOR_ARRAY)
262
      .value("CHANNEL", proto::VarType::CHANNEL)
263
      .value("PLACE_LIST", proto::VarType::PLACE_LIST)
Y
Yang Yang 已提交
264
      .value("READER", proto::VarType::READER)
T
typhoonzero 已提交
265
      .value("RAW", proto::VarType::RAW);
266 267
}

L
Luo Tao 已提交
268
void BindOpDesc(py::module &m) {  // NOLINT
269 270 271 272 273 274 275 276 277 278
  py::enum_<proto::AttrType>(m, "AttrType", "")
      .value("INT", proto::AttrType::INT)
      .value("INTS", proto::AttrType::INTS)
      .value("FLOAT", proto::AttrType::FLOAT)
      .value("FLOATS", proto::AttrType::FLOATS)
      .value("STRING", proto::AttrType::STRING)
      .value("STRINGS", proto::AttrType::STRINGS)
      .value("BOOL", proto::AttrType::BOOLEAN)
      .value("BOOLS", proto::AttrType::BOOLEANS)
      .value("BLOCK", proto::AttrType::BLOCK);
Y
Yu Yang 已提交
279

Y
Yu Yang 已提交
280
  py::class_<OpDesc> op_desc(m, "OpDesc", "");
F
fengjiayi 已提交
281
  op_desc
282
      .def("__init__", [](OpDesc &self) { new (&self) OpDesc(); },
F
fengjiayi 已提交
283
           py::return_value_policy::reference)
284 285
      .def("copy_from", &OpDesc::CopyFrom)
      .def("type", &OpDesc::Type)
Y
Yu Yang 已提交
286 287 288 289 290
      .def("set_type", &OpDesc::SetType)
      .def("input", &OpDesc::Input)
      .def("input_names", &OpDesc::InputNames)
      .def("output", &OpDesc::Output)
      .def("output_names", &OpDesc::OutputNames)
291
      .def("set_input", &OpDesc::SetInput)
Y
Yu Yang 已提交
292
      .def("set_output", &OpDesc::SetOutput)
293 294 295 296
      .def("input_arg_names", &OpDesc::InputArgumentNames)
      .def("output_arg_names", &OpDesc::OutputArgumentNames)
      .def("rename_input", &OpDesc::RenameInput)
      .def("rename_output", &OpDesc::RenameOutput)
Y
Yu Yang 已提交
297 298 299 300 301 302
      .def("has_attr", &OpDesc::HasAttr)
      .def("attr_type", &OpDesc::GetAttrType)
      .def("attr_names", &OpDesc::AttrNames)
      .def("set_attr", &OpDesc::SetAttr)
      .def("attr", &OpDesc::GetAttr)
      .def("set_block_attr", &OpDesc::SetBlockAttr)
T
typhoonzero 已提交
303
      .def("set_serialized_attr",
T
typhoonzero 已提交
304
           [](OpDesc &self, const std::string &name,
T
typhoonzero 已提交
305 306 307 308
              const py::bytes &seriralized) {
             std::string ser(seriralized);
             self.SetAttr(name, ser);
           })
Y
Yu Yang 已提交
309 310 311 312
      .def("block_attr", &OpDesc::GetBlockAttr)
      .def("check_attrs", &OpDesc::CheckAttrs)
      .def("infer_shape", &OpDesc::InferShape)
      .def("infer_var_type", &OpDesc::InferVarType)
313 314
      .def("serialize_to_string", SerializeMessage<OpDesc>)
      .def("block", &OpDesc::Block, py::return_value_policy::reference);
315
}
Y
Yu Yang 已提交
316

317
}  // namespace pybind
318
}  // namespace paddle