protobuf.cc 9.8 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 "paddle/framework/attribute.h"
18 19

namespace paddle {
20
namespace pybind {
21

Y
Yu Yang 已提交
22 23
using namespace paddle::framework;  // NOLINT

Y
Yu Yang 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
template <typename T>
inline std::vector<T> RepeatedToVector(
    const google::protobuf::RepeatedField<T> &repeated_field) {
  std::vector<T> ret;
  ret.reserve(repeated_field.size());
  std::copy(
      repeated_field.begin(), repeated_field.end(), std::back_inserter(ret));
  return ret;
}

template <typename T, typename RepeatedField>
inline void VectorToRepeated(const std::vector<T> &vec,
                             RepeatedField *repeated_field) {
  repeated_field->Reserve(vec.size());
  for (auto &elem : vec) {
    *repeated_field->Add() = elem;
  }
}

Y
Yu Yang 已提交
43 44 45
class ProgramDescBind;
class OpDescBind;
class BlockDescBind;
Y
Fix bug  
Yu Yang 已提交
46
class VarDescBind;
Y
Yu Yang 已提交
47

Y
Fix bug  
Yu Yang 已提交
48
class VarDescBind {
Y
Yu Yang 已提交
49
public:
Y
Fix bug  
Yu Yang 已提交
50 51 52 53 54 55 56
  explicit VarDescBind(const std::string &name) { var_desc_.set_name(name); }

  VarDesc *Proto() { return &var_desc_; }

private:
  VarDesc var_desc_;
};
Y
Yu Yang 已提交
57

Y
Fix bug  
Yu Yang 已提交
58 59
class OpDescBind {
public:
Y
Yu Yang 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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
  OpDesc *Proto() {
    Sync();
    return &op_desc_;
  }

  std::string Type() const { return op_desc_.type(); }

  void SetType(const std::string &type) { op_desc_.set_type(type); }

  const std::vector<std::string> &Input(const std::string &name) const {
    auto it = inputs_.find(name);
    PADDLE_ENFORCE(
        it != inputs_.end(), "Input %s cannot be found in Op %s", name, Type());
    return it->second;
  }

  std::vector<std::string> InputNames() const {
    std::vector<std::string> retv;
    retv.reserve(this->inputs_.size());
    for (auto &ipt : this->inputs_) {
      retv.push_back(ipt.first);
    }
    return retv;
  }

  void SetInput(const std::string &param_name,
                const std::vector<std::string> &args) {
    need_update_ = true;
    inputs_[param_name] = args;
  }

  const std::vector<std::string> &Output(const std::string &name) const {
    auto it = outputs_.find(name);
    PADDLE_ENFORCE(it != outputs_.end(),
                   "Output %s cannot be found in Op %s",
                   name,
                   Type());
    return it->second;
  }

  std::vector<std::string> OutputNames() const {
    std::vector<std::string> retv;
    retv.reserve(this->outputs_.size());
    for (auto &ipt : this->outputs_) {
      retv.push_back(ipt.first);
    }
    return retv;
  }

  void SetOutput(const std::string &param_name,
                 const std::vector<std::string> &args) {
    need_update_ = true;
    this->outputs_[param_name] = args;
  }

  std::string DebugString() { return this->Proto()->DebugString(); }

  void Sync() {
    if (need_update_) {
      this->op_desc_.mutable_inputs()->Clear();
      for (auto &ipt : inputs_) {
        auto *input = op_desc_.add_inputs();
        input->set_parameter(ipt.first);
        VectorToRepeated(ipt.second, input->mutable_arguments());
      }

      this->op_desc_.mutable_outputs()->Clear();
      for (auto &opt : outputs_) {
        auto *output = op_desc_.add_outputs();
        output->set_parameter(opt.first);
        VectorToRepeated(opt.second, output->mutable_arguments());
      }

      need_update_ = false;
    }
  }
Y
Yu Yang 已提交
136 137 138

private:
  OpDesc op_desc_;
Y
Yu Yang 已提交
139 140 141 142 143
  std::unordered_map<std::string, std::vector<std::string>> inputs_;
  std::unordered_map<std::string, std::vector<std::string>> outputs_;
  std::unordered_map<std::string, Attribute> attrs_;

  bool need_update_{false};
Y
Yu Yang 已提交
144 145 146 147 148 149 150
};

class BlockDescBind {
public:
  BlockDescBind(ProgramDescBind *prog, BlockDesc *desc)
      : prog_(prog), desc_(desc), need_update_(false) {}

Y
Fix bug  
Yu Yang 已提交
151 152 153
  BlockDescBind(const BlockDescBind &o) = delete;
  BlockDescBind &operator=(const BlockDescBind &o) = delete;

Y
Yu Yang 已提交
154
  int32_t id() const { return desc_->idx(); }
Y
Yu Yang 已提交
155 156 157

