process_group_bkcl.cc 30.4 KB
Newer Older
J
james 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

W
Wen Sun 已提交
15
#include "paddle/fluid/distributed/collective/process_group_bkcl.h"
J
james 已提交
16

W
Wen Sun 已提交
17
#include "paddle/fluid/distributed/collective/bkcl_tools.h"
W
Wen Sun 已提交
18
#include "paddle/fluid/distributed/collective/common.h"
19
#include "paddle/fluid/distributed/collective/utils.h"
J
james 已提交
20 21
#include "paddle/fluid/platform/device/xpu/bkcl_helper.h"
#include "paddle/fluid/platform/device/xpu/xpu_info.h"
H
Huang Jiyi 已提交
22
#include "paddle/phi/api/lib/utils/allocator.h"
23
#include "paddle/phi/core/device_context.h"
24
#include "paddle/phi/core/distributed/check/static_check.h"
25
#include "paddle/phi/core/enforce.h"
26
#include "paddle/phi/core/errors.h"
J
james 已提交
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 54 55 56 57 58 59 60 61 62

namespace paddle {
namespace distributed {
using XPUDeviceContext = paddle::platform::XPUDeviceContext;

ProcessGroupBKCL::BKCLTask::BKCLTask(const Place& place,
                                     int rank,
                                     CommType comm_type,
                                     bool sync_op,
                                     bool use_calc_stream)
    : TaskStream(rank, comm_type, sync_op, use_calc_stream), place_(place) {
  comm_event_ = std::make_shared<XPUEventManager>();
}

ProcessGroupBKCL::BKCLTask::~BKCLTask() {}

bool ProcessGroupBKCL::BKCLTask::IsCompleted() {
  LOG_FIRST_N(WARNING, 1) << "XPU do not support event query now.";
  return true;
}

// TODO(sheniang03): Add timeout for wait, now timeout unused
bool ProcessGroupBKCL::BKCLTask::Wait(std::chrono::milliseconds timeout) {
  // Warning here when use calc stream but also invoke waiting explicitly.
  if (UseCalcStream()) {
    VLOG(3) << "Warning: The communication is on calc stream, wait here is "
               "useless.";
    return true;
  }

  const auto* calc_ctx = static_cast<XPUContext*>(
      platform::DeviceContextPool::Instance().Get(place_));
  comm_event_->Block(*calc_ctx);

  if (barrier_) {
    // If we use the work to do barrier, we should block cpu
63 64 65 66 67

    // TODO(zhangxiaoci) There is no such function that can sync entire device
    // for xpu (for now), so all we can do is sync whatever stream that we know
    // and hope for the best. Note that for correctness the communication stream
    // needs to be in sync mode.
J
james 已提交
68 69
    platform::XPUDeviceGuard guard(place_.GetDeviceId());
    xpu_wait();
70
    calc_ctx->Wait();
J
james 已提交
71 72 73 74 75 76 77
  }
  return true;
}

// Same as Wait
void ProcessGroupBKCL::BKCLTask::Synchronize() { Wait(kWaitTimeout); }

78 79 80 81 82
ProcessGroupBKCL::ProcessGroupBKCL(
    const std::shared_ptr<phi::distributed::Store>& store,
    int rank,
    int size,
    int gid)
83
    : ProcessGroupWithStream(rank, size, gid), store_(store) {}
J
james 已提交
84 85

void ProcessGroupBKCL::GroupStart() {
86
  VLOG(3) << "bkcl_group_start";
J
james 已提交
87 88 89 90
  PADDLE_ENFORCE_XPU_SUCCESS(bkcl_group_start());
}

void ProcessGroupBKCL::GroupEnd() {
91
  VLOG(3) << "bkcl_group_end";
J
james 已提交
92 93 94
  PADDLE_ENFORCE_XPU_SUCCESS(bkcl_group_end());
}

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Recv(
    phi::DenseTensor* tensor,
    int src_rank,
    int64_t offset,
    int64_t numel,
    bool sync_op,
    bool use_calc_stream) {
  // numel > 0 indicates the tensor need to be sliced
  phi::DenseTensor partial_tensor;
  if (numel > 0) {
    partial_tensor = GetPartialTensor(*tensor, offset, numel);
    tensor = &partial_tensor;
  }

  return Collective(
      tensor,
      // have to pass a tensor here
      // TODO(zhangxiaoci) catch up with nccl's api
      *tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
118 119 120 121 122 123 124
        VLOG(3) << "calling bkcl_recv"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", src_rank: " << src_rank << ", numel: " << output->numel()
                << ", dtype: " << output->type() << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
125 126 127 128 129 130 131 132
        int r = bkcl_recv(comm,
                          output->data(),
                          output->numel(),
                          src_rank,
                          platform::ToBKCLDataType(
                              framework::TransToProtoVarType(output->type())),
                          stream);
        return r;
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
      },
      CommType::RECV,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Send(
    const phi::DenseTensor& tensor,
    int dst_rank,
    int64_t offset,
    int64_t numel,
    bool sync_op,
    bool use_calc_stream) {
  // numel > 0 indicates the tensor need to be sliced
  const phi::DenseTensor& tensor_maybe_partial =
      numel > 0 ? GetPartialTensor(tensor, offset, numel) : tensor;

  return Collective(
      nullptr,
      tensor_maybe_partial,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
157 158 159 160 161 162 163 164
        VLOG(3) << "calling bkcl_send"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", dst_rank: " << dst_rank
                << ", input numel: " << input.numel()
                << ", dtype: " << input.type() << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
165 166 167 168 169 170 171 172
        int r = bkcl_send(comm,
                          input.data(),
                          input.numel(),
                          dst_rank,
                          platform::ToBKCLDataType(
                              framework::TransToProtoVarType(input.type())),
                          stream);
        return r;
173 174 175 176 177 178
      },
      CommType::SEND,
      sync_op,
      use_calc_stream);
}

J
james 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
std::shared_ptr<ProcessGroupBKCL::BKCLTask> ProcessGroupBKCL::CreateTask(
    const Place& place,
    int rank,
    CommType comm_type,
    bool is_sync,
    bool use_calc_stream) {
  return std::make_shared<ProcessGroupBKCL::BKCLTask>(
      place, rank, comm_type, is_sync, use_calc_stream);
}

void ProcessGroupBKCL::BroadcastUniqueBKCLID(BKCLUniqueId* bkcl_id) {
  auto key = "ProcessGroupBKCL/bkcl_ids/" + std::to_string(gid_) + "/0";
  if (rank_ == 0) {
    auto id = std::vector<uint8_t>(
        reinterpret_cast<uint8_t*>(bkcl_id),
        reinterpret_cast<uint8_t*>(bkcl_id) + BKCL_UNIQUE_ID_BYTES);
    store_->set(key, id);
  } else {
    const auto& ret = store_->get(key);
    std::memcpy(bkcl_id, ret.data(), ret.size());
  }
}

void ProcessGroupBKCL::CreateBKCLEnvCache(const Place& place,
                                          const std::string& place_key) {
204
  platform::XPUDeviceGuard guard(place.GetDeviceId());
J
james 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  BKCLUniqueId bkcl_id;
  if (rank_ == 0) {
    PADDLE_ENFORCE_XPU_SUCCESS(bkcl_get_unique_id(&bkcl_id));
  }
  BroadcastUniqueBKCLID(&bkcl_id);

  VLOG(3) << "init bkcl rank: " << rank_ << ", nranks: " << size_
          << ", place: " << place_key
          << ", bkcl uniqueid: " << SerializeBKCLUniqueId(bkcl_id);

  calc_event_ = std::make_shared<XPUEventManager>();
  auto* calc_ctx = static_cast<phi::XPUContext*>(
      platform::DeviceContextPool::Instance().Get(place));
  // must use XPUDeviceContext here to make sure XPUContext::Init() is called
  auto comm_ctx = std::make_unique<XPUDeviceContext>(place);
R
Roc 已提交
220 221 222 223 224
  // set allocator
  comm_ctx->SetAllocator(memory::allocation::AllocatorFacade::Instance()
                             .GetAllocator(place)
                             .get());

J
james 已提交
225 226 227
  BKCLContext_t bkcl_comm;
  BKCLCHECK(bkcl_init_rank(&bkcl_comm, GetRank(), GetSize(), &bkcl_id));
  comm_ctx->SetBkclContext(bkcl_comm);
228 229
  // comm context creates a separate XPU stream for communication
  comm_ctx->CreateStream();
J
james 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

  place_to_calc_ctx_[place_key] = calc_ctx;
  place_to_comm_ctx_[place_key] = std::move(comm_ctx);
}

void ProcessGroupBKCL::SyncCalcStream(const Place& place) {
  const std::string& key = GetKeyFromPlace(place);
  const auto* calc_ctx = place_to_calc_ctx_[key];
  const auto* comm_ctx = place_to_comm_ctx_[key].get();
  calc_event_->Record(*calc_ctx);
  calc_event_->Block(*comm_ctx);
}

template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Collective(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    Fn fn,
    CommType op_type,
    bool sync_op,
    bool use_calc_stream) {
  const auto& place = in_tensor.place();
  const auto& key = GetKeyFromPlace(place);

J
james 已提交
254 255
  if (!calc_event_ ||
      (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end())) {
J
james 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    CreateBKCLEnvCache(place, key);
  }

  if (!use_calc_stream) {
    SyncCalcStream(place);
  }

  auto task = CreateTask(place, rank_, op_type, sync_op, use_calc_stream);

  const auto* calc_ctx = place_to_calc_ctx_[key];
  const auto& comm_ctx = place_to_comm_ctx_[key];
  auto bkcl_stream = use_calc_stream ? calc_ctx->stream() : comm_ctx->stream();
  fn(out_tensor, in_tensor, comm_ctx->bkcl_context(), bkcl_stream);

  if (!use_calc_stream) {
J
james 已提交
271 272
    PADDLE_ENFORCE_NOT_NULL(
        comm_ctx.get(), platform::errors::Fatal("comm context is nullptr."));
J
james 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    task->comm_event_->Record(*comm_ctx.get());
  }

  return task;
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllReduce(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    const AllreduceOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
292 293 294 295 296 297 298 299
        VLOG(3) << "calling bkcl_all_reduce"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << input.numel() << ", dtype: " << input.type()
                << ", reduce_type: " << ToBKCLRedType(opts.reduce_op)
                << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
300 301 302 303 304 305 306 307 308 309
        int r =
            bkcl_all_reduce(comm,
                            input.data(),
                            output->data(),
                            input.numel(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            ToBKCLRedType(opts.reduce_op),
                            stream);
        return r;
J
james 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
      },
      CommType::ALLREDUCE,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Broadcast(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    const BroadcastOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
        int root = opts.source_rank + opts.source_root;
330 331 332 333 334 335 336
        VLOG(3) << "calling bkcl_broadcast"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", root: " << root << ", numel: " << input.numel()
                << ", dtype: " << input.type() << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        if (framework::TransToProtoVarType(input.dtype()) ==
            framework::proto::VarType::INT64) {
          // special for int64_t, send as int32_t with DOUBLE NUMEL
          int r = bkcl_broadcast(
              comm,
              input.data(),
              output->data(),
              input.numel() * 2,
              platform::ToBKCLDataType(framework::proto::VarType::INT32),
              root,
              stream);
          return r;
        } else {
          int r =
              bkcl_broadcast(comm,
                             input.data(),
                             output->data(),
                             input.numel(),
                             platform::ToBKCLDataType(
                                 framework::TransToProtoVarType(input.type())),
                             root,
                             stream);
          return r;
        }
J
james 已提交
361 362 363 364 365 366 367 368 369
      },
      CommType::BROADCAST,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllGather(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
370 371
    int64_t offset,
    int64_t numel,
J
james 已提交
372 373
    bool sync_op,
    bool use_calc_stream) {
374 375 376 377 378 379 380 381
  const phi::DenseTensor& in_tensor_maybe_partial =
      numel > 0 ? GetPartialTensor(in_tensor, offset, numel) : in_tensor;
  phi::distributed::CommStaticCheck::GatherLikeShape(*out_tensor,
                                                     in_tensor_maybe_partial,
                                                     /*dst_rank*/ rank_,
                                                     /*cur_rank*/ rank_,
                                                     size_,
                                                     phi::AllocationType::XPU);
J
james 已提交
382 383 384 385 386 387 388
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
389 390 391 392 393 394 395
        VLOG(3) << "calling bkcl_all_gather"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << in_tensor_maybe_partial.numel()
                << ", dtype: " << input.type() << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
396 397 398 399 400 401 402 403 404
        int r =
            bkcl_all_gather(comm,
                            in_tensor_maybe_partial.data(),
                            in_tensor_maybe_partial.numel(),
                            output->data(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            stream);
        return r;
J
james 已提交
405 406 407 408 409 410
      },
      CommType::ALLGATHER,
      sync_op,
      use_calc_stream);
}

J
james 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Reduce(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    const ReduceOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
424 425 426 427 428 429 430 431 432
        VLOG(3) << "calling bkcl_reduce"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", root: " << opts.root_rank << ", numel: " << input.numel()
                << ", dtype: " << input.type()
                << ", reduce_type: " << ToBKCLRedType(opts.reduce_op)
                << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
433 434 435 436 437 438 439 440 441 442
        int r = bkcl_reduce(comm,
                            input.data(),
                            output->data(),
                            input.numel(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            ToBKCLRedType(opts.reduce_op),
                            opts.root_rank,
                            stream);
        return r;
J
james 已提交
443
      },
444
      CommType::REDUCE,
J
james 已提交
445 446 447 448
      sync_op,
      use_calc_stream);
}

449 450 451 452 453 454 455 456 457 458 459 460 461
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::ReduceScatter(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    const ReduceScatterOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
462 463 464 465 466 467 468 469
        VLOG(3) << "calling bkcl_reduce_scatter"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << output->numel() << ", dtype: " << input.type()
                << ", reduce_type: " << ToBKCLRedType(opts.reduce_op)
                << ", sync_op: " << sync_op
                << ", use_calc_stream: " << use_calc_stream;
470
        int r = bkcl_reduce_scatter(
471 472 473 474 475 476 477 478
            comm,
            input.data(),
            output->data(),
            output->numel(),
            platform::ToBKCLDataType(
                framework::TransToProtoVarType(input.type())),
            ToBKCLRedType(opts.reduce_op),
            stream);
479
        return r;
480 481 482 483 484 485
      },
      CommType::REDUCE_SCATTER,
      sync_op,
      use_calc_stream);
}

