bind_fleet_executor.cc 10.9 KB
Newer Older
L
LiYuRio 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// 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/fluid/pybind/bind_fleet_executor.h"
16
#include <pybind11/numpy.h>
L
LiYuRio 已提交
17
#include <pybind11/stl.h>
18 19
#include <string>
#include <vector>
20
#include "paddle/fluid/distributed/fleet_executor/dist_model.h"
21
#include "paddle/fluid/distributed/fleet_executor/dist_model_tensor_wrapper.h"
L
LiYuRio 已提交
22
#include "paddle/fluid/distributed/fleet_executor/fleet_executor.h"
L
LiYuRio 已提交
23
#include "paddle/fluid/distributed/fleet_executor/task_node.h"
24
#include "paddle/fluid/framework/operator.h"
L
LiYuRio 已提交
25
#include "paddle/fluid/framework/program_desc.h"
26
#include "paddle/fluid/framework/scope.h"
27
#include "paddle/fluid/platform/float16.h"
28
#include "paddle/fluid/platform/place.h"
29
#include "pybind11/pybind11.h"
L
LiYuRio 已提交
30 31 32

namespace py = pybind11;

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
namespace pybind11 {
namespace detail {

// Note: use same enum number of float16 in numpy.
// import numpy as np
// print np.dtype(np.float16).num  # 23
constexpr int NPY_FLOAT16_ = 23;

// Note: Since float16 is not a builtin type in C++, we register
// paddle::platform::float16 as numpy.float16.
// Ref: https://github.com/pybind/pybind11/issues/1776
template <>
struct npy_format_descriptor<paddle::platform::float16> {
  static py::dtype dtype() {
    handle ptr = npy_api::get().PyArray_DescrFromType_(NPY_FLOAT16_);
    return reinterpret_borrow<py::dtype>(ptr);
  }
  static std::string format() {
    // Note: "e" represents float16.
    // Details at:
    // https://docs.python.org/3/library/struct.html#format-characters.
    return "e";
  }
  static constexpr auto name = _("float16");
};

}  // namespace detail
}  // namespace pybind11

L
LiYuRio 已提交
62 63 64 65
namespace paddle {
namespace pybind {

using paddle::distributed::FleetExecutor;
L
LiYuRio 已提交
66
using paddle::distributed::TaskNode;
67 68
using paddle::distributed::DistModelConfig;
using paddle::distributed::DistModel;
69 70 71
using paddle::distributed::DistModelDataBuf;
using paddle::distributed::DistModelTensor;
using paddle::distributed::DistModelDataType;
72
using paddle::framework::OpDesc;
73
using paddle::framework::ProgramDesc;
L
LiYuRio 已提交
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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
template <typename T>
DistModelDataBuf DistModelDataBufCreate(
    py::array_t<T, py::array::c_style | py::array::forcecast> data) {
  // accept numpy array directly
  DistModelDataBuf buf(data.size() * sizeof(T));
  std::copy_n(static_cast<const T*>(data.data()), data.size(),
              static_cast<T*>(buf.data()));
  return buf;
}

template <typename T>
void DistModelDataBufReset(
    DistModelDataBuf& buf,                                             // NOLINT
    py::array_t<T, py::array::c_style | py::array::forcecast> data) {  // NOLINT
  // reset the data with numpy array directly
  buf.Resize(data.size() * sizeof(T));
  std::copy_n(static_cast<const T*>(data.data()), data.size(),
              static_cast<T*>(buf.data()));
}

template <typename T>
DistModelTensor DistModelTensorCreate(
    py::array_t<T, py::array::c_style | py::array::forcecast> data,
    const std::string name, const std::vector<std::vector<size_t>>& lod,
    bool copy) {
  DistModelTensor tensor;

  if (copy) {
    DistModelDataBuf buf(data.size() * sizeof(T));
    std::copy_n(static_cast<const T*>(data.data()), data.size(),
                static_cast<T*>(buf.data()));
    tensor.data = std::move(buf);
  } else {
    tensor.data =
        DistModelDataBuf(data.mutable_data(), data.size() * sizeof(T));
  }

  tensor.dtype = paddle::distributed::DistModelGetDtype<T>();
  tensor.name = name;
  tensor.lod = lod;
  tensor.shape.resize(data.ndim());
  std::copy_n(data.shape(), data.ndim(), tensor.shape.begin());

  return tensor;
}

py::dtype DistModelTypeToNumpyDType(DistModelDataType dtype) {
  py::dtype dt;
  switch (dtype) {
    case DistModelDataType::INT32:
      dt = py::dtype::of<int32_t>();
      break;
    case DistModelDataType::INT64:
      dt = py::dtype::of<int64_t>();
      break;
    case DistModelDataType::FLOAT32:
      dt = py::dtype::of<float>();
      break;
    case DistModelDataType::INT8:
      dt = py::dtype::of<int8_t>();
      break;
    case DistModelDataType::FLOAT16:
      dt = py::dtype::of<paddle::platform::float16>();
      break;
    default:
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported data type. Now only supports INT32, INT64, INT8, "
          "FLOAT16 and FLOAT32."));
  }

