ProcessGroupNCCL.cc 54.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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 "paddle/fluid/distributed/collective/ProcessGroupNCCL.h"
16

L
lilong12 已提交
17
#include "paddle/fluid/distributed/collective/Common.h"
18
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
L
LiYuRio 已提交
19
#include "paddle/phi/api/lib/utils/allocator.h"
20 21 22 23 24 25 26 27 28

DECLARE_bool(nccl_blocking_wait);
DECLARE_bool(use_stream_safe_cuda_allocator);

constexpr int64_t kWaitBlockTImeout = 10;

namespace paddle {
namespace distributed {

29 30 31 32 33 34 35
ProcessGroupNCCL::NCCLTask::NCCLTask(const Place& place,
                                     int rank,
                                     CommType comm_type,
                                     bool sync_op,
                                     bool use_calc_stream)
    : TaskStream(rank, comm_type, sync_op, use_calc_stream),
      comm_event_(place),
W
Wen Sun 已提交
36
      task_place_(place) {}
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

ProcessGroupNCCL::NCCLTask::~NCCLTask() {}

bool ProcessGroupNCCL::NCCLTask::IsCompleted() { return comm_event_.Query(); }

void ProcessGroupNCCL::NCCLTask::UpdateWaitChain(
    const phi::DeviceContext& ctx) {
  comm_event_.Record(&ctx);
}

// TODO(sheniang03): Add timeout for wait, now timeout unused
bool ProcessGroupNCCL::NCCLTask::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;
  }

W
Wen Sun 已提交
56 57 58
  const auto* calc_ctx =
      platform::DeviceContextPool::Instance().Get(task_place_);
  comm_event_.Wait(platform::Place2DeviceType(task_place_), calc_ctx);
59 60 61 62 63 64

  if (FLAGS_nccl_blocking_wait) {
    // NOTE(shenliang03): It will block host for sync
    while (!IsCompleted()) {
      std::this_thread::sleep_for(std::chrono::milliseconds(kWaitBlockTImeout));
    }
65
  }
66

W
Wen Sun 已提交
67
  if (IsBlockCPUInWait()) {
68 69 70 71 72 73 74 75
    // If we use the work to do barrier, we should block cpu
#ifdef PADDLE_WITH_CUDA
    PADDLE_ENFORCE_GPU_SUCCESS(cudaDeviceSynchronize());
#else
    PADDLE_ENFORCE_GPU_SUCCESS(hipDeviceSynchronize());
#endif
  }
  return true;
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
// Same as Wait
void ProcessGroupNCCL::NCCLTask::Synchronize() { Wait(kWaitTimeout); }

ProcessGroupNCCL::ProcessGroupNCCL(const std::shared_ptr<Store>& store,
                                   int rank,
                                   int size,
                                   const platform::Place& place,
                                   int gid)
    : ProcessGroupStream(rank, size, place, gid), store_(store) {
  platform::SetDeviceId(place_.device);
}

void ProcessGroupNCCL::GroupStart() {
  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
}

void ProcessGroupNCCL::GroupEnd() {
  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
}

const phi::DeviceContext& ProcessGroupNCCL::GetDeviceContext(
    const Place& place) const {
  return GetDeviceContext(place, /*use_calc_stream*/ false);
}

const phi::DeviceContext& ProcessGroupNCCL::GetDeviceContext(
    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);
    return *iter->second;
  } else {
    const auto& iter = place_to_comm_ctx_.find(key);
    PADDLE_ENFORCE_NE(
        iter,
        place_to_comm_ctx_.end(),
        platform::errors::NotFound(
            "Cannot find the device context in this process group."));
    return *iter->second;
  }
}

ncclComm_t ProcessGroupNCCL::NCCLComm(const Place& place) const {
  const std::string& key = GetKeyFromPlace(place);
  const auto& iter = place_to_comm_ctx_.find(key);
  PADDLE_ENFORCE_NE(
      iter,
      place_to_comm_ctx_.end(),
      platform::errors::NotFound(
          "Cannot find the NCCL commmunicator in this process group."));
  return iter->second->nccl_comm();
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllGather(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      out_tensor,
      in_tensor,
      [&](phi::DenseTensor* output,
          const phi::DenseTensor& input,
          ncclComm_t comm,
142
          gpuStream_t stream) {
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        return platform::dynload::ncclAllGather(
            input.data(),
            output->data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            comm,
            stream);
      },
      CommType::ALLGATHER,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::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,
          ncclComm_t comm,
168
          gpuStream_t stream) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        return platform::dynload::ncclAllReduce(
            input.data(),
            output->data(),
            input.numel(),
            platform::ToNCCLDataType(input.type()),
            ToNCCLRedType(opts.reduce_op),
            comm,
            stream);
      },
      CommType::ALLREDUCE,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Barrier(
    const BarrierOptions& opts) {
  auto allocator = std::unique_ptr<phi::Allocator>(
      new paddle::experimental::DefaultAllocator(place_));
  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 nccl_task = dynamic_cast<NCCLTask*>(task.get());
W
Wen Sun 已提交
196
  nccl_task->SetBlockCPUInWait();
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  return task;
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::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,
          ncclComm_t comm,
212
          gpuStream_t stream) {
213 214 215 216 217 218 219 220 221 222 223 224 225
        int root = opts.source_rank + opts.source_root;
        return platform::dynload::ncclBroadcast(
            input.data(),
            output->data(),
            input.numel(),
            platform::ToNCCLDataType(input.type()),
            root,
            comm,
            stream);
      },
      CommType::BROADCAST,
      sync_op,
      use_calc_stream);