J
james 已提交
486 487
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Barrier(
    const BarrierOptions& opts) {
488 489 490 491 492
  PADDLE_ENFORCE_GE(opts.device_id,
                    0,
                    platform::errors::PreconditionNotMet(
                        "The barrier device id must greater or equal than 0."));
  platform::XPUPlace place(opts.device_id);
J
james 已提交
493
  auto allocator = std::unique_ptr<phi::Allocator>(
494
      new paddle::experimental::DefaultAllocator(place));
J
james 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507
  phi::DenseTensorMeta meta(phi::DataType::FLOAT32, phi::DDim{1});
  phi::DenseTensor barrier_tensor{allocator.get(), meta};

  auto task = AllReduce(&barrier_tensor,
                        barrier_tensor,
                        {},
                        /*sync_op*/ true,
                        /*use_calc_stream*/ false);
  auto bkcl_task = dynamic_cast<BKCLTask*>(task.get());
  bkcl_task->barrier_ = true;
  return task;
}

508
phi::DeviceContext* ProcessGroupBKCL::GetDeviceContext(
J
james 已提交
509 510 511 512
    const Place& place) const {
  return GetDeviceContext(place, /*use_calc_stream*/ false);
}

513
phi::DeviceContext* ProcessGroupBKCL::GetDeviceContext(
J
james 已提交
514 515 516 517
    const Place& place, bool use_calc_stream) const {
  const std::string& key = GetKeyFromPlace(place);
  if (use_calc_stream) {
    const auto& iter = place_to_calc_ctx_.find(key);
R
Roc 已提交
518
    return iter->second;
J
james 已提交
519 520 521 522 523 524
  } else {
    const auto& iter = place_to_comm_ctx_.find(key);
    PADDLE_ENFORCE_NE(iter,
                      place_to_comm_ctx_.end(),
                      platform::errors::InvalidArgument(
                          "Cannot find device context in process group."));
R
Roc 已提交
525
    return iter->second.get();
J
james 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  }
}

