ProcessGroupNCCL.cc 21.4 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"
L
lilong12 已提交
16
#include "paddle/fluid/distributed/collective/Common.h"
17
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
B
Baibaifan 已提交
18 19 20
#include "paddle/fluid/platform/place.h"
#include "paddle/phi/api/include/api.h"
#include "paddle/phi/common/place.h"
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

DECLARE_bool(nccl_blocking_wait);
DECLARE_bool(use_stream_safe_cuda_allocator);

constexpr int64_t kWaitBlockTImeout = 10;

namespace paddle {
namespace distributed {

void SyncDefaultStream(
    const std::vector<Place>& places,
    std::vector<EventManager>& ncclEvents,                       // NOLINT
    std::vector<std::unique_ptr<CUDADeviceContext>>& dev_ctx) {  // NOLINT
  for (size_t i = 0; i < places.size(); ++i) {
    auto* default_ctx = static_cast<platform::CUDADeviceContext*>(
        platform::DeviceContextPool::Instance().Get(places[i]));
37 38
    ncclEvents[i].Record(*default_ctx);
    ncclEvents[i].Block(*dev_ctx[i]);
39 40 41 42 43
  }
}

std::shared_ptr<ProcessGroupNCCL::NCCLTask> ProcessGroupNCCL::CreateTask(
    std::vector<Place> places, int rank, CommType comm_type,
L
lilong12 已提交
44
    const std::vector<phi::DenseTensor>& inputs) {
45 46 47 48
  return std::make_shared<ProcessGroupNCCL::NCCLTask>(places, rank, comm_type,
                                                      inputs);
}

L
lilong12 已提交
49 50 51
ProcessGroupNCCL::NCCLTask::NCCLTask(
    const std::vector<Place>& places, int rank, CommType CommType,
    const std::vector<phi::DenseTensor>& inputs)
52 53 54 55 56 57 58 59
    : Task(rank, inputs, CommType), places_(places) {
  control_events_.resize(places.size());
  ncclComms_.resize(places.size());
}

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

void ProcessGroupNCCL::NCCLTask::SetOutputs(
L
lilong12 已提交
60 61
    std::vector<phi::DenseTensor>& outputs) {  // NOLINT
  outputs_ = std::make_shared<std::vector<phi::DenseTensor>>(outputs);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

void ProcessGroupNCCL::NCCLTask::SynchronizeStreams() {
  for (size_t i = 0; i < places_.size(); ++i) {
    auto* default_ctx = static_cast<platform::CUDADeviceContext*>(
        platform::DeviceContextPool::Instance().Get(places_[i]));
    default_ctx->WaitEvent(control_events_[i].GetRawCudaEvent());
  }
}

bool ProcessGroupNCCL::NCCLTask::IsCompleted() {
  for (size_t i = 0; i < places_.size(); ++i) {
    if (!control_events_[i].Query()) {
      return false;
    }
  }

  return true;
}

// TODO(sheniang03): Add timeout for wait, now timeout unused
bool ProcessGroupNCCL::NCCLTask::Wait(std::chrono::milliseconds timeout) {
  SynchronizeStreams();
  if (FLAGS_nccl_blocking_wait) {
    // NOTE(shenliang03): It will block host for sync
    while (!IsCompleted()) {
      std::this_thread::sleep_for(std::chrono::milliseconds(kWaitBlockTImeout));
    }
  }
B
Baibaifan 已提交
91 92 93 94 95 96 97 98

  if (!barrierTensors_.empty()) {
    // If we use the work to do barrier, we should block cpu
    for (auto& place : places_) {
      platform::CUDADeviceGuard gpuGuard(place);
      PADDLE_ENFORCE_GPU_SUCCESS(cudaDeviceSynchronize());
    }
  }
99 100 101 102 103 104
  return true;
}

// Same as Wait
void ProcessGroupNCCL::NCCLTask::Synchronize() { Wait(kWaitTimeout); }

105
ProcessGroupNCCL::ProcessGroupNCCL(const std::shared_ptr<Store>& store,
L
lilong12 已提交
106 107
                                   int rank, int size, int gid)
    : ProcessGroup(rank, size, gid), store_(store) {}
108 109 110

void ProcessGroupNCCL::BroadcastUniqueNCCLID(
    std::vector<ncclUniqueId>& nccl_ids) {  // NOLINT
111 112
  if (rank_ == 0) {
    for (size_t i = 0; i < nccl_ids.size(); i++) {
113 114
      auto key = "ProcessGroupNCCL/nccl_ids/" + std::to_string(gid_) + "/" +
                 std::to_string(i);
115 116 117 118 119 120 121
      auto nccl_id = std::vector<uint8_t>(
          reinterpret_cast<uint8_t*>(&nccl_ids[i]),
          reinterpret_cast<uint8_t*>(&nccl_ids[i]) + NCCL_UNIQUE_ID_BYTES);
      store_->set(key, nccl_id);
    }
  } else {
    for (size_t i = 0; i < nccl_ids.size(); i++) {
122 123
      auto key = "ProcessGroupNCCL/nccl_ids/" + std::to_string(gid_) + "/" +
                 std::to_string(i);
124 125 126
      auto ret = store_->get(key);
      std::memcpy(&nccl_ids[i], ret.data(), ret.size());
    }
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  }
}

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

  std::vector<std::shared_ptr<NCCLCommManager>> nccl_comms;
  nccl_comms.resize(places.size());

  // using vector just for broadcast
  std::vector<ncclUniqueId> nccl_ids;
  nccl_ids.resize(1);
  auto& nccl_id = nccl_ids.front();

B
Baibaifan 已提交
146 147 148 149
  for (auto& place : places) {
    used_place_ids_.insert(place.GetDeviceId());
  }

150 151 152 153 154
  if (rank_ == 0) {
    PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGetUniqueId(&nccl_id));
  }
  BroadcastUniqueNCCLID(nccl_ids);

155 156
  VLOG(3) << "init nccl rank: " << rank_ << ", nranks: " << size_
          << ", place: " << places_key
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
          << ", nccl uniqueid: " << SerializeNCCLUniqueId(nccl_id);