226 227
}

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Recv(
    phi::DenseTensor* tensor,
    int src_rank,
    bool sync_op,
    bool use_calc_stream) {
  return PointToPoint(
      tensor,
      src_rank,
      [&](phi::DenseTensor* output,
          int src,
          ncclComm_t comm,
          gpuStream_t stream) {
        return platform::dynload::ncclRecv(
            output->data(),
            output->numel(),
            platform::ToNCCLDataType(output->dtype()),
            src,
            comm,
            stream);
      },
      CommType::RECV,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::RecvPartial(
    phi::DenseTensor* tensor,
    int src_rank,
    int64_t offset,
    int64_t length,
    bool sync_op,
    bool use_calc_stream) {
  phi::DenseTensor tensor_flattened;
  tensor_flattened.ShareDataWith(*tensor).Resize({tensor->numel()});
  phi::DenseTensor tensor_recv =
      tensor_flattened.Slice(offset, offset + length);
  return PointToPoint(
      &tensor_recv,
      src_rank,
      [&](phi::DenseTensor* output,
          int src,
          ncclComm_t comm,
          gpuStream_t stream) {
        return platform::dynload::ncclRecv(
            output->data(),
            output->numel(),
            platform::ToNCCLDataType(output->dtype()),
            src,
            comm,
            stream);
      },
      CommType::RECV,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Send(
    phi::DenseTensor* tensor,
    int dst_rank,
    bool sync_op,
    bool use_calc_stream) {
  return PointToPoint(
      tensor,
      dst_rank,
      [&](phi::DenseTensor* input,
          int dst,
          ncclComm_t comm,
          gpuStream_t stream) {
        return platform::dynload::ncclSend(
            input->data(),
            input->numel(),
            platform::ToNCCLDataType(input->dtype()),
            dst,
            comm,
            stream);
      },
      CommType::SEND,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::SendPartial(
    phi::DenseTensor* tensor,
    int dst_rank,
    int64_t offset,
    int64_t length,
    bool sync_op,
    bool use_calc_stream) {
  phi::DenseTensor tensor_flattened;
  tensor_flattened.ShareDataWith(*tensor).Resize({tensor->numel()});
  phi::DenseTensor tensor_send =
      tensor_flattened.Slice(offset, offset + length);
  return PointToPoint(
      &tensor_send,
      dst_rank,
      [&](phi::DenseTensor* input,
          int dst,
          ncclComm_t comm,
          gpuStream_t stream) {
        return platform::dynload::ncclSend(
            input->data(),
            input->numel(),
            platform::ToNCCLDataType(input->dtype()),
            dst,
            comm,
            stream);
      },
      CommType::SEND,
      sync_op,
      use_calc_stream);
}

340
std::shared_ptr<ProcessGroupNCCL::NCCLTask> ProcessGroupNCCL::CreateTask(
341
    const Place& place,
342 343 344 345 346
    int rank,
    CommType comm_type,
    bool is_sync,
    bool use_calc_stream) {
  return std::make_shared<ProcessGroupNCCL::NCCLTask>(
347
      place, rank, comm_type, is_sync, use_calc_stream);
348 349
}

350 351 352 353 354 355 356 357 358 359 360 361
void ProcessGroupNCCL::BroadcastUniqueNCCLID(ncclUniqueId* nccl_id) {
  const std::string key =
      "ProcessGroupNCCL/nccl_ids/" + std::to_string(gid_) + "/0";
  if (rank_ == 0) {
    std::vector<uint8_t> nccl_id_wrapper(
        reinterpret_cast<uint8_t*>(nccl_id),
        reinterpret_cast<uint8_t*>(nccl_id) + NCCL_UNIQUE_ID_BYTES);
    store_->set(key, nccl_id_wrapper);
  } else {
    const auto& nccl_id_wrapper = store_->get(key);
    std::memcpy(nccl_id, nccl_id_wrapper.data(), nccl_id_wrapper.size());
  }
362 363
}

364 365
void ProcessGroupNCCL::CreateNCCLEnvCache(const Place& place,
                                          const std::string& place_key) {
W
Wen Sun 已提交
366 367 368 369
  if (place_to_comm_ctx_.size() > 0) {
    VLOG(3) << "Warning: Tensors from multiple devices are not supported yet.";
  }

370 371 372 373 374
  ncclUniqueId nccl_id;
  if (rank_ == 0) {
    PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGetUniqueId(&nccl_id));
  }
  BroadcastUniqueNCCLID(&nccl_id);
375

376 377 378
  VLOG(3) << "init nccl rank: " << rank_ << ", nranks: " << size_
          << ", place: " << place_key
          << ", nccl uniqueid: " << SerializeNCCLUniqueId(nccl_id);
379

380 381 382 383 384 385 386 387
  auto* calc_ctx = static_cast<phi::GPUContext*>(
      platform::DeviceContextPool::Instance().Get(place));
  auto comm_ctx = std::make_unique<phi::GPUContext>(place);
  ncclComm_t nccl_comm;
  NCCLCHECK(platform::dynload::ncclCommInitRank(
      &nccl_comm, GetSize(), nccl_id, GetRank()));
  comm_ctx->set_nccl_comm(nccl_comm);

W
Wen Sun 已提交
388 389 390
  place_to_calc_event_.emplace(place_key, place);
  place_to_calc_ctx_.emplace(place_key, calc_ctx);
  place_to_comm_ctx_.emplace(place_key, std::move(comm_ctx));
391 392

  // TODO(sunyilun): for compatibility, will be removed later
W
Wen Sun 已提交
393 394 395
  std::vector<phi::GPUContext*> comm_ctx_wrapper{
      place_to_comm_ctx_[place_key].get()};
  places_to_ctx_.emplace(place_key, comm_ctx_wrapper);
396 397
}

W
Wen Sun 已提交
398
void ProcessGroupNCCL::SyncCalcStream(const Place& place) {
399
  const std::string& key = GetKeyFromPlace(place);
W
Wen Sun 已提交
400 401 402 403 404
  auto& calc_event = place_to_calc_event_.at(key);
  const auto* calc_ctx = place_to_calc_ctx_.at(key);
  const auto* comm_ctx = place_to_comm_ctx_.at(key).get();
  calc_event.Record(calc_ctx);
  calc_event.Wait(platform::Place2DeviceType(place), comm_ctx);
405 406
}

407 408 409 410 411 412 413 414 415 416 417
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Collective(
    phi::DenseTensor* out_tensor,
    const phi::DenseTensor& in_tensor,
    Fn fn,
    CommType comm_type,
    bool sync_op,
    bool use_calc_stream) {
  const auto& place = in_tensor.place();
  const auto& key = GetKeyFromPlace(place);

W
Wen Sun 已提交
418 419 420
  platform::CUDADeviceGuard cuda_guard(place);

  if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
421
    CreateNCCLEnvCache(place, key);
422 423
  }

424
  if (!use_calc_stream) {
W
Wen Sun 已提交
425
    SyncCalcStream(place);
426
  }
427

428 429
  auto task = CreateTask(place, rank_, comm_type, sync_op, use_calc_stream);

W
Wen Sun 已提交
430 431 432
  const auto* calc_ctx = place_to_calc_ctx_.at(key);
  const auto& comm_ctx = place_to_comm_ctx_.at(key);
  auto nccl_comm = comm_ctx->nccl_comm();
433
  auto nccl_stream = use_calc_stream ? calc_ctx->stream() : comm_ctx->stream();
W
Wen Sun 已提交
434
  fn(out_tensor, in_tensor, nccl_comm, nccl_stream);
435 436 437 438 439

  if (!use_calc_stream) {
    if (FLAGS_use_stream_safe_cuda_allocator) {
      memory::RecordStream(in_tensor.Holder(), nccl_stream);
    }
W
Wen Sun 已提交
440
    task->UpdateWaitChain(*comm_ctx);
441 442 443
  }

  return task;
444 445
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::PointToPoint(
    phi::DenseTensor* tensor,
    int rank,
    Fn fn,
    CommType comm_type,
    bool sync_op,
    bool use_calc_stream) {
  const auto& place = tensor->place();
  const auto& key = GetKeyFromPlace(place);

  platform::CUDADeviceGuard cuda_guard(place);

  if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
    CreateNCCLEnvCache(place, key);
  }

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

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

  const auto* calc_ctx = place_to_calc_ctx_.at(key);
  const auto& comm_ctx = place_to_comm_ctx_.at(key);
  auto nccl_comm = comm_ctx->nccl_comm();
  auto nccl_stream = use_calc_stream ? calc_ctx->stream() : comm_ctx->stream();
  fn(tensor, rank, nccl_comm, nccl_stream);

  if (!use_calc_stream) {
    if (FLAGS_use_stream_safe_cuda_allocator) {
      memory::RecordStream(tensor->Holder(), nccl_stream);
    }
    task->UpdateWaitChain(*comm_ctx);
  }

  return task;
}

485
void ProcessGroupNCCL::CheckSplitSizes(std::vector<int64_t>* split_sizes,
486
                                       std::vector<int64_t> tensor_shape) {
487
  int64_t len_size = (*split_sizes).size();
488 489 490 491 492 493
  if (len_size == 0) {
    PADDLE_ENFORCE_EQ(tensor_shape[0] % size_ == 0,
                      true,
                      platform::errors::InvalidArgument(
                          "Tensor's dim[0] must be divisible by group size "
                          "when split_sizes not given."));
494 495 496 497
    (*split_sizes)
        .insert((*split_sizes).end(),
                size_,
                static_cast<int64_t>(tensor_shape[0] / size_));
498 499 500 501 502 503 504
  } else {
    PADDLE_ENFORCE_EQ(
        len_size == size_,
        true,
        platform::errors::InvalidArgument(
            "The length of split_sizes must be equal to group size."));
    auto sum_size = std::accumulate(
505
        (*split_sizes).begin(), (*split_sizes).end(), static_cast<int64_t>(0));
506 507 508 509 510 511 512 513
    PADDLE_ENFORCE_EQ(
        sum_size == tensor_shape[0],
        true,
        platform::errors::InvalidArgument(
            "The sum of split_sizes must be equal to tensor's dim[0]."));
  }
}

514 515
// TODO(sunyilun): methods below will be removed later
void SyncDefaultStream(const std::vector<Place>& places,
W
Wen Sun 已提交
516
                       platform::DeviceEvent& nccl_event,         // NOLINT
517 518 519 520
                       std::vector<phi::GPUContext*>& dev_ctx) {  // NOLINT
  for (size_t i = 0; i < places.size(); ++i) {
    auto* default_ctx = static_cast<phi::GPUContext*>(
        platform::DeviceContextPool::Instance().Get(places[i]));
W
Wen Sun 已提交
521 522
    nccl_event.Record(default_ctx);
    nccl_event.Wait(platform::Place2DeviceType(places[i]), dev_ctx[i]);
B
Baibaifan 已提交
523
  }
524 525
}

526 527 528 529 530 531 532
std::shared_ptr<ProcessGroupNCCL::NCCLTask> ProcessGroupNCCL::CreateTask(
    std::vector<Place> places,
    int rank,
    CommType comm_type,
    const std::vector<phi::DenseTensor>& inputs) {
  return std::make_shared<ProcessGroupNCCL::NCCLTask>(
      places, rank, comm_type, inputs);
533
}
534

535 536 537 538 539 540 541 542 543
std::shared_ptr<ProcessGroupNCCL::NCCLTask> ProcessGroupNCCL::CreateTask(
    const std::vector<Place>& places,
    int rank,
    CommType comm_type,
    const std::vector<phi::DenseTensor>& inputs,
    bool is_sync,
    bool use_calc_stream) {
  return std::make_shared<ProcessGroupNCCL::NCCLTask>(
      places, rank, comm_type, inputs, is_sync, use_calc_stream);
544 545
}

546 547 548 549 550 551 552
ProcessGroupNCCL::NCCLTask::NCCLTask(
    const std::vector<Place>& places,
    int rank,
    CommType CommType,
    const std::vector<phi::DenseTensor>& inputs)
    : TaskStream(rank, inputs, CommType),
      comm_event_(places[0]),
W
Wen Sun 已提交
553
      task_place_(places[0]) {}
554 555 556 557 558 559 560 561 562 563

ProcessGroupNCCL::NCCLTask::NCCLTask(
    const std::vector<Place>& places,
    int rank,
    CommType comm_type,
    const std::vector<phi::DenseTensor>& inputs,
    bool sync_op,
    bool use_calc_stream)
    : TaskStream(rank, inputs, comm_type, sync_op, use_calc_stream),
      comm_event_(places[0]),
W
Wen Sun 已提交
564
      task_place_(places[0]) {}
565

566 567 568
// create NCCLManager cache for places_key
void ProcessGroupNCCL::CreateNCCLManagerCache(
    const std::string& places_key, const std::vector<Place>& places) {
569 570
  PADDLE_ENFORCE_EQ(places_key.empty(),
                    false,
571 572 573 574
                    platform::errors::PreconditionNotMet(
                        "Not able to create/get the NCCL Communicator since "
                        "the GPU place are not known"));

575
  ncclUniqueId nccl_id;
576 577 578
  if (rank_ == 0) {
    PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGetUniqueId(&nccl_id));
  }
579
  BroadcastUniqueNCCLID(&nccl_id);
580

581 582
  VLOG(3) << "init nccl rank: " << rank_ << ", nranks: " << size_
          << ", place: " << places_key
583 584
          << ", nccl uniqueid: " << SerializeNCCLUniqueId(nccl_id);

L
Leo Chen 已提交
585
  std::vector<std::unique_ptr<phi::GPUContext>> dev_ctx;
586 587
  dev_ctx.resize(places.size());

588 589 590
  std::vector<phi::GPUContext*> dev_ctx_raw;
  dev_ctx_raw.resize(places.size());

591 592 593 594
  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());

  for (size_t i = 0; i < places.size(); ++i) {
    platform::CUDADeviceGuard guard(places[i]);
595

L
Leo Chen 已提交
596
    dev_ctx[i].reset(new phi::GPUContext(places[i]));
597 598 599 600 601
    ncclComm_t nccl_comm;
    NCCLCHECK(platform::dynload::ncclCommInitRank(
        &nccl_comm, GetSize(), nccl_id, GetRank()));
    dev_ctx[i]->set_nccl_comm(nccl_comm);
    dev_ctx_raw[i] = dev_ctx[i].get();
602 603 604 605
  }

  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());

606
  // TODO(sunyilun): for compatibility, will be removed later
W
Wen Sun 已提交
607 608 609 610 611 612
  place_to_calc_event_.emplace(places_key, places[0]);
  place_to_calc_ctx_.emplace(
      places_key,
      static_cast<phi::GPUContext*>(
          platform::DeviceContextPool::Instance().Get(places[0])));
  place_to_comm_ctx_.emplace(places_key, std::move(dev_ctx[0]));
613 614

  // These caches will be useful to process sync/wait/communicate
615
  places_to_ctx_.emplace(places_key, std::move(dev_ctx_raw));
616 617
}

618 619 620 621 622 623 624 625 626 627 628 629 630
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Collective(
    std::vector<phi::DenseTensor>& inputs,
    std::vector<phi::DenseTensor>& outputs,
    Fn fn,
    CommType comm_type,
    bool sync_op,
    bool use_calc_stream) {
  const auto& places = GetPlaceList(inputs);
  const auto& key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
W
Wen Sun 已提交
631
    if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
632 633 634 635
      CreateNCCLManagerCache(key, places);
    }
  }