// below are old apis
std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllReduce(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const AllreduceOptions& opts) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
J
james 已提交
544 545 546 547
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in XPUPlace."));
J
james 已提交
548 549 550 551 552 553 554
  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
555 556 557 558 559 560 561
        VLOG(3) << "calling bkcl_all_reduce"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << input.numel() << ", dtype: " << input.type()
                << ", reduce_type: " << ToBKCLRedType(opts.reduce_op)
                << ", sync_op: " << true << ", use_calc_stream: " << false;
562 563 564 565 566 567 568 569 570 571
        int r =
            bkcl_all_reduce(comm,
                            input.data(),
                            output->data(),
                            input.numel(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            ToBKCLRedType(opts.reduce_op),
                            stream);
        return r;
J
james 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      },
      CommType::ALLREDUCE,
      /*sync_op*/ true,
      /*use_calc_stream*/ false);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllReduce(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const AllreduceOptions& opts,
    bool sync_op) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
J
james 已提交
593 594 595 596
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in XPUPlace."));
J
james 已提交
597 598 599 600 601 602 603
  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
604 605 606 607 608 609 610
        VLOG(3) << "calling bkcl_all_reduce"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << input.numel() << ", dtype: " << input.type()
                << ", reduce_type: " << ToBKCLRedType(opts.reduce_op)
                << ", sync_op: " << sync_op << ", use_calc_stream: " << false;