  std::vector<std::unique_ptr<CUDADeviceContext>> dev_ctx;
  dev_ctx.resize(places.size());

  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());

  for (size_t i = 0; i < places.size(); ++i) {
    platform::CUDADeviceGuard guard(places[i]);
    nccl_comms[i] = NCCLCommManager::Create(GetSize(), GetRank(), nccl_id);
    dev_ctx[i].reset(new CUDADeviceContext(places[i]));
  }

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

  std::vector<EventManager> events;
  events.resize(places.size());

  // These caches will be useful to process sync/wait/communicate
  places_to_events_.emplace(places_key, std::move(events));
  places_to_ncclcomm_.emplace(places_key, std::move(nccl_comms));
  places_to_ctx_.emplace(places_key, std::move(dev_ctx));
}

template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Collective(
L
lilong12 已提交
183 184
    std::vector<phi::DenseTensor>& inputs,
    std::vector<phi::DenseTensor>& outputs, Fn fn, CommType op_type) {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  const auto places = GetPlaceList(inputs);
  const auto key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
    if (places_to_ncclcomm_.find(key) == places_to_ncclcomm_.end()) {
      CreateNCCLManagerCache(key, places);
    }
  }

  auto& nccl_comms = places_to_ncclcomm_[key];

  SyncDefaultStream(places, places_to_events_[key], places_to_ctx_[key]);

  auto task = CreateTask(places, rank_, op_type, inputs);
  task->SetOutputs(outputs);

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

  if (FLAGS_use_stream_safe_cuda_allocator) {
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
L
lilong12 已提交
208
      memory::RecordStream(inputs[i].Holder(),
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                           places_to_ctx_[key][i]->stream());
    }
  }

  {
    platform::NCCLGroupGuard nccl_guard;
    for (size_t i = 0; i < inputs.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
      const auto& nccl_stream = places_to_ctx_[key][i]->stream();
      fn(inputs[i], outputs[i], nccl_comms[i]->GetNcclComm(), nccl_stream);
    }
  }

  for (size_t i = 0; i < inputs.size(); ++i) {
    cuda_guard.SetDevice(places[i]);
    task->control_events_[i].Record(*places_to_ctx_[key][i]);
  }
  return task;
}

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
template <typename Fn>
void ProcessGroupNCCL::Collective(const phi::DenseTensor* in,
                                  phi::DenseTensor* out, Fn fn,
                                  CommType op_type) {
  std::vector<Place> places;
  places.push_back(in->place());
  const auto key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
    if (places_to_ncclcomm_.find(key) == places_to_ncclcomm_.end()) {
      CreateNCCLManagerCache(key, places);
    }
  }

  auto& nccl_comms = places_to_ncclcomm_[key];

  SyncDefaultStream(places, places_to_events_[key], places_to_ctx_[key]);

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

  if (FLAGS_use_stream_safe_cuda_allocator) {
    cuda_guard.SetDevice(places[0]);
    memory::RecordStream(in->Holder(), places_to_ctx_[key][0]->stream());
  }

  {
    platform::NCCLGroupGuard nccl_guard;
    cuda_guard.SetDevice(places[0]);
    const auto& nccl_stream = places_to_ctx_[key][0]->stream();
    fn(in, out, nccl_comms[0]->GetNcclComm(), nccl_stream);
  }

  cuda_guard.SetDevice(places[0]);
}