636
  if (!use_calc_stream) {
W
Wen Sun 已提交
637 638
    SyncDefaultStream(
        places, place_to_calc_event_.at(key), places_to_ctx_.at(key));
639
  }
640

641 642
  auto task =
      CreateTask(places, rank_, comm_type, inputs, sync_op, use_calc_stream);
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

  platform::CUDADeviceGuard cuda_guard;

  {
    platform::NCCLGroupGuard nccl_guard;
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);

      gpuStream_t nccl_stream;
      if (use_calc_stream) {
        nccl_stream =
            static_cast<phi::GPUContext*>(
                platform::DeviceContextPool::Instance().Get(places[i]))
                ->stream();
      } else {
W
Wen Sun 已提交
658
        nccl_stream = places_to_ctx_.at(key)[i]->stream();
659 660
      }

661 662
      fn(inputs[i],
         outputs[i],
W
Wen Sun 已提交
663
         places_to_ctx_.at(key)[i]->nccl_comm(),
664
         nccl_stream);
665 666 667 668 669 670 671 672 673 674 675 676 677 678
    }
  }

  if (FLAGS_use_stream_safe_cuda_allocator) {
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);

      gpuStream_t nccl_stream;
      if (use_calc_stream) {
        nccl_stream =
            static_cast<phi::GPUContext*>(
                platform::DeviceContextPool::Instance().Get(places[i]))
                ->stream();
      } else {
W
Wen Sun 已提交
679
        nccl_stream = places_to_ctx_.at(key)[i]->stream();
680 681 682 683 684 685 686 687 688 689
      }

      memory::RecordStream(inputs[i].Holder(), nccl_stream);
    }
  }

  // Adding stream event dependency only when use comm stream
  if (!use_calc_stream) {
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
690
      task->UpdateWaitChain(*places_to_ctx_.at(key)[i]);
691 692 693 694 695 696
    }
  }

  return task;
}