  return dt;
}

py::array DistModelTensorGetData(DistModelTensor& tensor) {  // NOLINT
  py::dtype dt = DistModelTypeToNumpyDType(tensor.dtype);
  return py::array(std::move(dt), {tensor.shape}, tensor.data.data());
}

L
LiYuRio 已提交
153 154 155 156
void BindFleetExecutor(py::module* m) {
  py::class_<FleetExecutor>(*m, "FleetExecutor")
      .def(py::init<const std::string&>())
      .def("init", &FleetExecutor::Init)
157 158
      .def("run", &FleetExecutor::Run,
           py::call_guard<py::gil_scoped_release>());
L
LiYuRio 已提交
159 160

  py::class_<TaskNode>(*m, "TaskNode")
161
      .def(py::init<framework::ProgramDesc*, int64_t, int64_t, int64_t>())
162 163
      .def(py::init<int32_t, const std::vector<framework::OpDesc*>&, int64_t,
                    int64_t, int64_t, int64_t>())
L
LiYuRio 已提交
164 165
      .def("task_id", &TaskNode::task_id)
      .def("add_upstream_task", &TaskNode::AddUpstreamTask)
166 167 168 169
      .def("add_downstream_task", &TaskNode::AddDownstreamTask)
      .def("set_run_pre_steps", &TaskNode::SetRunPerSteps)
      .def("set_run_at_offset", &TaskNode::SetRunAtOffset)
      .def("set_type", &TaskNode::SetType)
170
      .def("role", &TaskNode::role)
171
      .def("init", [](TaskNode& self) { self.Init(); })
172
      .def("set_program", &TaskNode::SetProgram);
173 174 175 176

  py::class_<DistModelConfig>(*m, "DistModelConfig")
      .def(py::init<>())
      .def_readwrite("model_dir", &DistModelConfig::model_dir)
177 178 179 180
      .def_readwrite("program_desc", &DistModelConfig::program_desc)
      .def_readwrite("scope", &DistModelConfig::scope)
      .def_readwrite("place", &DistModelConfig::place)
      .def_readwrite("device_id", &DistModelConfig::device_id)
181 182 183 184
      .def_readwrite("trainer_endpoints", &DistModelConfig::trainer_endpoints)
      .def_readwrite("current_endpoint", &DistModelConfig::current_endpoint)
      .def_readwrite("nranks", &DistModelConfig::nranks)
      .def_readwrite("local_rank", &DistModelConfig::local_rank)
185 186 187
      .def_readwrite("ring_id_to_ranks", &DistModelConfig::ring_id_to_ranks_)
      .def_readwrite("rank_to_ring_ids", &DistModelConfig::rank_to_ring_ids_)
      .def_readwrite("enable_timer", &DistModelConfig::enable_timer);
188 189 190 191

  py::class_<DistModel>(*m, "DistModel")
      .def(py::init<const DistModelConfig&>())
      .def("init", &DistModel::Init)
192 193 194 195 196 197
      .def("run",
           [](DistModel& self, const std::vector<DistModelTensor>& inputs) {
             std::vector<DistModelTensor> outputs;
             self.Run(inputs, &outputs);
             return outputs;
           });
198 199 200 201 202 203 204 205 206 207 208

  py::class_<DistModelDataBuf>(*m, "DistModelDataBuf")
      .def(py::init<size_t>())
      .def(py::init([](std::vector<float>& data) {
        auto buf = DistModelDataBuf(data.size() * sizeof(float));
        std::memcpy(buf.data(), static_cast<void*>(data.data()), buf.length());
        return buf;
      }))
      .def(py::init(&DistModelDataBufCreate<int32_t>))
      .def(py::init(&DistModelDataBufCreate<int64_t>))
      .def(py::init(&DistModelDataBufCreate<float>))
209
      .def(py::init(&DistModelDataBufCreate<paddle::platform::float16>))
210 211 212 213 214 215 216 217
      .def("reset",
           [](DistModelDataBuf& self, std::vector<float>& data) {
             self.Resize(data.size() * sizeof(float));
             std::memcpy(self.data(), data.data(), self.length());
           })
      .def("reset", &DistModelDataBufReset<int32_t>)
      .def("reset", &DistModelDataBufReset<int64_t>)
      .def("reset", &DistModelDataBufReset<float>)
218
      .def("reset", &DistModelDataBufReset<paddle::platform::float16>)
219
      .def("length", &DistModelDataBuf::length)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
      .def("tolist", [](DistModelDataBuf& self,
                        const std::string& dtype) -> py::list {
        py::list l;
        if (dtype == "int32") {
          auto* data = static_cast<int32_t*>(self.data());
          auto size = self.length() / sizeof(int32_t);
          l = py::cast(std::vector<int32_t>(data, data + size));
        } else if (dtype == "int64") {
          auto* data = static_cast<int64_t*>(self.data());
          auto size = self.length() / sizeof(int64_t);
          l = py::cast(std::vector<int64_t>(data, data + size));
        } else if (dtype == "float32") {
          auto* data = static_cast<float*>(self.data());
          auto size = self.length() / sizeof(float);
          l = py::cast(std::vector<float>(data, data + size));
        } else if (dtype == "float16") {
          auto* data = static_cast<paddle::platform::float16*>(self.data());
          auto size = self.length() / sizeof(paddle::platform::float16);
          l = py::cast(
              std::vector<paddle::platform::float16>(data, data + size));
        } else {
          PADDLE_THROW(platform::errors::Unimplemented(
              "Unsupported data type. Now only supports INT32, INT64, "
              "FLOAT16 and FLOAT32."));
        }
        return l;
      });
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

  py::class_<DistModelTensor>(*m, "DistModelTensor")
      .def(py::init<>())
      .def(py::init(&DistModelTensorCreate<int32_t>), py::arg("data"),
           py::arg("name") = "",
           py::arg("lod") = std::vector<std::vector<size_t>>(),
           py::arg("copy") = true)
      .def(py::init(&DistModelTensorCreate<int64_t>), py::arg("data"),
           py::arg("name") = "",
           py::arg("lod") = std::vector<std::vector<size_t>>(),
           py::arg("copy") = true)
      .def(py::init(&DistModelTensorCreate<float>), py::arg("data"),
           py::arg("name") = "",
           py::arg("lod") = std::vector<std::vector<size_t>>(),
           py::arg("copy") = true)
262 263 264 265
      .def(py::init(&DistModelTensorCreate<paddle::platform::float16>),
           py::arg("data"), py::arg("name") = "",
           py::arg("lod") = std::vector<std::vector<size_t>>(),
           py::arg("copy") = true)
266 267 268 269 270 271 272 273 274 275
      .def_readwrite("name", &DistModelTensor::name)
      .def_readwrite("shape", &DistModelTensor::shape)
      .def_readwrite("data", &DistModelTensor::data)
      .def_readwrite("dtype", &DistModelTensor::dtype)
      .def_readwrite("lod", &DistModelTensor::lod)
      .def("as_ndarray", &DistModelTensorGetData);

  py::enum_<DistModelDataType>(*m, "DistModelDataType")
      .value("FLOAT32", DistModelDataType::FLOAT32)
      .value("INT64", DistModelDataType::INT64)
276 277
      .value("INT32", DistModelDataType::INT32)
      .value("FLOAT16", DistModelDataType::FLOAT16);
L
LiYuRio 已提交
278 279 280
}
}  // namespace pybind
}  // namespace paddle