class_center_sample_op.cu 22.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//   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
// limitations under the License.

#ifdef PADDLE_WITH_HIP
#include <hiprand.h>
#include <hiprand_kernel.h>
18

19 20 21 22 23 24
#include <hipcub/hipcub.hpp>
typedef hiprandState curandState;
namespace cub = hipcub;
#else
#include <curand.h>
#include <curand_kernel.h>
25

26 27 28 29 30
#include <cub/cub.cuh>
#endif

#include <iterator>
#include <random>
31

32
#include "paddle/fluid/operators/class_center_sample_op.h"
33
#include "paddle/phi/api/include/tensor.h"
34 35

#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
36
#include "paddle/fluid/distributed/collective/ProcessGroup.h"
37
#include "paddle/fluid/platform/collective_helper.h"
38
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
39 40 41 42 43 44 45
#endif

namespace paddle {
namespace operators {
#define CUDA_KERNEL_LOOP(i, n)                            \
  for (int32_t i = blockIdx.x * blockDim.x + threadIdx.x, \
               step = blockDim.x * gridDim.x;             \
46 47
       i < (n);                                           \
       i += step)
48 49 50 51 52 53 54 55 56 57 58 59

using Tensor = framework::Tensor;

static constexpr int kNumCUDAThreads = 512;
static constexpr int kNumMaxinumNumBlocks = 4096;

inline int32_t NumBlocks(const int32_t n) {
  return std::min((n + kNumCUDAThreads - 1) / kNumCUDAThreads,
                  kNumMaxinumNumBlocks);
}

template <typename T>
60 61
__global__ void RandomSampleClassCenter(const int64_t n,
                                        int64_t seed,
62
                                        int64_t increment,
63 64
                                        const int64_t max_val,
                                        T* buffer) {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  const int id = blockIdx.x * blockDim.x + threadIdx.x;
  curandState localState;
  size_t local_seed =
      (static_cast<size_t>(seed) + 0x9E3779B9U +
       (static_cast<size_t>(id) << 6U) + (static_cast<size_t>(id) >> 2U));
#ifdef PADDLE_WITH_HIP
  hiprand_init(local_seed, id, increment, &localState);
  CUDA_KERNEL_LOOP(i, n) {
    buffer[i] = static_cast<T>(hiprand(&localState) % max_val);
  }
#else
  curand_init(local_seed, id, increment, &localState);
  CUDA_KERNEL_LOOP(i, n) {
    buffer[i] = static_cast<T>(curand(&localState) % max_val);
  }
#endif
}

template <typename T>
__global__ void Range(const int64_t n, T* out) {
  CUDA_KERNEL_LOOP(i, n) { out[i] = static_cast<T>(i); }
}

template <typename T>
89 90
__global__ void MarkPositiveClassCenter(const int64_t n,
                                        const int64_t rank,
91
                                        const T* class_interval_ptr,
92 93
                                        const int num_classes,
                                        const T* labels,
94 95 96 97 98 99 100 101 102 103 104
                                        T* out) {
  CUDA_KERNEL_LOOP(i, n) {
    T label = labels[i] - class_interval_ptr[rank];
    if (label >= 0 && label < num_classes) {
      out[label] = label - num_classes;
    }
  }
}

template <typename T>
__device__ void FindIntervalIndex(const T* class_interval_ptr,
105 106
                                  const int64_t nranks,
                                  const T value,
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                                  int64_t* find_index) {
  int64_t start = 0;
  int64_t end = nranks;
  int64_t mid = ((end - start) >> 1) + start + 1;
  while (start < end) {
    if (class_interval_ptr[mid] == value) break;
    if (class_interval_ptr[mid] > value)
      end = mid - 1;
    else
      start = mid;
    mid = ((end - start) >> 1) + start + 1;
  }
  *find_index = min(mid, end);
}

template <typename T>
123 124
__global__ void GetClassCenterBound(const int64_t n,
                                    const int64_t nranks,
125
                                    const T* class_interval_ptr,
126 127 128 129
                                    const T* key_ptr,
                                    const T* value_ptr,
                                    T* bound_index,
                                    T* bound_value) {
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  CUDA_KERNEL_LOOP(i, n) {
    if (i != 0) {
      int64_t cur_index, pre_index;
      FindIntervalIndex(class_interval_ptr, nranks, key_ptr[i], &cur_index);
      FindIntervalIndex(class_interval_ptr, nranks, key_ptr[i - 1], &pre_index);
      if (cur_index > pre_index) {
        assert(cur_index < nranks);
#pragma unroll
        for (int32_t j = pre_index + 1; j <= cur_index; ++j) {
          bound_index[j] = static_cast<T>(i);
          bound_value[j] = value_ptr[i];
        }
      }
    }
  }
  CUDA_KERNEL_LOOP(i, nranks + 1) {
    int64_t first_index, last_index;
    FindIntervalIndex(class_interval_ptr, nranks, key_ptr[0], &first_index);
    FindIntervalIndex(class_interval_ptr, nranks, key_ptr[n - 1], &last_index);
    if (i <= first_index) {
      bound_index[i] = 0;
      bound_value[i] = value_ptr[0];
    } else if (i > last_index) {
      bound_index[i] = n;
      bound_value[i] = value_ptr[n - 1] + 1;
    }
  }
}

template <typename T>
160 161
__global__ void GetRemappedLabel(const int64_t n,
                                 const int64_t nranks,
162
                                 const T* sampled_class_interval_ptr,
163 164 165 166
                                 const T* bound_index,
                                 const T* bound_value,
                                 const T* label_map_key,
                                 T* label_map_value,
167 168 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 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
                                 T* mapped_label) {
  CUDA_KERNEL_LOOP(i, n) {
#pragma unroll
    for (int64_t j = 0; j < nranks; j++) {
      if (i >= bound_index[j] && i < bound_index[j + 1]) {
        label_map_value[i] =
            label_map_value[i] - bound_value[j] + sampled_class_interval_ptr[j];
      }
    }
    mapped_label[label_map_key[i]] = label_map_value[i];
  }
}

// aligned vector generates vectorized load/store on CUDA
template <typename T, int Size>
struct alignas(sizeof(T) * Size) AlignedVector {
  T val[Size];
};

template <typename T>
inline int VectorizedSize(const T* pointer) {
  uint64_t address = reinterpret_cast<uint64_t>(pointer);
  constexpr int vec4 = std::alignment_of<AlignedVector<T, 4>>::value;  // NOLINT
  if (address % vec4 == 0) {
    return 4;
  }
  return 1;
}

#undef CUDA_KERNEL_LOOP

template <typename T>
class NotEqualToPreviousAdjacentIterator {
 public:
  using self_type = NotEqualToPreviousAdjacentIterator;
  using value_type = T;
  using difference_type = std::ptrdiff_t;
  using pointer = T*;
  using reference = T;
  using iterator_category = std::input_iterator_tag;