697 698
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Collective(
699
    std::vector<phi::DenseTensor>& inputs,
700 701 702
    std::vector<phi::DenseTensor>& outputs,
    Fn fn,
    CommType op_type) {
703 704 705 706 707
  const auto places = GetPlaceList(inputs);
  const auto key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
W
Wen Sun 已提交
708
    if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
709 710 711 712
      CreateNCCLManagerCache(key, places);
    }
  }

W
Wen Sun 已提交
713 714
  SyncDefaultStream(
      places, place_to_calc_event_.at(key), places_to_ctx_.at(key));
715 716 717 718 719 720

  auto task = CreateTask(places, rank_, op_type, inputs);

  // construct uninitialize guard for device
  platform::CUDADeviceGuard cuda_guard;

S
ShenLiang 已提交
721 722
  {
    platform::NCCLGroupGuard nccl_guard;
723 724
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
725
      const auto& nccl_stream = places_to_ctx_.at(key)[i]->stream();
726 727
      fn(inputs[i],
         outputs[i],
W
Wen Sun 已提交
728
         places_to_ctx_.at(key)[i]->nccl_comm(),
729
         nccl_stream);
730 731 732
    }
  }

S
ShenLiang 已提交
733
  if (FLAGS_use_stream_safe_cuda_allocator) {
734 735
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
S
ShenLiang 已提交
736
      memory::RecordStream(inputs[i].Holder(),
W
Wen Sun 已提交
737
                           places_to_ctx_.at(key)[i]->stream());
738 739 740 741 742
    }
  }

  for (size_t i = 0; i < inputs.size(); ++i) {
    cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
743
    task->UpdateWaitChain(*places_to_ctx_.at(key)[i]);
744 745 746 747
  }
  return task;
}

748 749
template <typename Fn>
void ProcessGroupNCCL::Collective(const phi::DenseTensor* in,
750 751
                                  phi::DenseTensor* out,
                                  Fn fn,
752 753 754
                                  CommType op_type) {
  std::vector<Place> places;
  places.push_back(in->place());
755
  const std::string& key = GetKeyFromPlaces(places);
756 757 758

  {
    std::lock_guard<std::mutex> lock(mutex_);
W
Wen Sun 已提交
759
    if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
760 761 762 763
      CreateNCCLManagerCache(key, places);
    }
  }