611 612 613 614 615 616 617 618 619 620
        int r =
            bkcl_all_reduce(comm,
                            input.data(),
                            output->data(),
                            input.numel(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            ToBKCLRedType(opts.reduce_op),
                            stream);
        return r;
J
james 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
      },
      CommType::ALLREDUCE,
      sync_op,
      /*use_calc_stream*/ false);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Broadcast(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const BroadcastOptions& opts) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
J
james 已提交
641 642 643 644
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in XPUPlace."));
J
james 已提交
645 646 647 648 649 650 651 652 653 654

  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
        const auto root =
            opts.source_rank * in_tensors.size() + opts.source_root;
655 656 657 658 659 660 661
        VLOG(3) << "calling bkcl_broadcast"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", root: " << root << ", numel: " << input.numel()
                << ", dtype: " << input.type() << ", sync_op: " << true
                << ", use_calc_stream: " << false;
662 663 664 665 666 667 668 669 670 671
        int r =
            bkcl_broadcast(comm,
                           input.data(),
                           output->data(),
                           input.numel(),
                           platform::ToBKCLDataType(
                               framework::TransToProtoVarType(input.type())),
                           root,
                           stream);
        return r;
J
james 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      },
      CommType::BROADCAST,
      /*sync_op*/ true,
      /*use_calc_stream*/ false);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::Broadcast(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const BroadcastOptions& opts,
    bool sync_op) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
