global_gather_op.cu.cc 10.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* Copyright (c) 2021 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
13
limitations under the License. */
14 15 16

#include "paddle/fluid/operators/collective/global_gather_op.h"

17
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
18
#include "paddle/fluid/platform/collective_helper.h"
19
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
20
#endif
21
#include "paddle/fluid/framework/convert_utils.h"
22 23 24

namespace paddle {
namespace operators {
25

26
template <typename T>
27 28
struct GlobalGatherFunctor<phi::GPUContext, T> {
  void operator()(const framework::ExecutionContext& ctx) {
29
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
30 31 32 33
#if NCCL_VERSION_CODE >= 2703
    auto x = ctx.Input<framework::LoDTensor>("X");
    auto local_count = ctx.Input<framework::LoDTensor>("local_count");
    auto global_count = ctx.Input<framework::LoDTensor>("global_count");
34 35 36 37
    auto local_count_type =
        framework::TransToProtoVarType(local_count->dtype());
    auto global_count_type =
        framework::TransToProtoVarType(global_count->dtype());
38 39 40 41 42 43 44 45 46 47 48 49 50
    if (local_count_type != framework::proto::VarType::INT64) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Please use int64 type in local_count."));
    }
    if (global_count_type != framework::proto::VarType::INT64) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Please use int64 type in global_count."));
    }
    auto out = ctx.Output<framework::LoDTensor>("Out");
    const int64_t* cpu_local_count_data;
    const int64_t* cpu_global_count_data;
    auto local_count_len = 0;

51
    phi::DenseTensor cpu_local_count;
52 53 54 55
    if (platform::is_cpu_place(local_count->place())) {
      cpu_local_count_data = local_count->data<int64_t>();
      local_count_len = local_count->numel();
    } else {
56 57
      framework::TensorCopySync(
          *local_count, platform::CPUPlace(), &cpu_local_count);
58 59 60 61
      cpu_local_count_data = cpu_local_count.data<int64_t>();
      local_count_len = cpu_local_count.numel();
    }

62
    phi::DenseTensor cpu_global_count;
63 64 65
    if (platform::is_cpu_place(global_count->place())) {
      cpu_global_count_data = global_count->data<int64_t>();
    } else {
66 67
      framework::TensorCopySync(
          *global_count, platform::CPUPlace(), &cpu_global_count);
68 69 70
      cpu_global_count_data = cpu_global_count.data<int64_t>();
    }

71 72
    ncclDataType_t dtype =
        platform::ToNCCLDataType(framework::TransToProtoVarType(x->dtype()));
73 74 75

    int ring_id = ctx.Attr<int>("ring_id");
    PADDLE_ENFORCE_GE(
76 77
        ring_id,
        0,
78 79 80 81 82
        platform::errors::InvalidArgument(
            "The ring_id (%d) for global gather op must be non-negative.",
            ring_id));
    auto place = ctx.GetPlace();
    auto comm = platform::NCCLCommContext::Instance().Get(ring_id, place);
83
    gpuStream_t stream = nullptr;
84 85
    if (ctx.Attr<bool>("use_calc_stream")) {
      auto dev_ctx = platform::DeviceContextPool::Instance().Get(place);
L
Leo Chen 已提交
86
      stream = static_cast<phi::GPUContext*>(dev_ctx)->stream();
87 88 89 90 91 92 93 94 95 96 97 98
    } else {
      stream = comm->stream();
    }
    int nranks = comm->nranks();
    auto in_feat = x->dims()[1];
    auto n_expert = local_count->dims()[0] / nranks;

    auto fwd_count = 0;

    for (auto i = 0; i < local_count_len; ++i) {
      fwd_count += cpu_local_count_data[i];
    }
99
    framework::DDim out_dims = phi::make_ddim({fwd_count, in_feat});
100 101 102 103 104 105 106 107 108
    int64_t* expert_ptr = new int64_t[n_expert * nranks];
    expert_ptr[0] = 0;
    auto tot_experts = n_expert * nranks;
    for (auto i = 1; i < tot_experts; ++i) {
      expert_ptr[i] = expert_ptr[i - 1] + cpu_local_count_data[i - 1];
    }
    auto send_ptr = 0;
    auto send_buf = x->data<T>();
    auto recv_buf = out->mutable_data<T>(out_dims, place);
109

110
    for (auto i = 0; i < n_expert; ++i) {
111
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
112 113 114
      for (auto j = 0; j < nranks; ++j) {
        int idx = i + j * n_expert;
        if (cpu_global_count_data[idx]) {
115
          PADDLE_ENFORCE_GPU_SUCCESS(
116 117
              platform::dynload::ncclSend(send_buf + send_ptr * in_feat,
                                          cpu_global_count_data[idx] * in_feat,
118 119 120 121
                                          dtype,
                                          j,
                                          comm->comm(),
                                          stream));
122 123 124
          send_ptr += cpu_global_count_data[idx];
        }
        if (cpu_local_count_data[idx]) {
125
          PADDLE_ENFORCE_GPU_SUCCESS(
126 127
              platform::dynload::ncclRecv(recv_buf + expert_ptr[idx] * in_feat,
                                          cpu_local_count_data[idx] * in_feat,
128 129 130 131
                                          dtype,
                                          j,
                                          comm->comm(),
                                          stream));
132 133
        }
      }
134
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
135 136 137 138 139 140 141 142 143 144 145 146
    }
#else
    PADDLE_THROW(
        platform::errors::Unavailable("NCCL version >= 2.7.3 is needed."));
#endif
#else
    PADDLE_THROW(
        platform::errors::Unavailable("PaddlePaddle should compile with GPU."));
#endif
  }
};

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
template <typename T>
struct GlobalGatherProcessGroupFunctor<phi::GPUContext, T> {
  void operator()(const framework::ExecutionContext& ctx) {
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#if NCCL_VERSION_CODE >= 2703
    auto x = ctx.Input<framework::LoDTensor>("X");
    auto local_count = ctx.Input<framework::LoDTensor>("local_count");
    auto global_count = ctx.Input<framework::LoDTensor>("global_count");
    auto local_count_type =
        framework::TransToProtoVarType(local_count->dtype());
    auto global_count_type =
        framework::TransToProtoVarType(global_count->dtype());
    if (local_count_type != framework::proto::VarType::INT64) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Please use int64 type in local_count."));
    }
    if (global_count_type != framework::proto::VarType::INT64) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Please use int64 type in global_count."));
    }
    auto out = ctx.Output<framework::LoDTensor>("Out");
    const int64_t* cpu_local_count_data;
    const int64_t* cpu_global_count_data;
    auto local_count_len = 0;