W
Wen Sun 已提交
764 765
  SyncDefaultStream(
      places, place_to_calc_event_.at(key), places_to_ctx_.at(key));
766 767 768 769 770 771

  // construct uninitialize guard for device
  platform::CUDADeviceGuard cuda_guard;

  if (FLAGS_use_stream_safe_cuda_allocator) {
    cuda_guard.SetDevice(places[0]);
W
Wen Sun 已提交
772
    memory::RecordStream(in->Holder(), places_to_ctx_.at(key)[0]->stream());
773 774 775 776 777
  }

  {
    platform::NCCLGroupGuard nccl_guard;
    cuda_guard.SetDevice(places[0]);
W
Wen Sun 已提交
778 779
    const auto& nccl_stream = places_to_ctx_.at(key)[0]->stream();
    fn(in, out, places_to_ctx_.at(key)[0]->nccl_comm(), nccl_stream);
780 781 782 783 784
  }

  cuda_guard.SetDevice(places[0]);
}

785 786 787 788 789 790 791 792 793 794 795 796 797
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::PointToPoint(
    std::vector<phi::DenseTensor>& tensors,
    Fn fn,
    int dst_rank,
    CommType op_type,
    bool sync_op,
    bool use_calc_stream) {
  const auto& places = GetPlaceList(tensors);
  const auto& key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
W
Wen Sun 已提交
798
    if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
799 800 801 802 803
      CreateNCCLManagerCache(key, places);
    }
  }

  if (!use_calc_stream) {
W
Wen Sun 已提交
804 805
    SyncDefaultStream(
        places, place_to_calc_event_.at(key), places_to_ctx_.at(key));
806 807 808 809 810 811 812
  }

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

  platform::CUDADeviceGuard cuda_guard;

813 814
  {
    platform::NCCLGroupGuard nccl_guard;
815 816 817 818 819 820 821 822 823
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
      gpuStream_t nccl_stream;
      if (use_calc_stream) {
        nccl_stream =
            static_cast<phi::GPUContext*>(
                platform::DeviceContextPool::Instance().Get(places[i]))
                ->stream();
      } else {
W
Wen Sun 已提交
824
        nccl_stream = places_to_ctx_.at(key)[i]->stream();
825
      }
826
      fn(tensors[i],
W
Wen Sun 已提交
827
         places_to_ctx_.at(key)[i]->nccl_comm(),
828 829
         nccl_stream,
         dst_rank);
830 831 832
    }
  }

833
  if (FLAGS_use_stream_safe_cuda_allocator) {
834 835 836 837 838 839 840 841 842
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
      gpuStream_t nccl_stream;
      if (use_calc_stream) {
        nccl_stream =
            static_cast<phi::GPUContext*>(
                platform::DeviceContextPool::Instance().Get(places[i]))
                ->stream();
      } else {
W
Wen Sun 已提交
843
        nccl_stream = places_to_ctx_.at(key)[i]->stream();
844
      }
845
      memory::RecordStream(tensors[i].Holder(), nccl_stream);
846 847 848 849 850 851
    }
  }

  if (!use_calc_stream) {
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
852
      task->UpdateWaitChain(*places_to_ctx_.at(key)[i]);
853 854 855 856 857 858
    }
  }

  return task;
}

B
Baibaifan 已提交
859 860
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::PointToPoint(
861 862 863
    std::vector<phi::DenseTensor>& tensors,
    Fn fn,
    int dst_rank,
864
    CommType op_type) {
B
Baibaifan 已提交
865 866 867 868 869
  const auto places = GetPlaceList(tensors);
  const auto key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
W
Wen Sun 已提交
870
    if (place_to_comm_ctx_.find(key) == place_to_comm_ctx_.end()) {
B
Baibaifan 已提交
871 872 873 874
      CreateNCCLManagerCache(key, places);
    }
  }

W
Wen Sun 已提交
875 876
  SyncDefaultStream(
      places, place_to_calc_event_.at(key), places_to_ctx_.at(key));
B
Baibaifan 已提交
877 878 879 880 881 882

  auto task = CreateTask(places, rank_, op_type, tensors);

  // construct uninitialize guard for device
  platform::CUDADeviceGuard cuda_guard;

883 884
  {
    platform::NCCLGroupGuard nccl_guard;
B
Baibaifan 已提交
885 886
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
887
      const auto& nccl_stream = places_to_ctx_.at(key)[i]->stream();
888
      fn(tensors[i],
W
Wen Sun 已提交
889
         places_to_ctx_.at(key)[i]->nccl_comm(),
890 891
         nccl_stream,
         dst_rank);
B
Baibaifan 已提交
892 893 894
    }
  }

895
  if (FLAGS_use_stream_safe_cuda_allocator) {
B
Baibaifan 已提交
896 897
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
898
      memory::RecordStream(tensors[i].Holder(),
W
Wen Sun 已提交
899
                           places_to_ctx_.at(key)[i]->stream());
B
Baibaifan 已提交
900 901 902 903 904
    }
  }

  for (size_t i = 0; i < tensors.size(); ++i) {
    cuda_guard.SetDevice(places[i]);
W
Wen Sun 已提交
905
    task->UpdateWaitChain(*places_to_ctx_.at(key)[i]);
B
Baibaifan 已提交
906 907 908 909
  }
  return task;
}

910
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllReduce(
911
    std::vector<phi::DenseTensor>& in_tensors,
912 913
    std::vector<phi::DenseTensor>& out_tensors,
    const AllreduceOptions& opts) {
914
  PADDLE_ENFORCE_EQ(
915 916
      CheckTensorsInCudaPlace(in_tensors),
      true,
917
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
918
  return Collective(
919 920 921 922 923 924
      in_tensors,
      out_tensors,
      [&](const phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
925
        return platform::dynload::ncclAllReduce(
926 927 928
            input.data(),
            output.data(),
            input.numel(),
929
            platform::ToNCCLDataType(input.type()),
930 931 932
            ToNCCLRedType(opts.reduce_op),
            comm,
            stream);
933 934
      },
      CommType::ALLREDUCE);
935 936 937
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Broadcast(
938
    std::vector<phi::DenseTensor>& in_tensors,
939 940
    std::vector<phi::DenseTensor>& out_tensors,
    const BroadcastOptions& opts) {
941
  PADDLE_ENFORCE_EQ(
942 943
      CheckTensorsInCudaPlace(in_tensors),
      true,
944 945
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));

946
  return Collective(
947 948 949 950 951
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
952 953 954 955
          const gpuStream_t& stream) {
        const auto root =
            opts.source_rank * in_tensors.size() + opts.source_root;
        return platform::dynload::ncclBroadcast(
956 957 958 959 960 961 962
            input.data(),
            output.data(),
            input.numel(),
            platform::ToNCCLDataType(input.type()),
            root,
            comm,
            stream);
963 964
      },
      CommType::BROADCAST);
965 966
}