J
james 已提交
693 694 695 696
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in XPUPlace."));
J
james 已提交
697 698 699 700 701 702 703 704 705 706

  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
        const auto root =
            opts.source_rank * in_tensors.size() + opts.source_root;
707 708 709 710 711 712 713
        VLOG(3) << "calling bkcl_broadcast"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", root: " << root << ", numel: " << input.numel()
                << ", dtype: " << input.type() << ", sync_op: " << sync_op
                << ", use_calc_stream: " << false;
714 715 716 717 718 719 720 721 722 723
        int r =
            bkcl_broadcast(comm,
                           input.data(),
                           output->data(),
                           input.numel(),
                           platform::ToBKCLDataType(
                               framework::TransToProtoVarType(input.type())),
                           root,
                           stream);
        return r;
J
james 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
      },
      CommType::BROADCAST,
      sync_op,
      /*use_calc_stream*/ false);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllGather(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
J
james 已提交
743 744 745 746
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in XPUPlace."));
J
james 已提交
747 748 749 750 751 752 753 754 755 756 757
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All outputs should be in XPUPlace."));
  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
758 759 760 761 762 763
        VLOG(3) << "calling bkcl_all_gather"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << input.numel() << ", dtype: " << input.type()
                << ", sync_op: " << true << ", use_calc_stream: " << false;
764 765 766 767 768 769 770 771 772
        int r =
            bkcl_all_gather(comm,
                            input.data(),
                            input.numel(),
                            output->data(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            stream);
        return r;
J
james 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
      },
      CommType::ALLGATHER,
      /*sync_op*/ true,
      /*use_calc_stream*/ false);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupBKCL::AllGather(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    bool sync_op) {
  PADDLE_ENFORCE_EQ(
      in_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      out_tensors.size(),
      1,
      platform::errors::InvalidArgument(
          "BKCL only support single tensor collective communication."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInXPUPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All outputs should be in XPUPlace."));
  return Collective(
      &out_tensors[0],
      in_tensors[0],
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          BKCLContext_t comm,
          const XPUStream& stream) {
804 805 806 807 808 809
        VLOG(3) << "calling bkcl_all_gather"
                << ", rank_id: " << platform::GetBKCLRankID(comm)
                << ", dev_id: " << platform::GetBKCLDevID(comm)
                << ", nranks: " << platform::GetBKCLNRanks(comm)
                << ", numel: " << input.numel() << ", dtype: " << input.type()
                << ", sync_op: " << sync_op << ", use_calc_stream: " << false;
810 811 812 813 814 815 816 817 818
        int r =
            bkcl_all_gather(comm,
                            input.data(),
                            input.numel(),
                            output->data(),
                            platform::ToBKCLDataType(
                                framework::TransToProtoVarType(input.type())),
                            stream);
        return r;
J
james 已提交
819 820 821 822 823 824
      },
      CommType::ALLGATHER,
      sync_op,
      /*use_calc_stream*/ false);
}

L
LiYuRio 已提交
825
std::shared_ptr<ProcessGroupBKCL> ProcessGroupBKCL::CreateProcessGroupBKCL(
826 827 828 829
    const std::shared_ptr<phi::distributed::Store>& store,
    int rank,
    int size,
    int gid) {
L
LiYuRio 已提交
830 831 832 833 834 835
  auto process_group =
      std::make_shared<ProcessGroupBKCL>(store, rank, size, gid);
  ProcessGroupIdMap::GetInstance().emplace(gid, process_group);
  return process_group;
}

J
james 已提交
836 837
}  //  namespace distributed
}  //  namespace paddle