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

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 已提交
14
#include "paddle/fluid/pybind/protobuf.h"
15

Y
Yu Yang 已提交
16
#include <deque>
Y
Yu Yang 已提交
17
#include <iostream>
L
Luo Tao 已提交
18 19
#include <string>
#include <tuple>
20

Y
Yi Wang 已提交
21 22 23 24 25
#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"
26

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

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

98
namespace paddle {
99
namespace pybind {
100

101
namespace pd = paddle::framework;
F
fengjiayi 已提交
102

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

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

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

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

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  pybind11::enum_<pd::proto::VarType::Type>(var_desc, "VarType", "")
      .value("BOOL", pd::proto::VarType::BOOL)
      .value("INT16", pd::proto::VarType::INT16)
      .value("INT32", pd::proto::VarType::INT32)
      .value("INT64", pd::proto::VarType::INT64)
      .value("FP16", pd::proto::VarType::FP16)
      .value("FP32", pd::proto::VarType::FP32)
      .value("FP64", pd::proto::VarType::FP64)
      .value("LOD_TENSOR", pd::proto::VarType::LOD_TENSOR)
      .value("SELECTED_ROWS", pd::proto::VarType::SELECTED_ROWS)
      .value("FEED_MINIBATCH", pd::proto::VarType::FEED_MINIBATCH)
      .value("FETCH_LIST", pd::proto::VarType::FETCH_LIST)
      .value("STEP_SCOPES", pd::proto::VarType::STEP_SCOPES)
      .value("LOD_RANK_TABLE", pd::proto::VarType::LOD_RANK_TABLE)
      .value("LOD_TENSOR_ARRAY", pd::proto::VarType::LOD_TENSOR_ARRAY)
      .value("CHANNEL", pd::proto::VarType::CHANNEL)
      .value("PLACE_LIST", pd::proto::VarType::PLACE_LIST)
      .value("READER", pd::proto::VarType::READER)
      .value("RAW", pd::proto::VarType::RAW);
273 274
}

275 276 277 278 279 280 281 282 283 284 285
void BindOpDesc(pybind11::module *m) {
  pybind11::enum_<pd::proto::AttrType>(*m, "AttrType", "")
      .value("INT", pd::proto::AttrType::INT)
      .value("INTS", pd::proto::AttrType::INTS)
      .value("FLOAT", pd::proto::AttrType::FLOAT)
      .value("FLOATS", pd::proto::AttrType::FLOATS)
      .value("STRING", pd::proto::AttrType::STRING)
      .value("STRINGS", pd::proto::AttrType::STRINGS)
      .value("BOOL", pd::proto::AttrType::BOOLEAN)
      .value("BOOLS", pd::proto::AttrType::BOOLEANS)
      .value("BLOCK", pd::proto::AttrType::BLOCK);
Y
Yu Yang 已提交
286

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

325
}  // namespace pybind
326
}  // namespace paddle