convolution.cu.h 21.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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. */

#pragma once

17
#include <thrust/binary_search.h>
18 19 20 21 22 23 24 25
#include <thrust/execution_policy.h>
#include <thrust/remove.h>
#include <thrust/sort.h>
#include <thrust/unique.h>

#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/backends/gpu/gpu_info.h"
#include "paddle/phi/backends/gpu/gpu_launch_config.h"
26
#include "paddle/phi/core/tensor_utils.h"
27
#include "paddle/phi/kernels/funcs/index_impl.cu.h"
Z
zhangkaihuo 已提交
28
#include "paddle/phi/kernels/funcs/math_function.h"
29
#include "paddle/phi/kernels/funcs/sparse/utils.cu.h"
Z
zhangkaihuo 已提交
30
#include "paddle/phi/kernels/primitive/compute_primitives.h"
Z
zhangkaihuo 已提交
31
#include "paddle/phi/kernels/sparse/conv_kernel.h"
32 33 34 35

namespace phi {
namespace sparse {

Z
zhangkaihuo 已提交
36 37
using Dims4D = phi::funcs::sparse::Dims4D;

38 39 40 41 42 43 44 45 46 47
// TODO(zhangkaihuo): After the GatherCUDAKernel is migrated to phi, replace
// this kernel with phi::GatherCUDAKernel;
// Vectorization can be used to improve read and write bandwidth
/**
 * brief: gather data from params according to indices
 * params: the inputs
 * indices: the indices you want to gather
 * output: the outputs
 * index_size: the size of indices
 * slice_size: slice size corresponding to each index, here is the channel size
48
 **/
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
template <typename T, typename IndexT = int>
__global__ void GatherKernel(const T* params,
                             const IndexT* indices,
                             T* output,
                             size_t index_size,
                             size_t slice_size) {
  CUDA_KERNEL_LOOP_TYPE(i, index_size * slice_size, int64_t) {
    int64_t indices_i = i / slice_size;
    int64_t slice_i = i - indices_i * slice_size;  // offset inside the slice
    IndexT gather_i = indices[indices_i];
    int64_t params_i = gather_i * slice_size + slice_i;
    *(output + i) = *(params + params_i);
  }
}

64 65 66 67 68 69 70
template <typename Context, typename IntT = int>
inline IntT* SortedAndUniqueIndex(const Context& dev_ctx,
                                  const IntT* rulebook_ptr,
                                  const int len,
                                  DenseTensor* out_index,
                                  DenseTensor* unique_key,
                                  DenseTensor* unique_value) {
71 72 73 74 75
  phi::IndexKernel<int, kps::IdentityFunctor<int>>(
      dev_ctx, out_index, kps::IdentityFunctor<int>());
  phi::IndexKernel<int, kps::IdentityFunctor<int>>(
      dev_ctx, unique_value, kps::IdentityFunctor<int>());

76
  phi::backends::gpu::GpuMemcpyAsync(unique_key->data<IntT>(),
77
                                     rulebook_ptr,
78
                                     sizeof(IntT) * len,
79 80 81 82 83 84 85 86 87 88 89 90 91
#ifdef PADDLE_WITH_HIP
                                     hipMemcpyDeviceToDevice,
#else
                                     cudaMemcpyDeviceToDevice,
#endif
                                     dev_ctx.stream());
// compared with thrust::sort_by_key, thrust::merge_by_key may achieved higher
// performance, but thrust::merge_by_key limited by data size
#ifdef PADDLE_WITH_HIP
  thrust::sort_by_key(thrust::hip::par.on(dev_ctx.stream()),
#else
  thrust::sort_by_key(thrust::cuda::par.on(dev_ctx.stream()),
#endif
92 93
                      unique_key->data<IntT>(),
                      unique_key->data<IntT>() + len,
94 95 96
                      out_index->data<int>());

  // 4. unique
97
  thrust::pair<IntT*, int*> new_end =
98 99 100 101 102
#ifdef PADDLE_WITH_HIP
      thrust::unique_by_key(thrust::hip::par.on(dev_ctx.stream()),
#else
      thrust::unique_by_key(thrust::cuda::par.on(dev_ctx.stream()),
#endif
103 104
                            unique_key->data<IntT>(),
                            unique_key->data<IntT>() + len,
105 106 107 108
                            unique_value->data<int>());
  return new_end.first;
}

Z
zhangkaihuo 已提交
109 110 111 112 113 114 115 116 117
/**
 * @brief: update the out index and indices
 * unique_keys: save the index of the output feature list
 * unique_values: indiates the index of key before deduplication
 * out_indexs: indicates the position of the output index in the rulebook
 * rulebook_len: indicates the length of rulebook
 * out_dims: indicates the output dims
 * out_indices: the indices of output, out_indices = IndexToPoint(unique_keys)
 * rulebook_out_indexs: the output index in rulebook
118
 **/
Z
zhangkaihuo 已提交
119
template <typename T>
120
__global__ void UpdateIndexKernel(const T* unique_keys,
Z
zhangkaihuo 已提交
121 122
                                  const int* unique_values,
                                  const int* out_indexs,
123
                                  const int64_t non_zero_num,
Z
zhangkaihuo 已提交
124 125 126 127 128 129
                                  const int rulebook_len,
                                  const Dims4D out_dims,
                                  T* out_indices,
                                  T* rulebook_out_indexs) {
  int tid = threadIdx.x + blockIdx.x * blockDim.x;
  for (int i = tid; i < non_zero_num; i += gridDim.x * blockDim.x) {
130 131
    const T index = unique_keys[i];
    T batch, x, y, z;
Z
zhangkaihuo 已提交
132 133 134 135 136 137 138 139 140 141 142 143
    phi::funcs::sparse::IndexToPoint<Dims4D>(
        index, out_dims, &batch, &x, &y, &z);
    // get out indices
    out_indices[i] = batch;
    out_indices[i + non_zero_num] = z;
    out_indices[i + non_zero_num * 2] = y;
    out_indices[i + non_zero_num * 3] = x;

    // update rulebook
    int start = unique_values[i];
    int end = i == non_zero_num - 1 ? rulebook_len : unique_values[i + 1];
    // max(end-start) = kernel_size
144
    for (T j = start; j < end; j++) {
Z
zhangkaihuo 已提交
145 146 147 148 149
      rulebook_out_indexs[out_indexs[j]] = i;
    }
  }
}

150 151 152 153 154 155 156 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 183 184 185
template <typename IntT>
__global__ void UpdateOutIndexAndCounterAfterLowerBound(
    const IntT* x_indexs,
    const IntT* bound_out,
    const int rulebook_len,
    const int kernel_size,
    const int64_t non_zero_num,
    IntT* rulebook_ptr,
    IntT* out_indexs,
    int* counter_ptr) {
  extern __shared__ int cache_count[];
  for (int i = threadIdx.x; i < kernel_size; i += blockDim.x) {
    cache_count[i] = 0;
  }
  __syncthreads();

  CUDA_KERNEL_LOOP_TYPE(i, rulebook_len, int64_t) {
    int j = bound_out[i];
    if (j >= 0 && j < non_zero_num && out_indexs[i] == x_indexs[j]) {
      out_indexs[i] = j;
    } else {
      // mask this position will be remove
      int kernel_index = rulebook_ptr[i];
      rulebook_ptr[i + rulebook_len] = -1;
      rulebook_ptr[i + 2 * rulebook_len] = -1;
      rulebook_ptr[i] = -1;
      atomicAdd(&cache_count[kernel_index], 1);
    }
  }
  __syncthreads();

  for (int i = threadIdx.x; i < kernel_size; i += blockDim.x) {
    atomicSub(&counter_ptr[i], cache_count[i]);
  }
}

Z
zhangkaihuo 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
/**
 * @brief product rulebook
 * for input_i in x_indices:
 *   if input_i participate in the convolution calculation:
 *       infer the output_i by input_i and kernel_i
 *       save output_i
 *
 * x_indices: the indices of input features
 * x_dims: the input dims
 * kernel_dims: the kernel dims
 * out_dims: the output dims
 * non_zero_num: the number of input features
 * rulebook: the rulebook to save the kernel index, input index and output index
 * counter: save the number of times each location in the kernel participates in
 *the caculation
201
 **/
Z
zhangkaihuo 已提交
202 203 204 205 206 207 208 209 210 211 212 213
template <typename T>
__global__ void ProductRuleBookKernel(const T* x_indices,
                                      const Dims4D x_dims,
                                      const Dims4D kernel_dims,
                                      const Dims4D out_dims,
                                      const int64_t non_zero_num,
                                      const Dims4D paddings,
                                      const Dims4D dilations,
                                      const Dims4D strides,
                                      const bool subm,
                                      T* rulebook,
                                      int* counter,
214
                                      T* in_indexs) {
Z
zhangkaihuo 已提交
215 216 217 218 219 220 221 222 223 224 225
  int tid = threadIdx.x + blockIdx.x * blockDim.x;
  extern __shared__ int counter_buf[];  // kernel_size
  const int kernel_size = kernel_dims[3] * kernel_dims[2] * kernel_dims[1];
  const int offset = kernel_size * non_zero_num;
  for (int i = threadIdx.x; i < kernel_size; i += blockDim.x) {
    counter_buf[i] = 0;
  }
  __syncthreads();

  for (int i = tid; i < non_zero_num; i += gridDim.x * blockDim.x) {
    int kernel_index = 0;
226 227 228 229
    T batch = x_indices[i];
    T in_z = x_indices[i + non_zero_num];
    T in_y = x_indices[i + 2 * non_zero_num];
    T in_x = x_indices[i + 3 * non_zero_num];
Z
zhangkaihuo 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    if (subm) {
      in_indexs[i] = PointToIndex(batch, in_x, in_y, in_z, x_dims);
    }
    for (int kz = 0; kz < kernel_dims[1]; kz++) {
      for (int ky = 0; ky < kernel_dims[2]; ky++) {
        for (int kx = 0; kx < kernel_dims[3]; kx++) {
          int in_i = -1, out_index = -1, kernel_i = -1;
          if (phi::funcs::sparse::Check(x_dims,
                                        kernel_dims,
                                        paddings,
                                        dilations,
                                        strides,
                                        in_x,
                                        in_y,
                                        in_z,
                                        kx,
                                        ky,
                                        kz)) {
248 249 250
            T out_z = (in_z + paddings[1] - kz * dilations[1]) / strides[1];
            T out_y = (in_y + paddings[2] - ky * dilations[2]) / strides[2];
            T out_x = (in_x + paddings[3] - kx * dilations[3]) / strides[3];
Z
zhangkaihuo 已提交
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
            in_i = i;
            out_index = phi::funcs::sparse::PointToIndex<Dims4D>(
                batch, out_x, out_y, out_z, out_dims);
            atomicAdd(&counter_buf[kernel_index], 1);
            kernel_i = kernel_index;
          }
          rulebook[kernel_index * non_zero_num + i] = kernel_i;
          rulebook[kernel_index * non_zero_num + offset + i] = in_i;
          rulebook[kernel_index * non_zero_num + offset * 2 + i] = out_index;
          ++kernel_index;
        }
      }
    }
  }
  __syncthreads();
  for (int i = threadIdx.x; i < kernel_size; i += blockDim.x) {
    atomicAdd(&counter[i], counter_buf[i]);
  }
}

// the basic algorithm can refer to convolution_kernel.cc or
// the second paper
// example:
// 1. the rulebook:
//  the kernel_index:                       0, 0, 0, 1, 1, 1, 2, 2, ....
//  the out_index(key):                     20, 30, 33, 30, 33, 20, 25
// 2. mark the index of out_index(value):   0, 1, 2, 3, 4, 5, 6, ....
// 3. sorted the (key, value)
// 4. unique the (key, value):
//  unique_key:     20, 25, 30, 33
//  unique_values:  0, 2, 3, 5
//  the index of unique_values is: 0, 1, 2, 3
// 5. update the out_index by unique_key, uniqe_value and the index of
// unique_value:
//  the new out_index: 0, 2, 3, 2, 3, 0, 1
286
template <typename T, typename Context, typename IntT = int>
Z
zhangkaihuo 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
int ProductRuleBook(const Context& dev_ctx,
                    const SparseCooTensor& x,
                    const std::vector<int>& kernel_sizes,
                    const std::vector<int>& paddings,
                    const std::vector<int>& dilations,
                    const std::vector<int>& strides,
                    const DDim& out_dims,
                    const bool subm,
                    DenseTensor* rulebook,
                    DenseTensor* counter_per_kernel,
                    DenseTensor* offsets_per_kernel,
                    DenseTensor* out_index,
                    DenseTensor* unique_value,
                    SparseCooTensor* out,
                    std::vector<int>* h_counter,
                    std::vector<int>* h_offsets) {
303
  auto indices_dtype = paddle::experimental::CppTypeToDataType<IntT>::Type();
Z
zhangkaihuo 已提交
304 305
  const int64_t non_zero_num = x.nnz();
  const auto& non_zero_indices = x.non_zero_indices();
306
  const IntT* indices_ptr = non_zero_indices.data<IntT>();
Z
zhangkaihuo 已提交
307
  DenseTensor in_indexs = phi::Empty<Context>(
308
      dev_ctx, DenseTensorMeta(indices_dtype, {x.nnz()}, DataLayout::NCHW));
Z
zhangkaihuo 已提交
309 310 311 312 313
  int* counter_ptr = counter_per_kernel->data<int>();
  int* offsets_ptr = offsets_per_kernel->data<int>();
  int kernel_size = kernel_sizes[0] * kernel_sizes[1] * kernel_sizes[2];
  const int rulebook_rows = 3;
  const int rulebook_cols = kernel_size * non_zero_num;
314
  DenseTensorMeta rulebook_meta(
315 316 317
      indices_dtype, {rulebook_rows, rulebook_cols}, DataLayout::NCHW);
  *rulebook = phi::Empty(dev_ctx, std::move(rulebook_meta));
  IntT* rulebook_ptr = rulebook->data<IntT>();
Z
zhangkaihuo 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331

  const auto x_dims = x.dims();
  Dims4D d_x_dims(x_dims[0], x_dims[3], x_dims[2], x_dims[1]);
  Dims4D d_kernel_dims(1, kernel_sizes[2], kernel_sizes[1], kernel_sizes[0]);
  Dims4D d_out_dims(out_dims[0], out_dims[3], out_dims[2], out_dims[1]);
  Dims4D d_paddings(1, paddings[2], paddings[1], paddings[0]);
  Dims4D d_strides(1, strides[2], strides[1], strides[0]);
  Dims4D d_dilations(1, dilations[2], dilations[1], dilations[0]);
  // 1. product rule book
  phi::funcs::SetConstant<Context, int> set_zero;
  set_zero(dev_ctx, counter_per_kernel, 0);
  auto config =
      phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, non_zero_num, 1);

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  ProductRuleBookKernel<IntT><<<config.block_per_grid.x,
                                config.thread_per_block.x,
                                kernel_size * sizeof(int),
                                dev_ctx.stream()>>>(indices_ptr,
                                                    d_x_dims,
                                                    d_kernel_dims,
                                                    d_out_dims,
                                                    non_zero_num,
                                                    d_paddings,
                                                    d_dilations,
                                                    d_strides,
                                                    subm,
                                                    rulebook_ptr,
                                                    counter_ptr,
                                                    in_indexs.data<IntT>());
Z
zhangkaihuo 已提交
347 348 349

// 2. remove -1
#ifdef PADDLE_WITH_HIP
350
  IntT* last = thrust::remove(thrust::hip::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
351
#else
352
  IntT* last = thrust::remove(thrust::cuda::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
353
#endif
354 355 356
                              rulebook_ptr,
                              rulebook_ptr + rulebook_rows * rulebook_cols,
                              -1);
Z
zhangkaihuo 已提交
357

358
  phi::funcs::sparse::DistanceKernel<IntT><<<1, 1, 0, dev_ctx.stream()>>>(
Z
zhangkaihuo 已提交
359
      rulebook_ptr, last, rulebook_ptr + 3 * kernel_size * non_zero_num - 1);
360
  IntT rulebook_len = 0;
Z
zhangkaihuo 已提交
361 362 363
  phi::backends::gpu::GpuMemcpyAsync(
      &rulebook_len,
      rulebook_ptr + 3 * kernel_size * non_zero_num - 1,
364
      sizeof(IntT),
Z
zhangkaihuo 已提交
365 366 367 368 369 370 371
#ifdef PADDLE_WITH_HIP
      hipMemcpyDeviceToHost,
#else
      cudaMemcpyDeviceToHost,
#endif
      dev_ctx.stream());
  dev_ctx.Wait();
372
  rulebook_len /= 3;
Z
zhangkaihuo 已提交
373 374 375 376 377 378 379 380

  if (subm) {
    // At present, hashtable is not used to map the input and output indexes.
    // At present, the intermediate output index is generated by normal
    // convolution,
    // and then the intermediate output index is subtracted from the input index
    // to obain the rulebook.

381 382 383 384 385 386 387 388
    // call lower_bound to get the real index of out_index
    const IntT* in_indexs_ptr = in_indexs.data<IntT>();
    IntT* out_indexs_ptr = rulebook_ptr + 2 * rulebook_len;
    DenseTensor bound = phi::Empty(
        dev_ctx,
        DenseTensorMeta(
            indices_dtype, {static_cast<int>(rulebook_len)}, DataLayout::NCHW));
    IntT* bound_ptr = bound.data<IntT>();
Z
zhangkaihuo 已提交
389
#ifdef PADDLE_WITH_HIP
390
    thrust::lower_bound(thrust::hip::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
391
#else
392
    thrust::lower_bound(thrust::cuda::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
393
#endif
394 395 396 397 398 399 400 401 402 403 404 405 406 407
                        in_indexs_ptr,
                        in_indexs_ptr + in_indexs.numel(),
                        out_indexs_ptr,
                        out_indexs_ptr + rulebook_len,
                        bound_ptr);

    config = phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, rulebook_len, 1);

    UpdateOutIndexAndCounterAfterLowerBound<<<config.block_per_grid,
                                              config.thread_per_block,
                                              kernel_size * sizeof(int),
                                              dev_ctx.stream()>>>(
        in_indexs_ptr,
        bound.data<IntT>(),
Z
zhangkaihuo 已提交
408 409
        rulebook_len,
        kernel_size,
410
        x.nnz(),
Z
zhangkaihuo 已提交
411
        rulebook_ptr,
412
        out_indexs_ptr,
Z
zhangkaihuo 已提交
413
        counter_ptr);
414

Z
zhangkaihuo 已提交
415 416
// remove -1
#ifdef PADDLE_WITH_HIP
417
    IntT* last = thrust::remove(thrust::hip::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
418
#else
419
    IntT* last = thrust::remove(thrust::cuda::par.on(dev_ctx.stream()),
Z
zhangkaihuo 已提交
420
#endif
421 422 423
                                rulebook_ptr,
                                rulebook_ptr + 3 * rulebook_len,
                                -1);
424 425
    phi::funcs::sparse::DistanceKernel<IntT>
        <<<1, 1, 0, dev_ctx.stream()>>>(rulebook_ptr, last, bound_ptr);
Z
zhangkaihuo 已提交
426
    phi::backends::gpu::GpuMemcpyAsync(&rulebook_len,
427
                                       bound_ptr,
428
                                       sizeof(IntT),
Z
zhangkaihuo 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
#ifdef PADDLE_WITH_HIP
                                       hipMemcpyDeviceToHost,
#else
                                       cudaMemcpyDeviceToHost,
#endif
                                       dev_ctx.stream());
    dev_ctx.Wait();
    rulebook_len /= 3;
  }

#ifdef PADDLE_WITH_HIP
  thrust::exclusive_scan(thrust::hip::par.on(dev_ctx.stream()),
#else
  thrust::exclusive_scan(thrust::cuda::par.on(dev_ctx.stream()),
#endif
                         counter_ptr,
                         counter_ptr + kernel_size,
                         offsets_ptr);

  phi::backends::gpu::GpuMemcpyAsync(&(*h_counter)[0],
                                     counter_ptr,
                                     kernel_size * sizeof(int),
451
#ifdef PADDLE_WITH_HIP
Z
zhangkaihuo 已提交
452 453 454
                                     hipMemcpyDeviceToHost,
#else
                                     cudaMemcpyDeviceToHost,
455
#endif
Z
zhangkaihuo 已提交
456
                                     dev_ctx.stream());
457

Z
zhangkaihuo 已提交
458 459 460
  phi::backends::gpu::GpuMemcpyAsync(&(*h_offsets)[0],
                                     offsets_ptr,
                                     kernel_size * sizeof(int),
461 462 463
#ifdef PADDLE_WITH_HIP
                                     hipMemcpyDeviceToHost,
#else
Z
zhangkaihuo 已提交
464 465
                                     cudaMemcpyDeviceToHost,
#endif
466 467
                                     dev_ctx.stream());

468
  rulebook->Resize({rulebook_rows, static_cast<int>(rulebook_len)});
Z
zhangkaihuo 已提交
469

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  if (!subm) {
    // 3. sorted or merge the out index
    out_index->ResizeAndAllocate({static_cast<int>(rulebook_len)});
    unique_value->ResizeAndAllocate({static_cast<int>(rulebook_len)});
    DenseTensor unique_key = phi::Empty(
        dev_ctx,
        DenseTensorMeta(
            indices_dtype, {static_cast<int>(rulebook_len)}, DataLayout::NCHW));
    int* out_index_ptr = out_index->data<int>();
    int* unique_value_ptr = unique_value->data<int>();
    IntT* unique_key_ptr = unique_key.data<IntT>();

    IntT* new_end =
        SortedAndUniqueIndex<Context, IntT>(dev_ctx,
                                            rulebook_ptr + 2 * rulebook_len,
                                            rulebook_len,
                                            out_index,
                                            &unique_key,
                                            unique_value);
    // thrust::distance doesn't support stream parameters
    // const int out_non_zero_num = thrust::distance(unique_key_ptr,
    // new_end.first);
492
    phi::funcs::sparse::DistanceKernel<IntT><<<1, 1, 0, dev_ctx.stream()>>>(
493 494 495 496
        unique_key_ptr,
        new_end,
        rulebook_ptr + rulebook_rows * rulebook_cols - 1);
    IntT out_non_zero_num = 0;
Z
zhangkaihuo 已提交
497
#ifdef PADDLE_WITH_HIP
498 499 500 501 502 503
    phi::backends::gpu::GpuMemcpyAsync(
        &out_non_zero_num,
        rulebook_ptr + rulebook_rows * rulebook_cols - 1,
        sizeof(IntT),
        hipMemcpyDeviceToHost,
        dev_ctx.stream());
Z
zhangkaihuo 已提交
504
#else
505 506 507 508 509 510
    phi::backends::gpu::GpuMemcpyAsync(
        &out_non_zero_num,
        rulebook_ptr + rulebook_rows * rulebook_cols - 1,
        sizeof(IntT),
        cudaMemcpyDeviceToHost,
        dev_ctx.stream());
Z
zhangkaihuo 已提交
511
#endif
512
    dev_ctx.Wait();
Z
zhangkaihuo 已提交
513

514 515 516 517
    // 5. update out_indices and rulebook by unique_value_ptr
    const int64_t sparse_dim = 4;
    DenseTensorMeta indices_meta(
        indices_dtype, {sparse_dim, out_non_zero_num}, DataLayout::NCHW);
518 519
    DenseTensorMeta values_meta(
        x.dtype(), {out_non_zero_num, kernel_sizes[4]}, x.values().layout());
520 521 522 523 524 525 526
    phi::DenseTensor out_indices = phi::Empty(dev_ctx, std::move(indices_meta));
    phi::DenseTensor out_values = phi::Empty(dev_ctx, std::move(values_meta));

    IntT* out_indices_ptr = out_indices.data<IntT>();

    config =
        phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, out_non_zero_num, 1);
527 528 529 530 531 532 533 534 535 536 537 538
    UpdateIndexKernel<IntT>
        <<<config.block_per_grid.x,
           config.thread_per_block.x,
           0,
           dev_ctx.stream()>>>(unique_key_ptr,
                               unique_value_ptr,
                               out_index_ptr,
                               out_non_zero_num,
                               rulebook_len,
                               d_out_dims,
                               out_indices_ptr,
                               rulebook_ptr + 2 * rulebook_len);
539 540 541 542
    out->SetMember(out_indices, out_values, out_dims, true);
  } else {
    DenseTensor out_indices =
        phi::EmptyLike<IntT>(dev_ctx, x.non_zero_indices());
543 544 545 546
    DenseTensor out_values = phi::Empty(
        dev_ctx,
        DenseTensorMeta(
            x.dtype(), {x.nnz(), kernel_sizes[4]}, x.values().layout()));
547 548 549 550
    phi::Copy(
        dev_ctx, x.non_zero_indices(), dev_ctx.GetPlace(), false, &out_indices);
    out->SetMember(out_indices, out_values, out_dims, true);
  }
Z
zhangkaihuo 已提交
551 552 553
  return rulebook_len;
}

554 555
}  // namespace sparse
}  // namespace phi