 public:
  __host__ __device__ __forceinline__
  NotEqualToPreviousAdjacentIterator(const T* arr, int64_t offset)
      : arr_(arr), offset_(offset) {}

  __host__ __device__ __forceinline__ reference operator*() const {
    return offset_ == 0 ? 0 : (arr_[offset_] == arr_[offset_ - 1] ? 0 : 1);
  }

  template <typename Distance>
  __host__ __device__ __forceinline__ self_type operator+(Distance n) const {
    self_type ret(arr_, offset_ + n);
    return ret;
  }

223 224 225 226 227 228
  template <typename Distance>
  __host__ __device__ __forceinline__ self_type operator-(Distance n) const {
    self_type ret(arr_, offset_ - n);
    return ret;
  }

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  template <typename Distance>
  __host__ __device__ __forceinline__ reference operator[](Distance n) const {
    return *(*this + n);
  }

 private:
  const T* arr_;
  int64_t offset_;
};

template <typename T>
struct ActualNumSampledFunctor {
  __host__ __device__ __forceinline__ T operator()(const T& a,
                                                   const T& b) const {
    return max(num_samples, (b - a));
  }
  T num_samples;
  explicit ActualNumSampledFunctor(const T num) : num_samples(num) {}
};

template <typename T>
class MemoryBuffer {
 public:
252 253 254 255
  MemoryBuffer(const int num_buffer_ele,
               const int num_temp_ele,
               const int nranks,
               const platform::Place& place) {
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
    offset1 = 0;
    offset2 = offset1 + num_buffer_ele;
    offset3 = offset2 + num_buffer_ele;
    offset4 = offset3 + num_buffer_ele;
    offset5 = offset4 + num_buffer_ele;
    offset6 = offset5 + (nranks + 1);
    offset7 = offset6 + (nranks + 1);
    offset8 = offset7 + (nranks + 1);
    offset9 = offset8 + num_temp_ele;

    buffer_ptr = buffer.mutable_data<T>(
        {4 * num_buffer_ele + 3 * (nranks + 1) + num_temp_ele}, place);
  }

