nccl_gpu_common.cc 2.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
Luo Tao 已提交
2 3 4 5 6 7 8 9 10 11 12 13

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. */
D
Dong Zhihong 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
D
dzhwinter 已提交
16 17

namespace paddle {
X
Xin Pan 已提交
18 19 20 21 22 23 24
namespace platform {
namespace {
// TODO(panyx0718): Where to destroy them.
std::unique_ptr<std::vector<ncclComm_t>> global_comms;
std::unique_ptr<std::unordered_map<int, int>> comm_id_map;
bool inited = false;
size_t last_num_gpus = -1;
X
Xin Pan 已提交
25 26 27
// TODO(panyx0718): Need to decide whether Paddle supports parallel
// runs with different number GPUs. If true, current solution is not enough.
std::mutex comm_mu;
X
Xin Pan 已提交
28 29 30
}

int Communicator::GetCommId(int device_id) const {
X
Xin Pan 已提交
31
  std::lock_guard<std::mutex> guard(comm_mu);
X
Xin Pan 已提交
32 33 34 35
  return comm_id_map->at(device_id);
}

void Communicator::InitAll(const std::vector<int>& gpus) {
X
Xin Pan 已提交
36
  std::lock_guard<std::mutex> guard(comm_mu);
X
Xin Pan 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
  if (inited && last_num_gpus == gpus.size()) {
    return;
  }
  last_num_gpus = gpus.size();
  if (global_comms) {
    for (size_t i = 0; i < global_comms->size(); ++i) {
      // FIXME(dzh) : PADDLE_ENFORCE return void
      dynload::ncclCommDestroy((*global_comms)[i]);
    }
  }
  global_comms.reset(new std::vector<ncclComm_t>());
  comm_id_map.reset(new std::unordered_map<int, int>());
  global_comms->resize(gpus.size());
  for (size_t i = 0; i < gpus.size(); ++i) {
    (*comm_id_map)[gpus[i]] = i;
  }
53
  PADDLE_ENFORCE_CUDA_SUCCESS(
X
Xin Pan 已提交
54 55 56 57 58
      dynload::ncclCommInitAll(global_comms->data(), gpus.size(), gpus.data()));
  inited = true;
}

const std::vector<ncclComm_t>& Communicator::comms() const {
X
Xin Pan 已提交
59
  std::lock_guard<std::mutex> guard(comm_mu);
X
Xin Pan 已提交
60 61 62 63
  return *global_comms;
}

}  // namespace platform
D
dzhwinter 已提交
64
}  // namespace paddle