protobuf.cc 14.4 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
#include "paddle/fluid/framework/block_desc.h"
22
#include "paddle/fluid/framework/ir/graph_helper.h"
Y
Yi Wang 已提交
23
#include "paddle/fluid/framework/op_desc.h"
24
#include "paddle/fluid/framework/process_mesh_desc.h"
Y
Yi Wang 已提交
25 26
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/var_desc.h"
27
#include "paddle/fluid/framework/version.h"
28
#include "paddle/fluid/pybind/pybind_boost_headers.h"
Y
Yu Yang 已提交
29

30
namespace paddle {
31
namespace pybind {
32

33 34 35
PyTypeObject *g_vartype_pytype = nullptr;
PyTypeObject *g_blockdesc_pytype = nullptr;

36
namespace pd = paddle::framework;
F
fengjiayi 已提交
37

Y
Yu Yang 已提交
38
template <typename T>
39 40
static pybind11::bytes SerializeMessage(
    T &self) {  // NOLINT due to pybind11 convention.
Y
Yu Yang 已提交
41 42
  // Check IsInitialized in Python
  std::string retv;
43 44
  PADDLE_ENFORCE_EQ(self.Proto()->SerializePartialToString(&retv),
                    true,
45 46
                    platform::errors::InvalidArgument(
                        "Failed to serialize input Desc to string."));
Y
Yu Yang 已提交
47 48 49
  return retv;
}

Y
Yu Yang 已提交
50
// Bind Methods
51 52 53
void BindProgramDesc(pybind11::module *m) {
  pybind11::class_<pd::ProgramDesc>(*m, "ProgramDesc", "")
      .def(pybind11::init<>())
Y
Yu Yang 已提交
54
      .def("__init__",
55 56
           [](pd::ProgramDesc &self, const pd::ProgramDesc &other) {
             new (&self) pd::ProgramDesc(other);
Y
Yu Yang 已提交
57
           })
58
      .def("__init__",
59
           [](pd::ProgramDesc &self, const pybind11::bytes &binary_str) {
60
             std::string str(binary_str);
61
             new (&self) pd::ProgramDesc(str);
62
           })
63 64
      .def("append_block",
           &pd::ProgramDesc::AppendBlock,
65
           pybind11::return_value_policy::reference)
66 67
      .def("block",
           &pd::ProgramDesc::MutableBlock,
68 69
           pybind11::return_value_policy::reference)
      .def("num_blocks", &pd::ProgramDesc::Size)
70
      .def("flush", &pd::ProgramDesc::Flush)
71 72
      .def("get_feed_target_names", &pd::ProgramDesc::GetFeedTargetNames)
      .def("get_fetch_target_names", &pd::ProgramDesc::GetFetchTargetNames)
73
      .def("serialize_to_string", SerializeMessage<pd::ProgramDesc>)
74
      .def("parse_from_string",
75 76
           [](pd::ProgramDesc &program_desc, const std::string &data) {
             pd::proto::ProgramDesc *desc = program_desc.Proto();
77
             PADDLE_ENFORCE_EQ(
78 79
                 desc->ParseFromString(data),
                 true,
80 81
                 platform::errors::InvalidArgument(
                     "Failed to parse ProgramDesc from binary string."));
X
version  
Xin Pan 已提交
82
           })
83 84 85 86 87 88
      .def(
          "_set_version",
          [](pd::ProgramDesc &self, int64_t version) {
            return self.SetVersion(version);
          },
          pybind11::arg("version") = pd::kCurProgramVersion)
89
      .def("_version",
90 91 92 93
           [](pd::ProgramDesc &self) -> int64_t { return self.Version(); })
      .def("get_op_deps", [](const framework::ProgramDesc &program) {
        return framework::ir::GetOpDependencies(program);
      });
94 95
}

96 97 98
void BindProcessMeshDesc(pybind11::module *m) {
  pybind11::class_<pd::ProcessMeshDesc>(*m, "ProcessMeshDesc", "")
      .def(pybind11::init<const std::vector<int32_t> &,
99 100
                          const std::vector<int32_t> &,
                          int32_t>())
101 102 103 104 105 106 107
      .def_property_readonly("id", &pd::ProcessMeshDesc::ID)
      .def_property_readonly("parent", &pd::ProcessMeshDesc::Parent)
      .def_property_readonly("topology", &pd::ProcessMeshDesc::Topology)
      .def_property_readonly("process_group",
                             &pd::ProcessMeshDesc::ProcessGroup);
}

108
void BindBlockDesc(pybind11::module *m) {
109 110 111
  pybind11::class_<pd::BlockDesc> blockdesc(*m, "BlockDesc", "");
  g_blockdesc_pytype = (PyTypeObject *)blockdesc.ptr();  // NOLINT
  blockdesc.def_property_readonly("id", &pd::BlockDesc::ID)
112 113
      .def_property_readonly("parent", &pd::BlockDesc::Parent)
      .def("get_forward_block_idx", &pd::BlockDesc::ForwardBlockID)
W
Wu Yi 已提交
114
      .def("_set_forward_block_idx", &pd::BlockDesc::SetForwardBlockID)
115 116
      .def("append_op",
           &pd::BlockDesc::AppendOp,
117
           pybind11::return_value_policy::reference)
118 119
      .def("_prepend_op",
           &pd::BlockDesc::PrependOp,
120
           pybind11::return_value_policy::reference)
121 122
      .def("_insert_op",
           &pd::BlockDesc::InsertOp,
123
           pybind11::return_value_policy::reference)
W
Wu Yi 已提交
124
      .def("_remove_op", &pd::BlockDesc::RemoveOp)
125 126 127 128 129 130 131 132 133 134 135 136 137 138
      .def(
          "var",
          [](pd::BlockDesc &self, pybind11::bytes byte_name) {
            std::string name = byte_name;
            return self.Var(name);
          },
          pybind11::return_value_policy::reference)
      .def(
          "has_var",
          [](pd::BlockDesc &self, pybind11::bytes byte_name) {
            std::string name = byte_name;
            return self.HasVar(name);
          },
          pybind11::return_value_policy::reference)
W
Wu Yi 已提交
139
      .def("_rename_var",
140 141
           [](pd::BlockDesc &self,
              const pybind11::bytes &byte_name,
142
              const pybind11::bytes &byte_name_new) {
T
typhoonzero 已提交
143 144
             std::string name = byte_name;
             std::string new_name = byte_name_new;
T
wip  
typhoonzero 已提交
145
             self.RenameVar(name, new_name);
Q
Qiao Longfei 已提交
146
           })
F
fengjiayi 已提交
147
      .def("has_var_recursive",
148
           [](pd::BlockDesc &self, pybind11::bytes byte_name) {
F
fengjiayi 已提交
149 150 151
             std::string name = byte_name;
             return self.HasVarRecursive(name);
           })
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
      .def(
          "find_var",
          [](pd::BlockDesc &self, pybind11::bytes byte_name) {
            std::string name = byte_name;
            return self.FindVar(name);
          },
          pybind11::return_value_policy::reference)
      .def(
          "find_var_recursive",
          [](pd::BlockDesc &self, pybind11::bytes byte_name) {
            std::string name = byte_name;
            return self.FindVarRecursive(name);
          },
          pybind11::return_value_policy::reference)
      .def(
          "_remove_var",
          [](pd::BlockDesc &self, pybind11::bytes byte_name) {
            std::string name = byte_name;
            return self.RemoveVar(name);
          },
          pybind11::return_value_policy::reference)
173 174
      .def("all_vars",
           &pd::BlockDesc::AllVars,
175 176 177
           pybind11::return_value_policy::reference)
      .def("op_size", &pd::BlockDesc::OpSize)
      .def("op", &pd::BlockDesc::Op, pybind11::return_value_policy::reference)
178 179
      .def("serialize_to_string", SerializeMessage<pd::BlockDesc>)
      .def("_move_from", &pd::BlockDesc::MoveFrom);
180 181
}

182 183
void BindVarDsec(pybind11::module *m) {
  pybind11::class_<pd::VarDesc> var_desc(*m, "VarDesc", "");
W
WangZhen 已提交
184
  var_desc.def(pybind11::init<const std::string &>())
M
minqiyang 已提交
185
      .def("name", &pd::VarDesc::Name, pybind11::return_value_policy::reference)
186 187 188
      .def("set_name", &pd::VarDesc::SetName)
      .def("set_shape", &pd::VarDesc::SetShape)
      .def("set_shapes", &pd::VarDesc::SetShapes)
H
hong 已提交
189
      .def("get_shape", &pd::VarDesc::GetShape)
190 191
      .def("set_dtype", &pd::VarDesc::SetDataType)
      .def("set_dtypes", &pd::VarDesc::SetDataTypes)
192 193
      .def("shape",
           &pd::VarDesc::GetShape,
194
           pybind11::return_value_policy::reference)
195 196
      .def("shapes",
           &pd::VarDesc::GetShapes,
197
           pybind11::return_value_policy::reference)
198 199
      .def("dtype",
           &pd::VarDesc::GetDataType,
200
           pybind11::return_value_policy::reference)
201 202
      .def("element_size",
           &pd::VarDesc::ElementSize,
203
           pybind11::return_value_policy::reference)
204 205
      .def("dtypes",
           &pd::VarDesc::GetDataTypes,
206 207
           pybind11::return_value_policy::reference)
      .def("lod_level", &pd::VarDesc::GetLoDLevel)
208 209
      .def("lod_levels",
           &pd::VarDesc::GetLoDLevels,
210 211 212 213 214 215 216
           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)
H
Huihuang Zheng 已提交
217
      .def("set_persistable", &pd::VarDesc::SetPersistable)
218 219 220 221 222 223 224 225
      .def("is_parameter", &pd::VarDesc::IsParameter)
      .def("set_is_parameter", &pd::VarDesc::SetIsParameter)
      .def("clear_is_parameter", &pd::VarDesc::ClearIsParameter)
      .def("has_is_parameter", &pd::VarDesc::HasIsParameter)
      .def("stop_gradient", &pd::VarDesc::StopGradient)
      .def("set_stop_gradient", &pd::VarDesc::SetStopGradient)
      .def("clear_stop_gradient", &pd::VarDesc::ClearStopGradient)
      .def("has_stop_gradient", &pd::VarDesc::HasStopGradient)
H
Huihuang Zheng 已提交
226
      .def("need_check_feed", &pd::VarDesc::NeedCheckFeed)
227 228 229 230 231
      .def("set_need_check_feed", &pd::VarDesc::SetNeedCheckFeed)
      .def("has_attr", &pd::VarDesc::HasAttr)
      .def("attr_names", &pd::VarDesc::AttrNames)
      .def("_set_attr", &pd::VarDesc::SetAttr)
      .def("remove_attr", &pd::VarDesc::RemoveAttr)
232
      .def("id", &pd::VarDesc::Id)
233 234
      .def("original_id", &pd::VarDesc::OriginalId)
      .def("set_original_id", &pd::VarDesc::SetOriginalId)
235
      .def("attr", &pd::VarDesc::GetAttr);
Y
Yu Yang 已提交
236

237 238 239
  pybind11::enum_<pd::proto::VarType::Type> vartype(var_desc, "VarType", "");
  g_vartype_pytype = (PyTypeObject *)vartype.ptr();  // NOLINT
  vartype.value("BOOL", pd::proto::VarType::BOOL)
240
      .value("UINT8", pd::proto::VarType::UINT8)
Q
qingqing01 已提交
241
      .value("INT8", pd::proto::VarType::INT8)
242 243 244 245 246 247
      .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)
248
      .value("BF16", pd::proto::VarType::BF16)
249 250
      .value("COMPLEX64", pd::proto::VarType::COMPLEX64)
      .value("COMPLEX128", pd::proto::VarType::COMPLEX128)
251 252 253 254 255 256 257 258 259
      .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("PLACE_LIST", pd::proto::VarType::PLACE_LIST)
      .value("READER", pd::proto::VarType::READER)
S
Steffy-zxf 已提交
260 261 262 263
      .value("RAW", pd::proto::VarType::RAW)
      .value("STRING", pd::proto::VarType::STRING)
      .value("STRINGS", pd::proto::VarType::STRINGS)
      .value("VOCAB", pd::proto::VarType::VOCAB);
264 265
}

266 267 268 269
void BindOpDesc(pybind11::module *m) {
  pybind11::enum_<pd::proto::AttrType>(*m, "AttrType", "")
      .value("INT", pd::proto::AttrType::INT)
      .value("INTS", pd::proto::AttrType::INTS)
T
tangwei12 已提交
270 271
      .value("LONG", pd::proto::AttrType::LONG)
      .value("LONGS", pd::proto::AttrType::LONGS)
272 273 274 275 276 277
      .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)
Y
Yancey1989 已提交
278 279
      .value("BLOCK", pd::proto::AttrType::BLOCK)
      .value("BLOCKS", pd::proto::AttrType::BLOCKS);
Y
Yu Yang 已提交
280

281
  pybind11::class_<pd::OpDesc> op_desc(*m, "OpDesc", "");
F
fengjiayi 已提交
282
  op_desc
283
      .def(
284 285
          "__init__",
          [](pd::OpDesc &self) { new (&self) pd::OpDesc(); },
286
          pybind11::return_value_policy::reference)
287 288 289 290 291 292 293
      .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)