  T* cub_sort_keys_ptr() { return buffer_ptr + offset1; }
  T* cub_sort_keys_out_ptr() { return buffer_ptr + offset2; }
  T* cub_sort_values_ptr() { return buffer_ptr + offset3; }
  T* cub_sort_values_out_ptr() { return buffer_ptr + offset4; }
  T* bound_index_ptr() { return buffer_ptr + offset5; }
  T* bound_value_ptr() { return buffer_ptr + offset6; }
  T* class_interval_ptr() { return buffer_ptr + offset7; }
  void* cub_temp_storage_ptr() {
    return reinterpret_cast<void*>(buffer_ptr + offset8);
  }

 private:
  Tensor buffer;
  T* buffer_ptr;
  int offset1;
  int offset2;
  int offset3;
  int offset4;
  int offset5;
  int offset6;
  int offset7;
  int offset8;
  int offset9;
};

template <typename DeviceContext, typename T>
class ClassCenterSampleCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* label = ctx.Input<Tensor>("Label");
    auto* remapped_label = ctx.Output<Tensor>("RemappedLabel");
    auto* sampled_local_class_center =
        ctx.Output<Tensor>("SampledLocalClassCenter");
    int num_classes = ctx.Attr<int>("num_classes");
    int num_samples = ctx.Attr<int>("num_samples");

    int rid = ctx.Attr<int>("ring_id");
    int nranks = ctx.Attr<int>("nranks");
    int rank = ctx.Attr<int>("rank");

    int seed = ctx.Attr<int>("seed");
    bool fix_seed = ctx.Attr<bool>("fix_seed");
312 313
    PADDLE_ENFORCE_GT(num_classes,
                      0,
314 315 316 317 318 319
                      platform::errors::InvalidArgument(
                          "The value 'num_classes' for Op(class_center_sample) "
                          "must be greater than 0, "
                          "but the value given is %d.",
                          num_classes));

320 321
    PADDLE_ENFORCE_GT(num_samples,
                      0,
322 323 324 325 326 327
                      platform::errors::InvalidArgument(
                          "The value 'num_samples' for Op(class_center_sample) "
                          "must be greater than 0, "
                          "but the value given is %d.",
                          num_samples));

328 329
    PADDLE_ENFORCE_LE(num_samples,
                      num_classes,
330 331 332 333
                      platform::errors::InvalidArgument(
                          "The value 'num_samples' for Op(class_center_sample) "
                          "must be less than or equal to %d, "
                          "but the value given is %d.",
334 335
                          num_classes,
                          num_samples));
336 337

    auto& dev_ctx = ctx.template device_context<DeviceContext>();
338
    auto place = dev_ctx.GetPlace();
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

    int batch_size = label->numel();
    // Algorithm:
    // We first randomly generate a value in [0, num_classes) on each position
    // in a array(shape[num_classes]). Then, we mark the element as negative
    // value in the array according input label. Now, we can sort the array
    // by ascending to ensure that the positive class center always in the
    // front of the sorted array. So, we can get the sampled class center
    // index by sorted keys. Finally, we can get the rempped label by remap
    // the input label according sampled class center.