967 968
void CheckTensorsInDifferentDevices(
    const std::vector<phi::DenseTensor>& tensors, const size_t num_devices) {
B
Baibaifan 已提交
969
  PADDLE_ENFORCE_EQ(
970 971
      tensors.size() == 0,
      false,
B
Baibaifan 已提交
972 973
      platform::errors::InvalidArgument("Tensor list must be nonempty."));
  PADDLE_ENFORCE_LE(
974 975
      tensors.size(),
      num_devices,
B
Baibaifan 已提交
976 977 978 979 980 981
      platform::errors::InvalidArgument(
          "Tensor list mustn't be larger than the number of available GPUs."));

  std::set<Place> used_devices;

  for (const auto& t : tensors) {
982 983
    PADDLE_ENFORCE_EQ(platform::is_gpu_place(t.place()),
                      true,
B
Baibaifan 已提交
984 985 986
                      platform::errors::InvalidArgument(
                          "Tensors must be CUDA and dense tensor."));

987
    const auto inserted = used_devices.insert(t.place()).second;
988 989
    PADDLE_ENFORCE_EQ(inserted,
                      true,
B
Baibaifan 已提交
990 991 992 993 994 995
                      platform::errors::InvalidArgument(
                          "Tensors must be on distinct GPU devices."));
  }
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Send(
996
    std::vector<phi::DenseTensor>& tensors, int dst_rank) {
B
Baibaifan 已提交
997 998
  CheckTensorsInDifferentDevices(tensors, static_cast<size_t>(GetSize()));

999 1000
  auto task = PointToPoint(
      tensors,
1001 1002 1003
      [&](phi::DenseTensor& input,
          ncclComm_t comm,
          const gpuStream_t& stream,
1004 1005
          int dst_rank) {
        return platform::dynload::ncclSend(
1006 1007 1008 1009 1010 1011
            input.data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            dst_rank,
            comm,
            stream);
1012
      },
1013 1014
      dst_rank,
      CommType::SEND);
B
Baibaifan 已提交
1015 1016 1017 1018
  return task;
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Recv(
1019
    std::vector<phi::DenseTensor>& tensors, int src_rank) {
B
Baibaifan 已提交
1020 1021
  CheckTensorsInDifferentDevices(tensors, static_cast<size_t>(GetSize()));

1022 1023
  auto task = PointToPoint(
      tensors,
1024 1025 1026
      [&](phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream,
1027 1028
          int src_rank) {
        return platform::dynload::ncclRecv(
1029 1030 1031 1032 1033 1034
            output.data(),
            output.numel(),
            platform::ToNCCLDataType(output.dtype()),
            src_rank,
            comm,
            stream);
1035
      },
1036 1037
      src_rank,
      CommType::RECV);
1038 1039 1040 1041
  return task;
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Send_Partial(
1042
    phi::DenseTensor& tensors, int dst_rank, int64_t offset, int64_t length) {
1043 1044 1045 1046 1047
  // CheckTensorsInDifferentDevices(tensors, static_cast<size_t>(GetSize()));

  phi::DenseTensor flatten_tensor;
  flatten_tensor.ShareDataWith(tensors).Resize({tensors.numel()});

1048 1049
  std::vector<phi::DenseTensor> shared_tensors{
      flatten_tensor.Slice(offset, offset + length)};
1050

1051 1052
  auto task = PointToPoint(
      shared_tensors,
1053 1054 1055
      [&](phi::DenseTensor& input,
          ncclComm_t comm,
          const gpuStream_t& stream,
1056 1057
          int dst_rank) {
        return platform::dynload::ncclSend(
1058 1059 1060 1061 1062 1063
            input.data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            dst_rank,
            comm,
            stream);
1064
      },
1065 1066
      dst_rank,
      CommType::SEND);
1067 1068 1069
  return task;
}

1070 1071 1072
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Send_Partial(
    phi::DenseTensor& tensors,
    int dst_rank,
1073 1074
    int64_t offset,
    int64_t length,
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    bool sync_op,
    bool use_calc_stream) {
  phi::DenseTensor flatten_tensor;
  flatten_tensor.ShareDataWith(tensors).Resize({tensors.numel()});

  std::vector<phi::DenseTensor> shared_tensors{
      flatten_tensor.Slice(offset, offset + length)};

  auto task = PointToPoint(
      shared_tensors,
      [&](phi::DenseTensor& input,
          ncclComm_t comm,
          const gpuStream_t& stream,
          int dst_rank) {
        return platform::dynload::ncclSend(
            input.data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            dst_rank,
            comm,
            stream);
      },
      dst_rank,
      CommType::SEND,
      sync_op,
      use_calc_stream);
  return task;
}

1104
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Recv_Partial(
1105
    phi::DenseTensor& tensors, int src_rank, int64_t offset, int64_t length) {
1106 1107 1108 1109 1110
  // phi::DenseTensor shared_input = tensors.Slice(offset, offset+length);

  phi::DenseTensor flatten_tensor;
  flatten_tensor.ShareDataWith(tensors).Resize({tensors.numel()});

1111 1112
  std::vector<phi::DenseTensor> shared_tensors{
      flatten_tensor.Slice(offset, offset + length)};
1113

1114 1115
  auto task = PointToPoint(
      shared_tensors,
1116 1117 1118
      [&](phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream,
1119 1120
          int src_rank) {
        return platform::dynload::ncclRecv(
1121 1122 1123 1124 1125 1126
            output.data(),
            output.numel(),
            platform::ToNCCLDataType(output.dtype()),
            src_rank,
            comm,
            stream);
1127
      },
1128 1129
      src_rank,
      CommType::RECV);
B
Baibaifan 已提交
1130 1131 1132
  return task;
}

1133 1134 1135
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Recv_Partial(
    phi::DenseTensor& tensors,
    int src_rank,
1136 1137
    int64_t offset,
    int64_t length,
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    bool sync_op,
    bool use_calc_stream) {
  phi::DenseTensor flatten_tensor;
  flatten_tensor.ShareDataWith(tensors).Resize({tensors.numel()});

  std::vector<phi::DenseTensor> shared_tensors{
      flatten_tensor.Slice(offset, offset + length)};

  auto task = PointToPoint(
      shared_tensors,
      [&](phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream,
          int src_rank) {
        return platform::dynload::ncclRecv(
            output.data(),
            output.numel(),
            platform::ToNCCLDataType(output.dtype()),
            src_rank,
            comm,
            stream);
      },
      src_rank,
      CommType::RECV,
      sync_op,
      use_calc_stream);
  return task;
}

1167
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllGather(
1168 1169
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors) {
1170
  PADDLE_ENFORCE_EQ(
1171 1172
      CheckTensorsInCudaPlace(in_tensors),
      true,
1173 1174
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
1175 1176
      CheckTensorsInCudaPlace(out_tensors),
      true,
1177
      platform::errors::InvalidArgument("All outputs should be in CudaPlace."));
1178
  return Collective(
1179 1180 1181 1182 1183 1184
      in_tensors,
      out_tensors,
      [&](const phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
1185
        return platform::dynload::ncclAllGather(
1186 1187 1188 1189 1190 1191
            input.data(),
            output.data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            comm,
            stream);
1192 1193
      },
      CommType::ALLGATHER);
1194 1195
}

1196 1197
void* GetPointerByOffset(void* raw_pointer,
                         size_t offset,
1198 1199 1200 1201 1202 1203 1204
                         experimental::DataType type) {
  if (type == experimental::DataType::FLOAT32) {
    return reinterpret_cast<void*>(reinterpret_cast<float*>(raw_pointer) +
                                   offset);
  } else if (type == experimental::DataType::FLOAT64) {
    return reinterpret_cast<void*>(reinterpret_cast<double*>(raw_pointer) +
                                   offset);
1205 1206 1207
  } else if (type == experimental::DataType::FLOAT16) {
    return reinterpret_cast<void*>(reinterpret_cast<int16_t*>(raw_pointer) +
                                   offset);
1208 1209 1210 1211 1212 1213
  } else if (type == experimental::DataType::INT32) {
    return reinterpret_cast<void*>(reinterpret_cast<int32_t*>(raw_pointer) +
                                   offset);
  } else if (type == experimental::DataType::INT64) {
    return reinterpret_cast<void*>(reinterpret_cast<int64_t*>(raw_pointer) +
                                   offset);
1214 1215 1216 1217 1218 1219 1220 1221
  } else if (type == experimental::DataType::INT8) {
    return reinterpret_cast<void*>(reinterpret_cast<int8_t*>(raw_pointer) +
                                   offset);
  } else if (type == experimental::DataType::UINT8) {
    return reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(raw_pointer) +
                                   offset);
  } else if (type == experimental::DataType::BOOL) {
    return reinterpret_cast<void*>(reinterpret_cast<bool*>(raw_pointer) +
1222
                                   offset);
1223 1224 1225
  } else if (type == experimental::DataType::BFLOAT16) {
    return reinterpret_cast<void*>(reinterpret_cast<uint16_t*>(raw_pointer) +
                                   offset);
1226 1227 1228 1229
  } else {
    PADDLE_THROW(platform::errors::Unimplemented(
        "This datatype in nccl is not supported."));
  }
1230
  return nullptr;
1231 1232
}

1233 1234 1235
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllGather_Partial(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
1236 1237
    int64_t offset,
    int64_t length) {
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All outputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        return platform::dynload::ncclAllGather(
            GetPointerByOffset(input.data(), offset, input.dtype()),
            output.data(),
            length,
            platform::ToNCCLDataType(input.dtype()),
            comm,
            stream);
      },
      CommType::ALLGATHER);
}