  int32_t Parent() const { return desc_->parent_idx(); }

Y
Fix bug  
Yu Yang 已提交
158 159 160 161 162 163 164 165 166 167 168
  VarDescBind *NewVar(const std::string &name) {
    need_update_ = true;
    auto it = vars_.find(name);
    PADDLE_ENFORCE(it == vars_.end(), "Duplicated variable %s", name);
    auto var = new VarDescBind(name);
    vars_[name].reset(var);
    return var;
  }

  BlockDescBind *ParentBlock() const;

Y
Yu Yang 已提交
169 170
  OpDescBind *AppendOp() {
    need_update_ = true;
Y
Fix bug  
Yu Yang 已提交
171 172
    ops_.emplace_back(new OpDescBind());
    return ops_.back().get();
Y
Yu Yang 已提交
173 174 175 176 177 178 179 180
  }

  void Sync() {
    if (need_update_) {
      auto &op_field = *this->desc_->mutable_ops();
      op_field.Clear();
      op_field.Reserve(static_cast<int>(ops_.size()));
      for (auto &op_desc : ops_) {
Y
Fix bug  
Yu Yang 已提交
181
        op_field.AddAllocated(op_desc->Proto());
Y
Yu Yang 已提交
182
      }
Y
Fix bug  
Yu Yang 已提交
183
      need_update_ = false;
Y
Yu Yang 已提交
184 185 186 187 188 189 190 191
    }
  }

private:
  ProgramDescBind *prog_;  // not_own
  BlockDesc *desc_;        // not_own
  bool need_update_;

Y
Fix bug  
Yu Yang 已提交
192 193
  std::deque<std::unique_ptr<OpDescBind>> ops_;
  std::unordered_map<std::string, std::unique_ptr<VarDescBind>> vars_;
Y
Yu Yang 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
};

using ProgDescMap =
    std::unordered_map<ProgramDesc *, std::unique_ptr<ProgramDescBind>>;
static ProgDescMap *g_bind_map = nullptr;

class ProgramDescBind {
public:
  static ProgramDescBind &Instance(ProgramDesc *prog) {
    if (g_bind_map == nullptr) {
      g_bind_map = new ProgDescMap();
    }
    auto &map = *g_bind_map;
    auto &ptr = map[prog];

    if (ptr == nullptr) {
      ptr.reset(new ProgramDescBind(prog));
    }
    return *ptr;
  }
Y
Fix bug  
Yu Yang 已提交
214 215
  ProgramDescBind(const ProgramDescBind &o) = delete;
  ProgramDescBind &operator=(const ProgramDescBind &o) = delete;
Y
Yu Yang 已提交
216

Y
Yu Yang 已提交
217
  BlockDescBind *AppendBlock(const BlockDescBind &parent) {
Y
Yu Yang 已提交
218
    auto *b = prog_->add_blocks();
Y
Yu Yang 已提交
219
    b->set_parent_idx(parent.id());
Y
Yu Yang 已提交
220
    b->set_idx(prog_->blocks_size() - 1);
Y
Fix bug  
Yu Yang 已提交
221 222
    blocks_.emplace_back(new BlockDescBind(this, b));
    return blocks_.back().get();
Y
Yu Yang 已提交
223 224
  }

Y
Fix bug  
Yu Yang 已提交
225
  BlockDescBind *Block(size_t idx) { return blocks_[idx].get(); }
Y
Yu Yang 已提交
226 227 228 229 230 231 232

  std::string DebugString() { return Proto()->DebugString(); }

  size_t Size() const { return blocks_.size(); }

  ProgramDesc *Proto() {
    for (auto &block : blocks_) {
Y
Fix bug  
Yu Yang 已提交
233
      block->Sync();
Y
Yu Yang 已提交
234 235 236 237 238 239 240
    }
    return prog_;
  }

private:
  explicit ProgramDescBind(ProgramDesc *prog) : prog_(prog) {
    for (auto &block : *prog->mutable_blocks()) {
Y
Fix bug  
Yu Yang 已提交
241
      blocks_.emplace_back(new BlockDescBind(this, &block));
Y
Yu Yang 已提交
242 243 244 245 246 247
    }
  }