    // step 1: Calculate num classes per device using nccl all reduce
    std::vector<T> shard_dim_vec(nranks + 1, 0);
    shard_dim_vec[rank + 1] = num_classes;
    Tensor num_classes_per_device;
354 355
    framework::TensorFromVector(
        shard_dim_vec, ctx.cuda_device_context(), &num_classes_per_device);
356 357 358 359
    T* num_classes_per_device_ptr = num_classes_per_device.data<T>();

#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
    if (nranks > 1) {
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
      auto map = distributed::ProcessGroupMapFromGid::getInstance();
      if (map->has(rid)) {
        // Use ProcessGroup
        distributed::ProcessGroup* pg = map->get(rid);
        std::vector<phi::DenseTensor> in_tensor;
        std::vector<phi::DenseTensor> out_tensor;
        in_tensor.push_back(num_classes_per_device);
        out_tensor.push_back(num_classes_per_device);

        distributed::AllreduceOptions opts;
        opts.reduce_op = distributed::ReduceOp::SUM;
        auto task = pg->AllReduce(in_tensor, out_tensor, opts);
        task->Wait();
      } else {
        const auto& comm =
            platform::NCCLCommContext::Instance().Get(rid, ctx.GetPlace());
        // use global calculate stream
        const auto calcu_stream =
            static_cast<platform::CUDADeviceContext*>(
                platform::DeviceContextPool::Instance().Get(ctx.GetPlace()))
                ->stream();
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclAllReduce(
382 383
            num_classes_per_device_ptr,
            num_classes_per_device_ptr,
384 385 386
            num_classes_per_device.numel(),
            platform::ToNCCLDataType(
                framework::TransToProtoVarType(num_classes_per_device.dtype())),
387 388 389
            ncclSum,
            comm->comm(),
            calcu_stream));
390
      }
391 392 393 394 395 396
    }
#endif

    // step 2: Determine temporary device storage requirements
    int num_buffer_ele = std::max(batch_size, num_classes);
    size_t cub_sort_temp_store_size = 0;
397
    PADDLE_ENFORCE_GPU_SUCCESS((cub::DeviceRadixSort::SortPairs<T, T>(
398 399 400 401 402 403 404 405 406 407
        nullptr,
        cub_sort_temp_store_size,
        nullptr,
        nullptr,
        nullptr,
        nullptr,
        num_buffer_ele,
        0,
        sizeof(T) * 8,
        ctx.cuda_device_context().stream())));
408 409 410

    size_t cub_sum_temp_store_size = 0;
    NotEqualToPreviousAdjacentIterator<T> unique_counting_iter_temp(nullptr, 0);
411 412 413 414 415 416 417 418
    PADDLE_ENFORCE_GPU_SUCCESS((
        cub::DeviceScan::InclusiveSum<NotEqualToPreviousAdjacentIterator<T>,
                                      T*>(nullptr,
                                          cub_sum_temp_store_size,
                                          unique_counting_iter_temp,
                                          nullptr,
                                          batch_size,
                                          ctx.cuda_device_context().stream())));
419 420 421

    size_t cub_scan_temp_store_size = 0;
    ActualNumSampledFunctor<T> actual_num_sampled_op_temp(num_samples);
422 423 424 425 426 427 428 429
    PADDLE_ENFORCE_GPU_SUCCESS(
        (cub::DeviceScan::InclusiveScan(nullptr,
                                        cub_scan_temp_store_size,
                                        num_classes_per_device_ptr,
                                        num_classes_per_device_ptr,
                                        actual_num_sampled_op_temp,
                                        nranks + 1,
                                        ctx.cuda_device_context().stream())));
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

    size_t cub_temp_storage_bytes =
        std::max(std::max(cub_sort_temp_store_size, cub_scan_temp_store_size),
                 cub_sum_temp_store_size);
    int num_temp_ele = cub_temp_storage_bytes / sizeof(T) + 1;

    // step 3: Alloc buffer memory so that we can reuse allocated memory
    MemoryBuffer<T> memory_buffer =
        MemoryBuffer<T>(num_buffer_ele, num_temp_ele, nranks, ctx.GetPlace());