172
    phi::DenseTensor cpu_local_count;
173 174 175 176
    if (platform::is_cpu_place(local_count->place())) {
      cpu_local_count_data = local_count->data<int64_t>();
      local_count_len = local_count->numel();
    } else {
177 178
      framework::TensorCopySync(
          *local_count, platform::CPUPlace(), &cpu_local_count);
179 180 181 182
      cpu_local_count_data = cpu_local_count.data<int64_t>();
      local_count_len = cpu_local_count.numel();
    }

183
    phi::DenseTensor cpu_global_count;
184 185 186
    if (platform::is_cpu_place(global_count->place())) {
      cpu_global_count_data = global_count->data<int64_t>();
    } else {
187 188
      framework::TensorCopySync(
          *global_count, platform::CPUPlace(), &cpu_global_count);
189 190 191 192 193
      cpu_global_count_data = cpu_global_count.data<int64_t>();
    }

    int ring_id = ctx.Attr<int>("ring_id");
    PADDLE_ENFORCE_GE(
194 195
        ring_id,
        0,
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        platform::errors::InvalidArgument(
            "The ring_id (%d) for global gather op must be non-negative.",
            ring_id));
    auto place = ctx.GetPlace();

    auto map = distributed::ProcessGroupMapFromGid::getInstance();
    distributed::ProcessGroup* pg = map->get(ring_id);

    int nranks = pg->GetSize();
    auto in_feat = x->dims()[1];
    auto n_expert = local_count->dims()[0] / nranks;

    auto fwd_count = 0;

    for (auto i = 0; i < local_count_len; ++i) {
      fwd_count += cpu_local_count_data[i];
    }
    framework::DDim out_dims = phi::make_ddim({fwd_count, in_feat});
    int64_t* expert_ptr = new int64_t[n_expert * nranks];
    expert_ptr[0] = 0;
    auto tot_experts = n_expert * nranks;
    for (auto i = 1; i < tot_experts; ++i) {
      expert_ptr[i] = expert_ptr[i - 1] + cpu_local_count_data[i - 1];
    }
    auto send_ptr = 0;
    out->mutable_data<T>(out_dims, place);

    for (auto i = 0; i < n_expert; ++i) {
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupStart());
      for (auto j = 0; j < nranks; ++j) {
        int idx = i + j * n_expert;
        if (cpu_global_count_data[idx]) {
          phi::DenseTensor tmp = *x;
229 230
          pg->Send_Partial(
              tmp, j, send_ptr * in_feat, cpu_global_count_data[idx] * in_feat);
231 232 233
          send_ptr += cpu_global_count_data[idx];
        }
        if (cpu_local_count_data[idx]) {
234 235 236
          pg->Recv_Partial(*out,
                           j,
                           expert_ptr[idx] * in_feat,
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
                           cpu_local_count_data[idx] * in_feat);
        }
      }
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGroupEnd());
    }

#ifdef PADDLE_WITH_CUDA
    PADDLE_ENFORCE_GPU_SUCCESS(cudaDeviceSynchronize());
#else
    PADDLE_ENFORCE_GPU_SUCCESS(hipDeviceSynchronize());
#endif

#else
    PADDLE_THROW(
        platform::errors::Unavailable("NCCL version >= 2.7.3 is needed."));
#endif
#else
    PADDLE_THROW(
        platform::errors::Unavailable("PaddlePaddle should compile with GPU."));
#endif
  }
};

template <typename T>
class GlobalGatherOpCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const int rid = ctx.Attr<int>("ring_id");
    auto map = distributed::ProcessGroupMapFromGid::getInstance();
    if (map->has(rid)) {
      GlobalGatherProcessGroupFunctor<phi::GPUContext, T> functor_;
      functor_(ctx);
    } else {
      GlobalGatherFunctor<phi::GPUContext, T> functor_;
      functor_(ctx);
    }
  }
};

276 277 278 279 280 281
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

282 283
REGISTER_OP_CUDA_KERNEL(global_gather,
                        ops::GlobalGatherOpCUDAKernel<float>,
284 285 286 287
                        ops::GlobalGatherOpCUDAKernel<double>,
                        ops::GlobalGatherOpCUDAKernel<int>,
                        ops::GlobalGatherOpCUDAKernel<int64_t>,
                        ops::GlobalGatherOpCUDAKernel<plat::float16>);