H
hong 已提交
294
      .def("set_input",
295 296
           [](pd::OpDesc &self,
              const std::string &name,
H
hong 已提交
297 298 299 300
              const std::vector<std::string> &vec_var_name) {
             self.SetInput(name, vec_var_name);
           })
      .def("set_output",
301 302
           [](pd::OpDesc &self,
              const std::string &name,
H
hong 已提交
303 304 305
              const std::vector<std::string> &vec_var_name) {
             self.SetOutput(name, vec_var_name);
           })
306
      .def("remove_output", &pd::OpDesc::RemoveOutput)
307
      .def("remove_input", &pd::OpDesc::RemoveInput)
308 309
      .def("input_arg_names", &pd::OpDesc::InputArgumentNames)
      .def("output_arg_names", &pd::OpDesc::OutputArgumentNames)
W
Wu Yi 已提交
310 311
      .def("_rename_input", &pd::OpDesc::RenameInput)
      .def("_rename_output", &pd::OpDesc::RenameOutput)
312 313 314
      .def("has_attr", &pd::OpDesc::HasAttr)
      .def("attr_type", &pd::OpDesc::GetAttrType)
      .def("attr_names", &pd::OpDesc::AttrNames)
W
Wu Yi 已提交
315
      .def("_set_attr", &pd::OpDesc::SetAttr)