    T* cub_sort_keys_ptr = memory_buffer.cub_sort_keys_ptr();
    T* cub_sort_keys_out_ptr = memory_buffer.cub_sort_keys_out_ptr();
    T* cub_sort_values_ptr = memory_buffer.cub_sort_values_ptr();
    T* cub_sort_values_out_ptr = memory_buffer.cub_sort_values_out_ptr();
    T* bound_index_ptr = memory_buffer.bound_index_ptr();
    T* bound_value_ptr = memory_buffer.bound_value_ptr();
    T* class_interval_ptr = memory_buffer.class_interval_ptr();
    void* cub_temp_storage_ptr = memory_buffer.cub_temp_storage_ptr();

    // step 4: Calculate class interval among nranks
450 451 452 453 454 455 456
    PADDLE_ENFORCE_GPU_SUCCESS(
        (cub::DeviceScan::InclusiveSum(cub_temp_storage_ptr,
                                       cub_temp_storage_bytes,
                                       num_classes_per_device_ptr,
                                       class_interval_ptr,
                                       nranks + 1,
                                       ctx.cuda_device_context().stream())));
457 458

    // step 5: random sample negative class center
459 460
    uint64_t seed_data;
    uint64_t increment;
461
    int vec_size = VectorizedSize<T>(cub_sort_keys_ptr);
462 463 464 465
    auto offset = ((num_classes - 1) /
                       (NumBlocks(num_classes) * kNumCUDAThreads * vec_size) +
                   1) *
                  vec_size;
466
    int device_id = ctx.GetPlace().GetDeviceId();
467 468
    auto gen_cuda = framework::DefaultCUDAGenerator(device_id);
    if (!fix_seed) {
469 470 471 472
      auto seed_offset = gen_cuda->IncrementOffset(offset);
      seed_data = seed_offset.first;
      increment = seed_offset.second;
    } else {
473
      seed_data = seed + rank;
474
      increment = offset;
475
    }
476 477 478
    RandomSampleClassCenter<T><<<NumBlocks(num_classes),
                                 kNumCUDAThreads,
                                 0,
479
                                 ctx.cuda_device_context().stream()>>>(
480
        num_classes, seed_data, increment, num_classes, cub_sort_keys_ptr);
481 482 483

    // step 6: mark positive class center as negative value
    // fill the sort values to index 0, 1, ..., batch_size-1
484 485 486
    MarkPositiveClassCenter<<<NumBlocks(batch_size),
                              kNumCUDAThreads,
                              0,
487
                              ctx.cuda_device_context().stream()>>>(
488 489 490 491 492
        batch_size,
        rank,
        class_interval_ptr,
        num_classes,
        label->data<T>(),
493
        cub_sort_keys_ptr);
494 495 496
    Range<T><<<NumBlocks(num_buffer_ele),
               kNumCUDAThreads,
               0,
497 498 499 500 501
               ctx.cuda_device_context().stream()>>>(num_buffer_ele,
                                                     cub_sort_values_ptr);

    // step 7: sort class center by ascending, so that positive class center
    // always be sampled.
502
    PADDLE_ENFORCE_GPU_SUCCESS((cub::DeviceRadixSort::SortPairs<T, T>(
503 504 505 506 507 508 509 510 511 512
        cub_temp_storage_ptr,
        cub_temp_storage_bytes,
        cub_sort_keys_ptr,
        cub_sort_keys_out_ptr,
        cub_sort_values_ptr,
        cub_sort_values_out_ptr,
        num_classes,
        0,
        sizeof(T) * 8,
        ctx.cuda_device_context().stream())));
513 514

    // step 8: sort input label ascending
515
    PADDLE_ENFORCE_GPU_SUCCESS((cub::DeviceRadixSort::SortPairs<T, T>(
516 517 518 519 520 521 522 523 524 525
        cub_temp_storage_ptr,
        cub_temp_storage_bytes,
        label->data<T>(),
        cub_sort_keys_out_ptr,
        cub_sort_values_ptr,
        cub_sort_keys_ptr,
        batch_size,
        0,
        sizeof(T) * 8,
        ctx.cuda_device_context().stream())));
526 527 528 529 530