  // Not owned
  ProgramDesc *prog_;

Y
Fix bug  
Yu Yang 已提交
248
  std::vector<std::unique_ptr<BlockDescBind>> blocks_;
Y
Yu Yang 已提交
249 250
};

Y
Fix bug  
Yu Yang 已提交
251 252 253 254 255 256 257
BlockDescBind *BlockDescBind::ParentBlock() const {
  if (this->desc_->parent_idx() == -1) {
    return nullptr;
  }
  return prog_->Block(static_cast<size_t>(this->desc_->parent_idx()));
}

F
fengjiayi 已提交
258
void BindProgramDesc(py::module &m) {
Y
Yu Yang 已提交
259
  py::class_<ProgramDescBind>(m, "ProgramDesc", "")
260
      .def_static("instance",
Y
Yu Yang 已提交
261 262 263
                  []() -> ProgramDescBind * {
                    return &ProgramDescBind::Instance(&GetProgramDesc());
                  },
264 265
                  py::return_value_policy::reference)
      .def_static("__create_program_desc__",
Y
Yu Yang 已提交
266
                  []() -> ProgramDescBind * {
267 268 269 270 271
                    // Only used for unit-test
                    auto *prog_desc = new ProgramDesc;
                    auto *block = prog_desc->mutable_blocks()->Add();
                    block->set_idx(0);
                    block->set_parent_idx(-1);
Y
Yu Yang 已提交
272 273 274
                    return &ProgramDescBind::Instance(prog_desc);
                  },
                  py::return_value_policy::reference)
275
      .def("append_block",
Y
Yu Yang 已提交
276
           &ProgramDescBind::AppendBlock,
277
           py::return_value_policy::reference)
Y
Yu Yang 已提交
278 279 280
      .def("block", &ProgramDescBind::Block, py::return_value_policy::reference)
      .def("__str__", &ProgramDescBind::DebugString)
      .def("num_blocks", &ProgramDescBind::Size);
281 282
}

F
fengjiayi 已提交
283
void BindBlockDesc(py::module &m) {
Y
Yu Yang 已提交
284 285 286
  py::class_<BlockDescBind>(m, "BlockDesc", "")
      .def_property_readonly("id", &BlockDescBind::id)
      .def_property_readonly("parent", &BlockDescBind::Parent)
287
      .def("append_op",
Y
Yu Yang 已提交
288
           &BlockDescBind::AppendOp,
289 290 291 292 293 294
           py::return_value_policy::reference)
      .def("new_var",
           [](BlockDesc &self) { return self.add_vars(); },
           py::return_value_policy::reference);
}

F
fengjiayi 已提交
295
void BindVarDsec(py::module &m) {
Y
Yu Yang 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  py::class_<VarDesc>(m, "VarDesc", "");
  //  using namespace paddle::framework;  // NOLINT
  //  py::class_<VarDesc>(m, "VarDesc", "")
  //      .def(py::init<>())
  //      .def("set_name",
  //           [](VarDesc &self, const std::string &name) { self.set_name(name);
  //           })
  //      .def("set_shape",
  //           [](VarDesc &self, const std::vector<int64_t> &dims) {
  //             VectorToRepeated(dims,
  //             self.mutable_lod_tensor()->mutable_dims());
  //           })
  //      .def("set_data_type",
  //           [](VarDesc &self, int type_id) {
  //             LoDTensorDesc *lod_tensor_desc = self.mutable_lod_tensor();
  //             lod_tensor_desc->set_data_type(static_cast<DataType>(type_id));
  //           })
  //      .def("shape", [](VarDesc &self) {
  //        const LoDTensorDesc &lod_tensor_desc = self.lod_tensor();
  //        return RepeatedToVector(lod_tensor_desc.dims());
  //      });
317 318
}

F
fengjiayi 已提交
319
void BindOpDesc(py::module &m) {
Y
Yu Yang 已提交
320 321 322 323 324 325 326 327 328 329 330
  py::class_<OpDescBind>(m, "OpDesc", "")
      .def("type", &OpDescBind::Type)
      .def("set_type", &OpDescBind::SetType)
      .def("input", &OpDescBind::Input)
      .def("input_names", &OpDescBind::InputNames)
      .def("set_input", &OpDescBind::SetInput)
      .def("output", &OpDescBind::Output)
      .def("output_names", &OpDescBind::OutputNames)
      .def("set_output", &OpDescBind::SetOutput)
      .def("__str__", &OpDescBind::DebugString)
      .def("__repr__", &OpDescBind::DebugString);
331
}
332
}  // namespace pybind
333
}  // namespace paddle