B
Baibaifan 已提交
266 267
template <typename Fn>
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::PointToPoint(
L
lilong12 已提交
268 269
    std::vector<phi::DenseTensor>& tensors, Fn fn, int dst_rank,
    CommType op_type) {
B
Baibaifan 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  const auto places = GetPlaceList(tensors);
  const auto key = GetKeyFromPlaces(places);

  {
    std::lock_guard<std::mutex> lock(mutex_);
    if (places_to_ncclcomm_.find(key) == places_to_ncclcomm_.end()) {
      CreateNCCLManagerCache(key, places);
    }
  }

  auto& nccl_comms = places_to_ncclcomm_[key];

  SyncDefaultStream(places, places_to_events_[key], places_to_ctx_[key]);

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

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

  if (FLAGS_use_stream_safe_cuda_allocator) {
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
L
lilong12 已提交
292
      memory::RecordStream(tensors[i].Holder(),
B
Baibaifan 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
                           places_to_ctx_[key][i]->stream());
    }
  }

  {
    platform::NCCLGroupGuard nccl_guard;
    for (size_t i = 0; i < tensors.size(); ++i) {
      cuda_guard.SetDevice(places[i]);
      const auto& nccl_stream = places_to_ctx_[key][i]->stream();
      fn(tensors[i], nccl_comms[i]->GetNcclComm(), nccl_stream, dst_rank);
    }
  }

  for (size_t i = 0; i < tensors.size(); ++i) {
    cuda_guard.SetDevice(places[i]);
    task->control_events_[i].Record(*places_to_ctx_[key][i]);
  }
  return task;
}