    // step 9: Calculate new index using InclusiveSum on ascending sorted input
    // label
    NotEqualToPreviousAdjacentIterator<T> unique_counting_iter(
        cub_sort_keys_out_ptr, 0);
531 532 533 534 535 536 537 538
    PADDLE_ENFORCE_GPU_SUCCESS((
        cub::DeviceScan::InclusiveSum<NotEqualToPreviousAdjacentIterator<T>,
                                      T*>(cub_temp_storage_ptr,
                                          cub_temp_storage_bytes,
                                          unique_counting_iter,
                                          cub_sort_values_ptr,
                                          batch_size,
                                          ctx.cuda_device_context().stream())));
539 540

    // step 10: Calculate new class center bound among ranks
541 542 543 544 545 546 547 548 549 550 551
    GetClassCenterBound<T>
        <<<NumBlocks(batch_size),
           kNumCUDAThreads,
           0,
           ctx.cuda_device_context().stream()>>>(batch_size,
                                                 nranks,
                                                 class_interval_ptr,
                                                 cub_sort_keys_out_ptr,
                                                 cub_sort_values_ptr,
                                                 bound_index_ptr,
                                                 bound_value_ptr);
552 553 554 555 556

    // step 11: Calculate actual number of sampled class per device.
    // Since maybe num_positive_class_center > num_samples,
    // we need to ensure all positive class center per device are sampled.
    ActualNumSampledFunctor<T> actual_num_sampled_op(num_samples);
557 558 559 560 561 562 563 564
    PADDLE_ENFORCE_GPU_SUCCESS(
        (cub::DeviceScan::InclusiveScan(cub_temp_storage_ptr,
                                        cub_temp_storage_bytes,
                                        bound_value_ptr,
                                        num_classes_per_device_ptr,
                                        actual_num_sampled_op,
                                        nranks + 1,
                                        ctx.cuda_device_context().stream())));
565 566

    // step 12: Calculate actual sampled class interval among nranks
567 568 569 570 571 572 573
    PADDLE_ENFORCE_GPU_SUCCESS(
        (cub::DeviceScan::InclusiveSum(cub_temp_storage_ptr,
                                       cub_temp_storage_bytes,
                                       num_classes_per_device_ptr,
                                       class_interval_ptr,
                                       nranks + 1,
                                       ctx.cuda_device_context().stream())));
574 575

    // step 13: Get remapped label for output
576 577 578
    GetRemappedLabel<T><<<NumBlocks(batch_size),
                          kNumCUDAThreads,
                          0,
579
                          ctx.cuda_device_context().stream()>>>(
580 581 582 583 584 585 586
        batch_size,
        nranks,
        class_interval_ptr,
        bound_index_ptr,
        bound_value_ptr,
        cub_sort_keys_ptr,
        cub_sort_values_ptr,
587 588 589
        remapped_label->mutable_data<T>(ctx.GetPlace()));

    // step 14: Get sampled class center for output
590 591
    framework::TensorCopySync(
        num_classes_per_device, platform::CPUPlace(), &num_classes_per_device);
592 593 594 595
    T actual_num_samples = num_classes_per_device.data<T>()[rank + 1];
    T* sampled_local_class_center_ptr =
        sampled_local_class_center->mutable_data<T>({actual_num_samples},
                                                    ctx.GetPlace());
596 597 598 599 600
    memory::Copy(place,
                 sampled_local_class_center_ptr,
                 place,
                 cub_sort_values_out_ptr,
                 actual_num_samples * sizeof(T),
601 602 603 604 605 606 607 608 609 610 611 612
                 nullptr);
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_CUDA_KERNEL(
    class_center_sample,
    ops::ClassCenterSampleCUDAKernel<paddle::platform::CUDADeviceContext,
                                     int64_t>,
    ops::ClassCenterSampleCUDAKernel<paddle::platform::CUDADeviceContext, int>);