316
      .def("remove_attr", &pd::OpDesc::RemoveAttr)
317 318
      .def("attr", &pd::OpDesc::GetAttr)
      .def("set_block_attr", &pd::OpDesc::SetBlockAttr)
319
      .def("set_blocks_attr", &pd::OpDesc::SetBlocksAttr)
T
typhoonzero 已提交
320
      .def("set_serialized_attr",
321 322
           [](pd::OpDesc &self,
              const std::string &name,
323
              const pybind11::bytes &seriralized) {
T
typhoonzero 已提交
324 325 326
             std::string ser(seriralized);
             self.SetAttr(name, ser);
           })
W
Wu Yi 已提交
327 328
      .def("_block_attr_id", &pd::OpDesc::GetBlockAttrId)
      .def("_blocks_attr_ids", &pd::OpDesc::GetBlocksAttrIds)
329 330 331
      .def("check_attrs", &pd::OpDesc::CheckAttrs)
      .def("infer_shape", &pd::OpDesc::InferShape)
      .def("infer_var_type", &pd::OpDesc::InferVarType)
332
      .def("set_is_target", &pd::OpDesc::SetIsTarget)
333
      .def("serialize_to_string", SerializeMessage<pd::OpDesc>)
334
      .def(
335 336
          "block",
          [](pd::OpDesc &self) { return self.Block(); },
337
          pybind11::return_value_policy::reference)
338
      .def("id", &pd::OpDesc::Id)
339 340
      .def("original_id", &pd::OpDesc::OriginalId)
      .def("set_original_id", &pd::OpDesc::SetOriginalId)
341 342
      .def("inputs", &pd::OpDesc::Inputs)
      .def("outputs", &pd::OpDesc::Outputs);
343
}
Y
Yu Yang 已提交
344

345
}  // namespace pybind
346
}  // namespace paddle