313
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllReduce(
L
lilong12 已提交
314 315
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors, const AllreduceOptions& opts) {
316
  PADDLE_ENFORCE_EQ(
L
lilong12 已提交
317
      CheckTensorsInCudaPlace(in_tensors), true,
318
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
L
lilong12 已提交
319 320 321 322 323 324 325 326 327
  return Collective(in_tensors, out_tensors,
                    [&](const phi::DenseTensor& input, phi::DenseTensor& output,
                        ncclComm_t comm, const gpuStream_t& stream) {
                      return platform::dynload::ncclAllReduce(
                          input.data(), output.data(), input.numel(),
                          platform::ToNCCLDataType(input.type()),
                          ToNCCLRedType(opts.reduce_op), comm, stream);
                    },
                    CommType::ALLREDUCE);
328 329 330
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Broadcast(
L
lilong12 已提交
331 332
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors, const BroadcastOptions& opts) {
333
  PADDLE_ENFORCE_EQ(
L
lilong12 已提交
334
      CheckTensorsInCudaPlace(in_tensors), true,
335 336
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));

L
lilong12 已提交
337 338 339 340 341 342 343 344 345 346 347
  return Collective(in_tensors, out_tensors,
                    [&](phi::DenseTensor& input, phi::DenseTensor& output,
                        ncclComm_t comm, const gpuStream_t& stream) {
                      const auto root = opts.source_rank * in_tensors.size() +
                                        opts.source_root;
                      return platform::dynload::ncclBroadcast(
                          input.data(), output.data(), input.numel(),
                          platform::ToNCCLDataType(input.type()), root, comm,
                          stream);
                    },
                    CommType::BROADCAST);
348 349
}

B
Baibaifan 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Barrier(
    const BarrierOptions& opts) {
  std::vector<phi::GPUPlace> places;

  if (!opts.place_ids.empty()) {
    for (auto place_id : opts.place_ids) {
      places.emplace_back(place_id);
    }
  } else if (!used_place_ids_.empty()) {
    for (auto place_id : used_place_ids_) {
      places.emplace_back(place_id);
    }
  } else {
    auto numGPUs = GetSize();
    int place_id = static_cast<int>(rank_ % numGPUs);
    places.emplace_back(place_id);
  }

L
lilong12 已提交
368
  std::vector<phi::DenseTensor> barrierTensors;
B
Baibaifan 已提交
369 370 371 372 373
  barrierTensors.reserve(places.size());

  platform::CUDADeviceGuard gpuGuard;
  for (auto& place : places) {
    gpuGuard.SetDeviceIndex(place.GetDeviceId());
374
    auto dt = full({1}, 0, phi::DataType::FLOAT32, phi::GPUPlace());
L
lilong12 已提交
375 376
    barrierTensors.push_back(
        *std::dynamic_pointer_cast<phi::DenseTensor>(dt.impl()));
B
Baibaifan 已提交
377
  }
L
lilong12 已提交
378
  auto task = ProcessGroupNCCL::AllReduce(barrierTensors, barrierTensors);
B
Baibaifan 已提交
379 380 381 382 383
  auto nccl_task = dynamic_cast<ProcessGroupNCCL::NCCLTask*>(task.get());
  nccl_task->barrierTensors_ = std::move(barrierTensors);
  return task;
}

L
lilong12 已提交
384 385
void CheckTensorsInDifferentDevices(
    const std::vector<phi::DenseTensor>& tensors, const size_t num_devices) {
B
Baibaifan 已提交
386 387 388 389 390 391 392 393 394 395 396
  PADDLE_ENFORCE_EQ(
      tensors.size() == 0, false,
      platform::errors::InvalidArgument("Tensor list must be nonempty."));
  PADDLE_ENFORCE_LE(
      tensors.size(), num_devices,
      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) {
L
lilong12 已提交
397
    PADDLE_ENFORCE_EQ(platform::is_gpu_place(t.place()), true,
B
Baibaifan 已提交
398 399 400
                      platform::errors::InvalidArgument(
                          "Tensors must be CUDA and dense tensor."));

401
    const auto inserted = used_devices.insert(t.place()).second;
B
Baibaifan 已提交
402 403 404 405 406 407 408
    PADDLE_ENFORCE_EQ(inserted, true,
                      platform::errors::InvalidArgument(
                          "Tensors must be on distinct GPU devices."));
  }
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Send(
L
lilong12 已提交
409
    std::vector<phi::DenseTensor>& tensors, int dst_rank) {
B
Baibaifan 已提交
410 411
  CheckTensorsInDifferentDevices(tensors, static_cast<size_t>(GetSize()));

L
lilong12 已提交
412 413 414 415 416 417 418 419 420
  auto task = PointToPoint(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);
B
Baibaifan 已提交
421 422 423 424
  return task;
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Recv(
L
lilong12 已提交
425
    std::vector<phi::DenseTensor>& tensors, int src_rank) {
B
Baibaifan 已提交
426 427
  CheckTensorsInDifferentDevices(tensors, static_cast<size_t>(GetSize()));

L
lilong12 已提交
428 429 430 431 432 433 434 435 436
  auto task = PointToPoint(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);
B
Baibaifan 已提交
437 438 439
  return task;
}

440
std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllGather(
L
lilong12 已提交
441 442
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors) {
443 444 445 446 447 448
  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."));
L
lilong12 已提交
449 450 451 452 453 454 455 456 457
  return Collective(in_tensors, out_tensors,
                    [&](const phi::DenseTensor& input, phi::DenseTensor& output,
                        ncclComm_t comm, const gpuStream_t& stream) {
                      return platform::dynload::ncclAllGather(
                          input.data(), output.data(), input.numel(),
                          platform::ToNCCLDataType(input.dtype()), comm,
                          stream);
                    },
                    CommType::ALLGATHER);
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
}

void* GetPointerByOffset(void* raw_pointer, size_t offset,
                         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);
  } 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);
  } else if (type == experimental::DataType::FLOAT16) {
    return reinterpret_cast<void*>(reinterpret_cast<int16_t*>(raw_pointer) +
                                   offset);
  } else {
    PADDLE_THROW(platform::errors::Unimplemented(
        "This datatype in nccl is not supported."));
  }