1264 1265 1266
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllGather_Partial(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
1267 1268
    int64_t offset,
    int64_t length,
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    bool sync_op,
    bool use_calc_stream) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All outputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        return platform::dynload::ncclAllGather(
            GetPointerByOffset(input.data(), offset, input.dtype()),
            output.data(),
            length,
            platform::ToNCCLDataType(input.dtype()),
            comm,
            stream);
      },
      CommType::ALLGATHER,
      sync_op,
      use_calc_stream);
}

1299
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllToAll(
1300 1301
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors) {
1302
  PADDLE_ENFORCE_EQ(
1303 1304
      CheckTensorsInCudaPlace(in_tensors),
      true,
1305 1306
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
1307 1308
      CheckTensorsInCudaPlace(out_tensors),
      true,
1309 1310
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
1311 1312 1313 1314 1315
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
1316 1317 1318 1319 1320
          const gpuStream_t& stream) {
        size_t offset = 0;
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
        for (auto i = 0; i < size_; i++) {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
1321
              GetPointerByOffset(input.data(), offset, input.dtype()),
1322 1323 1324 1325 1326
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
1327
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
1328
              GetPointerByOffset(output.data(), offset, input.dtype()),
1329 1330 1331 1332 1333
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
1334
          offset += input.numel() / size_;
1335 1336 1337
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
      },
1338 1339 1340
      CommType::ALLTOALL);
}

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllToAll(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    bool sync_op,
    bool use_calc_stream) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        size_t offset = 0;
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
        for (auto i = 0; i < size_; i++) {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
              GetPointerByOffset(input.data(), offset, input.dtype()),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
              GetPointerByOffset(output.data(), offset, input.dtype()),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          offset += input.numel() / size_;
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
      },
      CommType::ALLTOALL,
      sync_op,
      use_calc_stream);
}

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllToAll_Single(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    std::vector<int64_t>& in_sizes,
    std::vector<int64_t>& out_sizes) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        PADDLE_ENFORCE_EQ(input.dtype() == output.dtype(),
                          true,
                          platform::errors::InvalidArgument(
                              "The dtypes of input and output must be equal."));

        std::vector<int64_t> in_dims = phi::vectorize(input.dims());
        std::vector<int64_t> out_dims = phi::vectorize(output.dims());
