distributed_py.cc 10.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* Copyright (c) 2022 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 <fcntl.h>
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif

#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif

#include "paddle/fluid/distributed/collective/ProcessGroup.h"
#include "paddle/fluid/distributed/collective/Types.h"
26
#include "paddle/fluid/distributed/collective/reducer.h"
27 28 29 30 31 32 33 34 35 36 37
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/pybind/distributed_py.h"
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/phi/api/all.h"

#if defined(PADDLE_WITH_NCCL)
#include "paddle/fluid/distributed/collective/ProcessGroupNCCL.h"
#endif

38 39 40 41 42
#if defined(PADDLE_WITH_GLOO)
#include "paddle/fluid/distributed/collective/ProcessGroupGloo.h"
#include "paddle/fluid/distributed/store/tcp_store.h"
#endif

43 44 45 46 47 48 49
namespace py = pybind11;

namespace paddle {
namespace pybind {

using Tensor = paddle::experimental::Tensor;

50 51 52 53 54 55 56 57
#if defined(PADDLE_WITH_GLOO)
using ProcessGroupGloo = paddle::distributed::ProcessGroupGloo;
using GlooStore = paddle::distributed::ProcessGroupGloo::GlooStore;
using GlooOptions = paddle::distributed::ProcessGroupGloo::GlooOptions;
#endif

static std::string GLOO_SOCKET_IFNAME_ENV = "GLOO_SOCKET_IFNAME";  // NOLINT

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
void BindDistributed(py::module *m) {
  py::enum_<distributed::ReduceOp>(*m, "ReduceOp")
      .value("SUM", distributed::ReduceOp::SUM)
      .value("AVG", distributed::ReduceOp::AVG)
      .value("MAX", distributed::ReduceOp::MAX)
      .value("MIN", distributed::ReduceOp::MIN)
      .value("PRODUCT", distributed::ReduceOp::PRODUCT);

  py::class_<distributed::AllreduceOptions>(*m, "AllreduceOptions")
      .def(py::init<>())
      .def_readwrite("reduce_op", &distributed::AllreduceOptions::reduce_op);

  py::class_<distributed::BroadcastOptions>(*m, "BroadcastOptions")
      .def(py::init<>())
      .def_readwrite("source_rank", &distributed::BroadcastOptions::source_rank)
      .def_readwrite("source_root",
                     &distributed::BroadcastOptions::source_root);

B
Baibaifan 已提交
76 77 78 79
  py::class_<distributed::BarrierOptions>(*m, "BarrierOptions")
      .def(py::init<>())
      .def_readwrite("place_ids", &distributed::BarrierOptions::place_ids);

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
  auto ProcessGroup =
      py::class_<distributed::ProcessGroup,
                 std::shared_ptr<distributed::ProcessGroup>>(*m, "ProcessGroup")
          .def("rank", &distributed::ProcessGroup::GetRank)
          .def("size", &distributed::ProcessGroup::GetSize)
          .def("name", &distributed::ProcessGroup::GetBackendName)
          .def("allreduce",
               [](distributed::ProcessGroup &self, py::handle py_tensor,
                  distributed::ReduceOp op) {
                 auto tensor = CastPyArg2Tensor(py_tensor.ptr(), 0);
                 distributed::AllreduceOptions opts;
                 opts.reduce_op = op;
                 std::vector<Tensor> tensors = {tensor};
                 return self.AllReduce(tensors, opts);
               },
               py::arg("tensor"), py::arg("op") = distributed::ReduceOp::SUM,
               py::call_guard<py::gil_scoped_release>())

          .def("broadcast",
               [](distributed::ProcessGroup &self, py::handle py_tensor,
                  int source_rank) {
                 auto tensor = CastPyArg2Tensor(py_tensor.ptr(), 0);
                 distributed::BroadcastOptions opts;
                 opts.source_rank = source_rank;
                 std::vector<Tensor> tensors = {tensor};
                 return self.Broadcast(tensors, opts);
               },
               py::arg("tensor"), py::arg("source_rank"),
B
Baibaifan 已提交
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
               py::call_guard<py::gil_scoped_release>())

          .def("barrier",
               [](distributed::ProcessGroup &self, std::vector<int> place_ids) {
                 distributed::BarrierOptions opts;
                 opts.place_ids = place_ids;
                 return self.Barrier(opts);
               },
               py::arg("place_ids") = std::vector<int>{},
               py::call_guard<py::gil_scoped_release>())

          .def("send",
               [](distributed::ProcessGroup &self, py::handle py_tensor,
                  int dst) {
                 auto tensor = CastPyArg2Tensor(py_tensor.ptr(), 0);
                 std::vector<Tensor> tensors = {tensor};
                 return self.Send(tensors, dst);
               },
               py::arg("tensor"), py::arg("dst"),
               py::call_guard<py::gil_scoped_release>())

          .def("recv",
               [](distributed::ProcessGroup &self, py::handle py_tensor,
                  int src) {
                 auto tensor = CastPyArg2Tensor(py_tensor.ptr(), 0);
                 std::vector<Tensor> tensors = {tensor};
                 return self.Recv(tensors, src);
               },
               py::arg("tensor"), py::arg("src"),
137 138 139 140 141 142 143 144
               py::call_guard<py::gil_scoped_release>());

#if defined(PADDLE_WITH_NCCL)
  py::class_<distributed::ProcessGroupNCCL,
             std::shared_ptr<distributed::ProcessGroupNCCL>>(
      *m, "ProcessGroupNCCL", ProcessGroup)
      .def(py::init<const distributed::ProcessGroupStrategy &, int, int>(),
           py::call_guard<py::gil_scoped_release>());
145
#endif
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

  py::class_<distributed::ProcessGroup::Task,
             std::shared_ptr<distributed::ProcessGroup::Task>>(*m, "task")
      .def("is_completed", &distributed::ProcessGroup::Task::IsCompleted)
      .def("wait", &distributed::ProcessGroup::Task::Wait,
           py::arg("timeout") = kWaitTimeout,
           py::call_guard<py::gil_scoped_release>())
      .def("synchronize", &distributed::ProcessGroup::Task::Synchronize,
           py::call_guard<py::gil_scoped_release>());

  // define parallel strategy, it will be removed
  py::class_<distributed::ProcessGroupStrategy> pg_strategy(
      *m, "ProcessGroupStrategy", "");
  pg_strategy.def(py::init())
      .def_property("nranks",
                    [](const distributed::ProcessGroupStrategy &self) {
                      return self.nranks_;
                    },
                    [](distributed::ProcessGroupStrategy &self, int nranks) {
                      self.nranks_ = nranks;
                    })
      .def_property("local_rank",
                    [](const distributed::ProcessGroupStrategy &self) {
                      return self.local_rank_;
                    },
                    [](distributed::ProcessGroupStrategy &self,
                       int local_rank) { self.local_rank_ = local_rank; })
      .def_property(
          "trainer_endpoints",
          [](const distributed::ProcessGroupStrategy &self) {
            return self.trainer_endpoints_;
          },
          [](distributed::ProcessGroupStrategy &self,
             std::vector<std::string> eps) { self.trainer_endpoints_ = eps; })
      .def_property("current_endpoint",
                    [](const distributed::ProcessGroupStrategy &self) {
                      return self.current_endpoint_;
                    },
                    [](distributed::ProcessGroupStrategy &self,
                       const std::string &ep) { self.current_endpoint_ = ep; })
      .def_property("nrings",
                    [](const distributed::ProcessGroupStrategy &self) {
                      return self.nrings_;
                    },
                    [](distributed::ProcessGroupStrategy &self, int nrings) {
                      self.nrings_ = nrings;
                    });
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
#if defined(PADDLE_WITH_GLOO)
  py::class_<GlooOptions>(*m, "GlooOptions")
      .def(py::init<>())
      .def_readwrite("_device", &GlooOptions::device)
      .def_static("create", &GlooOptions::create);

  py::class_<GlooStore, std::shared_ptr<GlooStore>>(*m, "GlooStore")
      .def(py::init(
               [](const std::shared_ptr<paddle::distributed::TCPStore> &store) {
                 return std::make_shared<GlooStore>(store);
               }),
           py::call_guard<py::gil_scoped_release>());

  py::class_<ProcessGroupGloo, std::shared_ptr<ProcessGroupGloo>>(
      *m, "ProcessGroupGloo", ProcessGroup)
      .def(py::init<const std::shared_ptr<GlooStore> &, int, int,
                    std::shared_ptr<GlooOptions> &>(),
           py::call_guard<py::gil_scoped_release>())
      .def(py::init([](const std::shared_ptr<GlooStore> &store, int rank,
                       int world_size) {
             auto opts = GlooOptions::create();
             char *ifname = getenv(GLOO_SOCKET_IFNAME_ENV.c_str());
             if (ifname && strlen(ifname) > 1) {
               opts->device = ProcessGroupGloo::createDeviceForInterface(
                   std::string(ifname));
             } else {
               opts->device = ProcessGroupGloo::createDefaultDevice();
             }
             return std::make_shared<ProcessGroupGloo>(store, rank, world_size,
                                                       opts);
           }),
           py::arg("store"), py::arg("rank"),
           py::arg("world_size"),  // py::arg("timeout") =
                                   // kProcessGroupDefaultTimeout,
           py::call_guard<py::gil_scoped_release>())
      .def_static("create_default_device",
                  &ProcessGroupGloo::createDefaultDevice);
#endif

233 234 235 236 237 238 239 240 241 242 243 244
  m->def("eager_assign_group_by_size",
         [](py::handle py_tensors, std::vector<bool> is_sparse_gradient,
            std::vector<size_t> group_size_limits,
            std::vector<int64_t> tensor_indices) {
           auto tensors = CastPyArg2VectorOfTensor(py_tensors.ptr(), 0);
           return distributed::Eager_AssignGroupBySize(
               tensors, is_sparse_gradient, group_size_limits, tensor_indices);
         },
         py::arg("tensors"), py::arg("is_sparse_gradient"),
         py::arg("group_size_limits") = std::vector<size_t>{25 * 1024 * 1024},
         py::arg("tensor_indices") = std::vector<int64_t>{},
         py::call_guard<py::gil_scoped_release>());
245 246 247 248
}

}  // end namespace pybind
}  // namespace paddle