L
lilong12 已提交
481
  return nullptr;
482 483 484
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::AllToAll(
L
lilong12 已提交
485 486
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors) {
487 488 489 490 491 492 493 494
  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,
L
lilong12 已提交
495
      [&](phi::DenseTensor& input, phi::DenseTensor& output, ncclComm_t comm,
496 497 498 499 500
          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(
L
lilong12 已提交
501 502 503
              GetPointerByOffset(input.data(), offset, input.dtype()),
              input.numel() / size_, platform::ToNCCLDataType(input.dtype()), i,
              comm, stream));
504
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
L
lilong12 已提交
505 506 507 508
              GetPointerByOffset(output.data(), offset, input.dtype()),
              input.numel() / size_, platform::ToNCCLDataType(input.dtype()), i,
              comm, stream));
          offset += input.numel() / size_;
509 510 511 512 513 514 515
        }
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
      },
      CommType::ALLREDUCE);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Reduce(
L
lilong12 已提交
516 517
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors, const ReduceOptions& opts) {
518
  PADDLE_ENFORCE_EQ(
L
lilong12 已提交
519
      CheckTensorsInCudaPlace(in_tensors), true,
520 521
      platform::errors::InvalidArgument("All inputs should be in CudaPlace."));
  return Collective(
L
lilong12 已提交
522 523 524
      in_tensors, out_tensors,
      [&](const phi::DenseTensor& input, phi::DenseTensor& output,
          ncclComm_t comm, const gpuStream_t& stream) {
525
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclReduce(
L
lilong12 已提交
526 527
            input.data(), output.data(), input.numel(),
            platform::ToNCCLDataType(input.dtype()),
528 529 530 531 532 533
            ToNCCLRedType(opts.reduce_op), opts.root_rank, comm, stream));
      },
      CommType::REDUCE);
}

std::shared_ptr<ProcessGroup::Task> ProcessGroupNCCL::Scatter(
L
lilong12 已提交
534 535
    std::vector<phi::DenseTensor>& in_tensors,
    std::vector<phi::DenseTensor>& out_tensors, const ScatterOptions& opts) {
536 537 538 539 540 541 542 543
  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,
L
lilong12 已提交
544
      [&](phi::DenseTensor& input, phi::DenseTensor& output, ncclComm_t comm,
545 546 547 548 549 550
          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(
L
lilong12 已提交
551 552 553 554
                GetPointerByOffset(input.data(), offset, input.dtype()),
                input.numel() / size_, platform::ToNCCLDataType(input.dtype()),
                i, comm, stream));
            offset += input.numel() / size_;
555 556
          }
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
L
lilong12 已提交
557 558
              output.data(), input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()), opts.root_rank, comm,
559 560 561 562
              stream));
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
        } else {
          PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclRecv(
L
lilong12 已提交
563 564
              output.data(), input.numel() / size_,
              platform::ToNCCLDataType(input.dtype()), opts.root_rank, comm,
565 566 567 568 569 570
              stream));
        }
      },
      CommType::SCATTER);
}

571 572
}  //  namespace distributed
}  //  namespace paddle