1414 1415
        CheckSplitSizes(&in_sizes, in_dims);
        CheckSplitSizes(&out_sizes, out_dims);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

        size_t in_offset = 0, out_offset = 0;
        size_t in_length = 0, out_length = 0;
        size_t in_row_size = input.numel() / in_dims[0];
        size_t out_row_size = output.numel() / out_dims[0];

        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
        for (auto i = 0; i < size_; i++) {
          in_length = in_sizes[i] * in_row_size;
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
              GetPointerByOffset(input.data(), in_offset, input.dtype()),
              in_length,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          in_offset += in_length;

          out_length = out_sizes[i] * out_row_size;
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
              GetPointerByOffset(output.data(), out_offset, input.dtype()),
              out_length,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          out_offset += out_length;
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
      },
      CommType::ALLTOALL_SINGLE);
1447 1448
}

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllToAllSingle(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    std::vector<int64_t>& in_sizes,
    std::vector<int64_t>& out_sizes,
    bool sync_op,
    bool use_calc_stream) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        PADDLE_ENFORCE_EQ(input.dtype() == output.dtype(),
                          true,
                          platform::errors::InvalidArgument(
                              "The dtypes of input and output must be equal."));

        std::vector<int64_t> in_dims = phi::vectorize(input.dims());
        std::vector<int64_t> out_dims = phi::vectorize(output.dims());
        CheckSplitSizes(&in_sizes, in_dims);
        CheckSplitSizes(&out_sizes, out_dims);

        size_t in_offset = 0, out_offset = 0;
        size_t in_length = 0, out_length = 0;
        size_t in_row_size = input.numel() / in_dims[0];
        size_t out_row_size = output.numel() / out_dims[0];

        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
        for (auto i = 0; i < size_; i++) {
          in_length = in_sizes[i] * in_row_size;
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
              GetPointerByOffset(input.data(), in_offset, input.dtype()),
              in_length,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          in_offset += in_length;

          out_length = out_sizes[i] * out_row_size;
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
              GetPointerByOffset(output.data(), out_offset, input.dtype()),
              out_length,
              platform::ToNCCLDataType(input.dtype()),
              i,
              comm,
              stream));
          out_offset += out_length;
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
      },
      CommType::ALLTOALL_SINGLE,
      sync_op,
      use_calc_stream);
}

1515
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Reduce(
1516
    std::vector<phi::DenseTensor>& in_tensors,
1517 1518
    std::vector<phi::DenseTensor>& out_tensors,
    const ReduceOptions& opts) {
1519
  PADDLE_ENFORCE_EQ(
1520 1521
      CheckTensorsInCudaPlace(in_tensors),
      true,
1522 1523
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
1524 1525 1526 1527 1528 1529
      in_tensors,
      out_tensors,
      [&](const phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
1530
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclReduce(
1531 1532 1533
            input.data(),
            output.data(),
            input.numel(),
1534
            platform::ToNCCLDataType(input.dtype()),
1535 1536 1537 1538
            ToNCCLRedType(opts.reduce_op),
            opts.root_rank,
            comm,
            stream));
1539 1540 1541 1542
      },
      CommType::REDUCE);
}

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Reduce(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const ReduceOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](const phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclReduce(
            input.data(),
            output.data(),
            input.numel(),
            platform::ToNCCLDataType(input.dtype()),
            ToNCCLRedType(opts.reduce_op),
            opts.root_rank,
            comm,
            stream));
      },
      CommType::REDUCE,
      sync_op,
      use_calc_stream);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::ReduceScatter(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const ReduceScatterOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        if (FLAGS_use_stream_safe_cuda_allocator) {
          platform::CUDADeviceGuard cuda_guard;
          cuda_guard.SetDevice(output.place());
          memory::RecordStream(output.Holder(), stream);
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclReduceScatter(
            input.data(),
            output.data(),
            output.numel(),
            platform::ToNCCLDataType(input.dtype()),
            ToNCCLRedType(opts.reduce_op),
            comm,
            stream));
      },
      CommType::REDUCE_SCATTER,
      sync_op,
      use_calc_stream);
}

1607
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Scatter(
1608
    std::vector<phi::DenseTensor>& in_tensors,
1609 1610
    std::vector<phi::DenseTensor>& out_tensors,
    const ScatterOptions& opts) {
1611
  PADDLE_ENFORCE_EQ(
1612 1613
      CheckTensorsInCudaPlace(in_tensors),
      true,
1614 1615
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
1616 1617
      CheckTensorsInCudaPlace(out_tensors),
      true,
1618 1619
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
1620 1621 1622 1623 1624
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
1625 1626 1627 1628 1629 1630
          const gpuStream_t& stream) {
        size_t offset = 0;
        if (rank_ == opts.root_rank) {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
          for (auto i = 0; i < size_; i++) {
            PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
1631
                GetPointerByOffset(input.data(), offset, input.dtype()),
1632 1633 1634 1635 1636
                input.numel() / size_,
                platform::ToNCCLDataType(input.dtype()),
                i,
                comm,
                stream));
1637
            offset += input.numel() / size_;
1638 1639
          }
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
1640 1641 1642 1643 1644
              output.data(),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              opts.root_rank,
              comm,
1645 1646 1647 1648
              stream));
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
        } else {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
1649 1650 1651 1652 1653
              output.data(),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              opts.root_rank,
              comm,
1654 1655 1656 1657 1658 1659
              stream));
        }
      },
      CommType::SCATTER);
}

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Scatter(
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors,
    const ScatterOptions& opts,
    bool sync_op,
    bool use_calc_stream) {
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(in_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  PADDLE_ENFORCE_EQ(
      CheckTensorsInCudaPlace(out_tensors),
      true,
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
      in_tensors,
      out_tensors,
      [&](phi::DenseTensor& input,
          phi::DenseTensor& output,
          ncclComm_t comm,
          const gpuStream_t& stream) {
        PADDLE_ENFORCE_EQ(
            output.numel(),
            input.numel() / size_,
            platform::errors::InvalidArgument(
                "Input and output tensors should have the same shape."));
        size_t offset = 0;
        if (rank_ == opts.root_rank) {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
          for (auto i = 0; i < size_; i++) {
            PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclSend(
                GetPointerByOffset(input.data(), offset, input.dtype()),
                input.numel() / size_,
                platform::ToNCCLDataType(input.dtype()),
                i,
                comm,
                stream));
            offset += input.numel() / size_;
          }
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
              output.data(),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              opts.root_rank,
              comm,
              stream));
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
        } else {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
              output.data(),
              input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()),
              opts.root_rank,
              comm,
              stream));
        }
      },
      CommType::SCATTER,
      sync_op,
      use_calc_stream);
}

1722 1723
}  //  namespace distributed
}  //  namespace paddle