test_sparse_utils_dev_api.cc 35.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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 NCHW KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <gtest/gtest.h>
#include <memory>

18 19 20 21
#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/common/place.h"
#include "paddle/phi/kernels/copy_kernel.h"
#include "paddle/phi/kernels/sparse/sparse_utils_kernel.h"
22

23 24 25
#include "paddle/phi/api/lib/utils/allocator.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/kernel_registry.h"
26

W
Wilber 已提交
27 28
#include "paddle/fluid/memory/allocation/allocator_facade.h"

29
namespace phi {
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
namespace tests {

template <typename ValueT, typename IndicesT>
inline void CheckResult(
    const DeviceContext* dev_ctx,
    const SparseCooTensor& coo,
    const std::vector<ValueT> non_zero_elements,
    const std::vector<IndicesT>& non_zero_indices,
    const int64_t non_zero_num,
    const std::shared_ptr<paddle::experimental::DefaultAllocator>& alloc) {
  const DenseTensor real_indices = coo.non_zero_indices();
  const DenseTensor real_elements = coo.non_zero_elements();
  ASSERT_EQ(coo.nnz(), non_zero_num);

#if defined(PADDLE_WITH_CUDA)
45 46
  if (coo.place() == phi::GPUPlace()) {
    const auto* dev_ctx_gpu = static_cast<const phi::GPUContext*>(dev_ctx);
47 48 49 50 51 52 53 54 55
    DenseTensor indices(
        alloc.get(),
        DenseTensorMeta(
            DataType::INT64, real_indices.dims(), real_indices.layout()));

    DenseTensor elements(alloc.get(),
                         DenseTensorMeta(real_elements.dtype(),
                                         real_elements.dims(),
                                         real_elements.layout()));
56 57
    phi::Copy(*dev_ctx_gpu, real_indices, true, &indices);
    phi::Copy(*dev_ctx_gpu, real_elements, true, &elements);
58 59 60 61 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

    int cmp_indices = memcmp(indices.data<IndicesT>(),
                             non_zero_indices.data(),
                             non_zero_indices.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_indices, 0);
    int cmp_elements = memcmp(elements.data<ValueT>(),
                              non_zero_elements.data(),
                              non_zero_elements.size() * sizeof(ValueT));
    ASSERT_EQ(cmp_elements, 0);
  } else {
#endif
    int cmp_indices = memcmp(real_indices.data<IndicesT>(),
                             non_zero_indices.data(),
                             non_zero_indices.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_indices, 0);
    int cmp_elements = memcmp(real_elements.data<ValueT>(),
                              non_zero_elements.data(),
                              non_zero_elements.size() * sizeof(ValueT));
    ASSERT_EQ(cmp_elements, 0);
#if defined(PADDLE_WITH_CUDA)
  }
#endif
}

template <typename T>
void TestDenseToSparseCoo(const DenseTensor& dense_x,
                          const int64_t sparse_dim,
                          const std::vector<T>& non_zero_data,
                          const std::vector<int64_t>& indices_data,
                          const int64_t non_zero_num) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

91
  phi::CPUContext dev_ctx_cpu;
W
Wilber 已提交
92 93
  dev_ctx_cpu.Init();

94 95 96 97 98 99 100 101 102 103 104 105
  // 1. test cpu
  auto cpu_sparse_out =
      sparse::DenseToSparseCoo<T>(dev_ctx_cpu, dense_x, sparse_dim);
  CheckResult<T, int64_t>(&dev_ctx_cpu,
                          cpu_sparse_out,
                          non_zero_data,
                          indices_data,
                          non_zero_num,
                          alloc);

// 2. test cuda
#if defined(PADDLE_WITH_CUDA)
106
  phi::GPUContext dev_ctx_gpu;
W
Wilber 已提交
107 108 109 110 111 112 113
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
114
          .GetAllocator(phi::CPUPlace())
W
Wilber 已提交
115 116 117
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();

118 119 120 121 122 123 124
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
  DenseTensor d_dense_x(
      cuda_alloc.get(),
      DenseTensorMeta(dense_x.dtype(), dense_x.dims(), dense_x.layout()));

125
  phi::Copy(dev_ctx_gpu, dense_x, true, &d_dense_x);
126
  auto sparse_out =
W
Wilber 已提交
127 128
      sparse::DenseToSparseCoo<T>(dev_ctx_gpu, d_dense_x, sparse_dim);
  CheckResult<T, int64_t>(&dev_ctx_gpu,
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
                          sparse_out,
                          non_zero_data,
                          indices_data,
                          non_zero_num,
                          alloc);
#endif
}

TEST(DEV_API, to_sparse_coo) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  std::default_random_engine random(time(NULL));
  std::uniform_real_distribution<float> dis(0.0, 1.0);
  std::uniform_int_distribution<int> dis_int(4, 64);
  const int rows = dis_int(random), cols = dis_int(random);
  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(DataType::FLOAT32, {rows, cols}, DataLayout::NCHW));

149
  phi::CPUPlace cpu;
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 186 187 188 189 190 191 192 193 194 195
  auto* dense_x_data = dense_x.mutable_data<float>(cpu);
  std::vector<float> dense_data(rows * cols);
  std::vector<float> non_zero_data;
  std::vector<int64_t> rows_data, cols_data;
  const int64_t sparse_dim = 2;

  const float zero_rate = dis(random);

  int64_t non_zero_num = 0;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      bool iszero = dis(random) < zero_rate;
      if (iszero) {
        dense_data[i * cols + j] = 0.0;
      } else {
        float data = dis(random);
        dense_data[i * cols + j] = data;
        non_zero_data.push_back(data);
        rows_data.push_back(i);
        cols_data.push_back(j);
        non_zero_num += 1;
      }
    }
  }

  std::copy(
      dense_data.data(), dense_data.data() + dense_data.size(), dense_x_data);

  std::vector<int64_t> indices_data(non_zero_num * 2);
  memcpy(&indices_data[0], &rows_data[0], non_zero_num * sizeof(int64_t));
  memcpy(&indices_data[non_zero_num],
         &cols_data[0],
         non_zero_num * sizeof(int64_t));

  TestDenseToSparseCoo(
      dense_x, sparse_dim, non_zero_data, indices_data, non_zero_num);
}

TEST(DEV_API, to_sparse_coo_hybird) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(DataType::FLOAT32, {3, 3}, DataLayout::NCHW));

196
  phi::CPUPlace cpu;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  const int64_t sparse_dim = 1;  // the non zero element is a vector
  auto* dense_x_data = dense_x.mutable_data<float>(cpu);
  float dense_data[3][3] = {{0.0, 1.0, 0.0}, {0.0, 0.0, 0.0}, {3.2, 0.0, 0.0}};
  std::vector<float> non_zero_data = {
      /*element0(*/ 0.0, 1.0, 0.0 /*)*/, /*element1(*/ 3.2, 0.0, 0.0 /*)*/};
  std::vector<int64_t> indices_data = {0, 2};
  const int64_t non_zero_num = 2;

  std::copy(&dense_data[0][0], &dense_data[0][0] + 9, dense_x_data);
  TestDenseToSparseCoo(
      dense_x, sparse_dim, non_zero_data, indices_data, non_zero_num);
}

TEST(DEV_API, to_sparse_coo_fp16) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(DataType::FLOAT16, {3, 3}, DataLayout::NCHW));

218
  phi::CPUPlace cpu;
219 220
  const int64_t sparse_dim = 2;
  const int64_t non_zero_num = 2;
221
  auto* dense_x_data = dense_x.mutable_data<phi::dtype::float16>(cpu);
222 223
  float dense_data[3][3] = {{0.0, 1.0, 0.0}, {0.0, 0.0, 0.0}, {3.2, 0.0, 0.0}};
  std::vector<float> data = {1.0, 3.2};
224
  std::vector<phi::dtype::float16> non_zero_data(non_zero_num);
225
  for (int i = 0; i < non_zero_num; i++) {
226
    non_zero_data[i] = static_cast<phi::dtype::float16>(data[i]);
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  }
  std::vector<int64_t> indices_data = {0, 2, 1, 0};

  std::copy(&dense_data[0][0], &dense_data[0][0] + 9, dense_x_data);
  TestDenseToSparseCoo<paddle::float16>(
      dense_x, sparse_dim, non_zero_data, indices_data, non_zero_num);
}

TEST(DEV_API, to_sparse_coo_batch) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(DataType::FLOAT32, {2, 3, 3}, DataLayout::NCHW));

243
  phi::CPUPlace cpu;
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  const int64_t sparse_dim = 3;
  const int64_t non_zero_num = 4;
  auto* dense_x_data = dense_x.mutable_data<float>(cpu);
  float dense_data[2][3][3] = {
      {{0.0, 1.0, 0.0}, {0.0, 0.0, 0.0}, {2.0, 0.0, 0.0}},
      {{0.0, 0.0, 0.0}, {0.0, 3.0, 0.0}, {4.0, 0.0, 0.0}}};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 4.0};
  std::vector<int64_t> indices_data = {0, 0, 1, 1, 0, 2, 1, 2, 1, 0, 1, 0};
  /*
      0, 0, 1, 1,
      0, 2, 1, 2,
      1, 0, 1, 0
   */

  std::copy(&dense_data[0][0][0], &dense_data[0][0][0] + 18, dense_x_data);
  TestDenseToSparseCoo<float>(
      dense_x, sparse_dim, non_zero_data, indices_data, non_zero_num);
}

263 264 265 266 267 268 269 270 271 272 273 274 275
template <typename T>
void TestSparseCsrToCoo(const DDim& dense_dims,
                        const std::vector<T>& non_zero_data,
                        const std::vector<int64_t>& crows_data,
                        const std::vector<int64_t>& cols_data,
                        const std::vector<int64_t>& indices_data,
                        const int64_t non_zero_num) {
  int batchs = 1;
  int rows = dense_dims[0];
  if (dense_dims.size() == 3) {
    batchs = dense_dims[0];
    rows = dense_dims[1];
  }
276
  phi::DenseTensorMeta crows_meta(
277
      DataType::INT64, {batchs * (rows + 1)}, DataLayout::NCHW);
278
  phi::DenseTensorMeta cols_meta(
279
      DataType::INT64, {non_zero_num}, DataLayout::NCHW);
280
  phi::DenseTensorMeta values_meta(
281 282 283 284 285
      paddle::experimental::CppTypeToDataType<T>::Type(),
      {non_zero_num},
      DataLayout::NCHW);
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());
286 287 288 289
  phi::CPUPlace place;
  phi::DenseTensor crows(alloc.get(), crows_meta);
  phi::DenseTensor cols(alloc.get(), cols_meta);
  phi::DenseTensor values(alloc.get(), values_meta);
290 291 292 293 294 295 296 297 298
  memcpy(crows.mutable_data<int64_t>(place),
         crows_data.data(),
         crows_data.size() * sizeof(int64_t));
  memcpy(cols.mutable_data<int64_t>(place),
         cols_data.data(),
         cols_data.size() * sizeof(int64_t));
  memcpy(values.mutable_data<T>(place),
         non_zero_data.data(),
         non_zero_data.size() * sizeof(T));
299
  phi::SparseCsrTensor csr(crows, cols, values, dense_dims);
300 301

  // 1. test cpu
302
  phi::CPUContext dev_ctx_cpu;
303 304 305 306 307 308 309 310 311
  auto cpu_sparse_out = sparse::SparseCsrToCoo<T>(dev_ctx_cpu, csr);
  CheckResult<T, int64_t>(&dev_ctx_cpu,
                          cpu_sparse_out,
                          non_zero_data,
                          indices_data,
                          non_zero_num,
                          alloc);
// 2. test cuda
#if defined(PADDLE_WITH_CUDA)
312
  phi::GPUContext dev_ctx_gpu;
W
Wilber 已提交
313 314 315 316 317 318 319
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
320
          .GetAllocator(phi::CPUPlace())
W
Wilber 已提交
321 322 323
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();

324 325 326
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
327 328 329 330 331 332 333
  phi::DenseTensor d_crows(cuda_alloc.get(), crows_meta);
  phi::DenseTensor d_cols(cuda_alloc.get(), cols_meta);
  phi::DenseTensor d_values(cuda_alloc.get(), values_meta);
  phi::Copy(dev_ctx_gpu, crows, true, &d_crows);
  phi::Copy(dev_ctx_gpu, cols, true, &d_cols);
  phi::Copy(dev_ctx_gpu, values, true, &d_values);
  phi::SparseCsrTensor d_csr(d_crows, d_cols, d_values, dense_dims);
W
Wilber 已提交
334 335
  auto cuda_sparse_out = sparse::SparseCsrToCoo<T>(dev_ctx_gpu, d_csr);
  CheckResult<T, int64_t>(&dev_ctx_gpu,
336 337 338 339 340 341 342 343 344
                          cuda_sparse_out,
                          non_zero_data,
                          indices_data,
                          non_zero_num,
                          alloc);
#endif
}

TEST(DEV_API, sparse_csr_to_coo) {
345
  DDim dense_dims = phi::make_ddim({3, 3});
346 347 348 349 350 351 352 353 354 355 356 357 358 359
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> indices_data = {0, 1, 1, 2, 1, 0, 2, 0};
  std::vector<int64_t> cols_data = {1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4};
  const int64_t non_zero_num = 4;
  TestSparseCsrToCoo(dense_dims,
                     non_zero_data,
                     crows_data,
                     cols_data,
                     indices_data,
                     non_zero_num);
}

TEST(DEV_API, sparse_csr_to_coo_batch_and_fp16) {
360
  DDim dense_dims = phi::make_ddim({2, 3, 3});
361 362 363 364 365 366
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2, 1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> cols_data = {1, 0, 2, 0, 1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4, 0, 1, 3, 4};
  std::vector<int64_t> indices_data = {0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 2,
                                       0, 1, 1, 2, 1, 0, 2, 0, 1, 0, 2, 0};
  const int64_t non_zero_num = 8;
367
  using float16 = phi::dtype::float16;
368 369 370 371 372 373 374 375 376 377 378 379
  std::vector<float16> non_zero_data_fp16(non_zero_num);
  for (int64_t i = 0; i < non_zero_num; i++) {
    non_zero_data_fp16[i] = static_cast<float16>(non_zero_data[i]);
  }
  TestSparseCsrToCoo(dense_dims,
                     non_zero_data_fp16,
                     crows_data,
                     cols_data,
                     indices_data,
                     non_zero_num);
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
template <typename ValueT, typename IndicesT>
inline void CheckCsrResult(
    const DeviceContext* dev_ctx,
    const SparseCsrTensor& csr,
    const std::vector<ValueT> non_zero_elements,
    const std::vector<IndicesT>& non_zero_crows,
    const std::vector<IndicesT>& non_zero_cols,
    const int64_t non_zero_num,
    const std::shared_ptr<paddle::experimental::DefaultAllocator>& alloc) {
  const DenseTensor real_crows = csr.non_zero_crows();
  const DenseTensor real_cols = csr.non_zero_cols();
  const DenseTensor real_elements = csr.non_zero_elements();
  ASSERT_EQ(csr.non_zero_cols().numel(), non_zero_num);

#if defined(PADDLE_WITH_CUDA)
  if (csr.place() == paddle::platform::CUDAPlace()) {
396
    const auto* dev_ctx_gpu = static_cast<const phi::GPUContext*>(dev_ctx);
397 398 399 400 401 402 403 404 405 406 407 408
    DenseTensor crows(
        alloc.get(),
        DenseTensorMeta(
            DataType::INT64, real_crows.dims(), real_crows.layout()));
    DenseTensor cols(
        alloc.get(),
        DenseTensorMeta(DataType::INT64, real_cols.dims(), real_cols.layout()));

    DenseTensor elements(alloc.get(),
                         DenseTensorMeta(real_elements.dtype(),
                                         real_elements.dims(),
                                         real_elements.layout()));
409 410 411
    phi::Copy(*dev_ctx_gpu, real_crows, true, &crows);
    phi::Copy(*dev_ctx_gpu, real_cols, true, &cols);
    phi::Copy(*dev_ctx_gpu, real_elements, true, &elements);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

    int cmp_crows = memcmp(crows.data<IndicesT>(),
                           non_zero_crows.data(),
                           non_zero_crows.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_crows, 0);
    int cmp_cols = memcmp(cols.data<IndicesT>(),
                          non_zero_cols.data(),
                          non_zero_cols.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_cols, 0);
    int cmp_elements = memcmp(elements.data<ValueT>(),
                              non_zero_elements.data(),
                              non_zero_elements.size() * sizeof(ValueT));
    ASSERT_EQ(cmp_elements, 0);
  } else {
#endif
    int cmp_crows = memcmp(real_crows.data<IndicesT>(),
                           non_zero_crows.data(),
                           non_zero_crows.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_crows, 0);
    int cmp_cols = memcmp(real_cols.data<IndicesT>(),
                          non_zero_cols.data(),
                          non_zero_cols.size() * sizeof(IndicesT));
    ASSERT_EQ(cmp_cols, 0);
    int cmp_elements = memcmp(real_elements.data<ValueT>(),
                              non_zero_elements.data(),
                              non_zero_elements.size() * sizeof(ValueT));
    ASSERT_EQ(cmp_elements, 0);
#if defined(PADDLE_WITH_CUDA)
  }
#endif
}

template <typename T>
void TestCooToCsr(const DDim& dense_dims,
                  const int64_t& non_zero_num,
                  const std::vector<T>& non_zero_data,
                  const std::vector<int64_t>& non_zero_indices,
                  const std::vector<int64_t>& cols_data,
                  const std::vector<int64_t>& crows_data) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

454
  phi::CPUPlace cpu;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  DenseTensorMeta indices_meta(
      DataType::INT64,
      {static_cast<int64_t>(dense_dims.size()), non_zero_num},
      DataLayout::NCHW);
  DenseTensor indices(alloc.get(), indices_meta);
  DenseTensorMeta values_meta(
      paddle::experimental::CppTypeToDataType<T>::Type(),
      {non_zero_num},
      DataLayout::NCHW);
  DenseTensor values(alloc.get(), values_meta);

  memcpy(indices.mutable_data<int64_t>(cpu),
         non_zero_indices.data(),
         non_zero_indices.size() * sizeof(int64_t));
  memcpy(values.mutable_data<T>(cpu),
         non_zero_data.data(),
         non_zero_data.size() * sizeof(T));
472
  phi::SparseCooTensor coo(indices, values, dense_dims);
473 474

  // 1. test cpu
475
  phi::CPUContext dev_ctx_cpu;
476 477 478 479 480 481 482 483 484 485 486 487 488 489
  auto cpu_sparse_out = sparse::SparseCooToCsr<T>(dev_ctx_cpu, coo);
  CheckCsrResult<T, int64_t>(&dev_ctx_cpu,
                             cpu_sparse_out,
                             non_zero_data,
                             crows_data,
                             cols_data,
                             non_zero_num,
                             alloc);

// 2. test cuda
#if defined(PADDLE_WITH_CUDA)
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
490
  phi::GPUContext dev_ctx_gpu;
491 492 493 494 495 496 497
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
498
          .GetAllocator(phi::CPUPlace())
499 500
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();
501 502 503 504 505
  phi::DenseTensor d_indices(cuda_alloc.get(), indices_meta);
  phi::DenseTensor d_values(cuda_alloc.get(), values_meta);
  phi::Copy(dev_ctx_gpu, indices, true, &d_indices);
  phi::Copy(dev_ctx_gpu, values, true, &d_values);
  phi::SparseCooTensor d_coo(d_indices, d_values, dense_dims);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  auto cuda_sparse_out = sparse::SparseCooToCsr<T>(dev_ctx_gpu, d_coo);
  CheckCsrResult<T, int64_t>(&dev_ctx_gpu,
                             cuda_sparse_out,
                             non_zero_data,
                             crows_data,
                             cols_data,
                             non_zero_num,
                             alloc);
#endif
}

TEST(DEV_API, coo_to_csr) {
  // float dense_data[3][3] = {{0.0, 1.0, 0.0}, {2.0, 0.0, 3.0}, {3.2, 0.0,
  // 0.0}};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> non_zero_indices = {0, 1, 1, 2, 1, 0, 2, 0};
  std::vector<int64_t> cols_data = {1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4};
  const int64_t non_zero_num = 4;
525
  auto dense_dims = phi::make_ddim({3, 3});
526 527 528 529 530 531 532 533 534 535 536 537 538 539
  TestCooToCsr<float>(dense_dims,
                      non_zero_num,
                      non_zero_data,
                      non_zero_indices,
                      cols_data,
                      crows_data);
}

TEST(DEV_API, batch_coo_to_csr) {
  // float dense_data[2][3][3] =
  //  {{{0.0, 1.0, 0.0}, {2.0, 0.0, 3.0}, {3.2, 0.0, 0.0}},
  //  {{0.0, 1.0, 0.0}, {2.0, 0.0, 3.0}, {0.0, 0.0, 0.0}}};
  const int64_t non_zero_num = 7;
  std::vector<float> data = {1.0, 2.0, 3.0, 3.2, 1.0, 2.0, 3.0};
540
  std::vector<phi::dtype::float16> non_zero_data(non_zero_num);
541
  for (int64_t i = 0; i < non_zero_num; i++) {
542
    non_zero_data[i] = static_cast<phi::dtype::float16>(data[i]);
543 544 545 546 547
  }
  std::vector<int64_t> non_zero_indices = {0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 2,
                                           0, 1, 1, 1, 0, 2, 0, 1, 0, 2};
  std::vector<int64_t> cols_data = {1, 0, 2, 0, 1, 0, 2};
  std::vector<int64_t> crows_data = {0, 1, 3, 4, 0, 1, 3, 3};
548 549 550 551 552 553 554
  auto dense_dims = phi::make_ddim({2, 3, 3});
  TestCooToCsr<phi::dtype::float16>(dense_dims,
                                    non_zero_num,
                                    non_zero_data,
                                    non_zero_indices,
                                    cols_data,
                                    crows_data);
555 556 557 558 559 560 561 562 563 564
}

template <typename T>
void TestDenseToSparseCsr(const DenseTensor& dense_x,
                          const int64_t non_zero_num,
                          const std::vector<T>& non_zero_data,
                          const std::vector<int64_t>& crows_data,
                          const std::vector<int64_t>& cols_data) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());
565
  phi::CPUContext dev_ctx_cpu;
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

  // 1. test cpu
  auto cpu_sparse_out = sparse::DenseToSparseCsr<T>(dev_ctx_cpu, dense_x);
  CheckCsrResult<T, int64_t>(&dev_ctx_cpu,
                             cpu_sparse_out,
                             non_zero_data,
                             crows_data,
                             cols_data,
                             non_zero_num,
                             alloc);
// 2. test cuda
#if defined(PADDLE_WITH_CUDA)
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
  DenseTensor d_dense_x(
      cuda_alloc.get(),
      DenseTensorMeta(dense_x.dtype(), dense_x.dims(), dense_x.layout()));

585
  phi::GPUContext dev_ctx_gpu;
586 587 588 589 590 591 592
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
593
          .GetAllocator(phi::CPUPlace())
594 595
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();
596
  phi::Copy(dev_ctx_gpu, dense_x, true, &d_dense_x);
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
  auto sparse_out = sparse::DenseToSparseCsr<T>(dev_ctx_gpu, d_dense_x);

  CheckCsrResult<T, int64_t>(&dev_ctx_gpu,
                             sparse_out,
                             non_zero_data,
                             crows_data,
                             cols_data,
                             non_zero_num,
                             alloc);
#endif
}

TEST(DEV_API, dense_to_sparse_csr) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(
616
          DataType::FLOAT32, phi::make_ddim({3, 3}), DataLayout::NCHW));
617

618
  phi::CPUPlace cpu;
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  auto* dense_x_data = dense_x.mutable_data<float>(cpu);
  float dense_data[3][3] = {{0.0, 1.0, 0.0}, {2.0, 0.0, 3.0}, {3.2, 0.0, 0.0}};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> cols_data = {1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4};
  const int64_t non_zero_num = 4;

  std::copy(&dense_data[0][0], &dense_data[0][0] + 9, dense_x_data);
  TestDenseToSparseCsr<float>(
      dense_x, non_zero_num, non_zero_data, crows_data, cols_data);
}

TEST(DEV_API, dense_to_sparse_csr_batch) {
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

635 636 637
  DenseTensor dense_x(
      alloc.get(),
      DenseTensorMeta(
638
          DataType::FLOAT16, phi::make_ddim({2, 3, 3}), DataLayout::NCHW));
639

640 641
  phi::CPUPlace cpu;
  auto* dense_x_data = dense_x.mutable_data<phi::dtype::float16>(cpu);
642 643 644 645 646
  const int64_t non_zero_num = 7;
  float dense_data[2][3][3] = {
      {{0.0, 1.0, 0.0}, {2.0, 0.0, 3.0}, {3.2, 0.0, 0.0}},
      {{0.0, 1.0, 0.0}, {2.0, 0.0, 0.0}, {3.2, 0.0, 0.0}}};
  std::vector<float> data = {1.0, 2.0, 3.0, 3.2, 1.0, 2.0, 3.2};
647
  std::vector<phi::dtype::float16> non_zero_data(non_zero_num);
648
  for (int64_t i = 0; i < non_zero_num; i++) {
649
    non_zero_data[i] = static_cast<phi::dtype::float16>(data[i]);
650 651 652 653 654 655
  }
  std::vector<int64_t> cols_data = {1, 0, 2, 0, 1, 0, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4, 0, 1, 2, 3};

  float* dense_ptr = &dense_data[0][0][0];
  for (int i = 0; i < 18; i++) {
656
    dense_x_data[i] = static_cast<phi::dtype::float16>(dense_ptr[i]);
657
  }
658
  TestDenseToSparseCsr<phi::dtype::float16>(
659 660 661
      dense_x, non_zero_num, non_zero_data, crows_data, cols_data);
}

Z
zhangkaihuo 已提交
662 663 664 665 666 667 668
template <typename T>
void TestSparseCooToDense(const DDim& dense_dims,
                          const std::vector<T>& dense_data,
                          const std::vector<T>& non_zero_data,
                          const std::vector<int64_t>& indices_data,
                          const int64_t non_zero_num,
                          const int64_t sparse_dim) {
669
  phi::CPUContext dev_ctx_cpu;
Z
zhangkaihuo 已提交
670 671 672 673 674 675
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

  DenseTensor dense_indices(
      alloc.get(),
      DenseTensorMeta(DataType::INT64,
676
                      phi::make_ddim({sparse_dim, non_zero_num}),
Z
zhangkaihuo 已提交
677 678 679 680 681 682
                      DataLayout::NCHW));
  std::vector<int64_t> dense_elements_vec;
  dense_elements_vec.push_back(non_zero_num);
  for (int64_t i = sparse_dim; i < dense_dims.size(); i++) {
    dense_elements_vec.push_back(dense_dims[i]);
  }
683
  DDim dense_elements_dims = phi::make_ddim(dense_elements_vec);
Z
zhangkaihuo 已提交
684 685 686 687 688 689
  DenseTensor dense_elements(
      alloc.get(),
      DenseTensorMeta(paddle::experimental::CppTypeToDataType<T>::Type(),
                      dense_elements_dims,
                      DataLayout::NCHW));

690
  phi::CPUPlace cpu_place;
Z
zhangkaihuo 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
  memcpy(dense_indices.mutable_data<int64_t>(cpu_place),
         indices_data.data(),
         indices_data.size() * sizeof(int64_t));
  memcpy(dense_elements.mutable_data<T>(cpu_place),
         non_zero_data.data(),
         non_zero_num * sizeof(T));

  SparseCooTensor coo(dense_indices, dense_elements, dense_dims);

  DenseTensor dense_out = sparse::SparseCooToDense<T>(dev_ctx_cpu, coo);

  int cmp = memcmp(
      &dense_data[0], dense_out.data<T>(), sizeof(T) * dense_data.size());
  ASSERT_EQ(cmp, 0);

#if defined(PADDLE_WITH_CUDA)
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
710
  phi::GPUContext dev_ctx_gpu;
Z
zhangkaihuo 已提交
711 712 713 714 715 716 717
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
718
          .GetAllocator(phi::CPUPlace())
Z
zhangkaihuo 已提交
719 720 721 722
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();
  DenseTensor d_dense_indices(cuda_alloc.get(), dense_indices.meta());
  DenseTensor d_dense_elements(cuda_alloc.get(), dense_elements.meta());
723 724
  phi::Copy(dev_ctx_gpu, dense_indices, true, &d_dense_indices);
  phi::Copy(dev_ctx_gpu, dense_elements, true, &d_dense_elements);
Z
zhangkaihuo 已提交
725 726 727 728 729 730 731
  SparseCooTensor coo_cuda(d_dense_indices, d_dense_elements, dense_dims);
  auto dense_out_cuda = sparse::SparseCooToDense<T>(dev_ctx_gpu, coo_cuda);

  DenseTensor h_dense_out(alloc.get(),
                          DenseTensorMeta(dense_out_cuda.dtype(),
                                          dense_out_cuda.dims(),
                                          dense_out_cuda.layout()));
732
  phi::Copy(dev_ctx_gpu, dense_out_cuda, true, &h_dense_out);
Z
zhangkaihuo 已提交
733 734 735 736 737 738 739 740 741 742 743 744
  int cmp_cuda = memcmp(
      &dense_data[0], h_dense_out.data<T>(), sizeof(T) * dense_data.size());
  ASSERT_EQ(cmp_cuda, 0);
#endif
}

TEST(DEV_API, sparse_coo_to_dense) {
  const int non_zero_num = 4;
  const int sparse_dim = 2;
  std::vector<float> dense_data = {0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 3.2, 0.0, 0.0};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> indices_data = {0, 1, 1, 2, 1, 0, 2, 0};
745
  DDim dense_dims = phi::make_ddim({3, 3});
Z
zhangkaihuo 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
  TestSparseCooToDense(dense_dims,
                       dense_data,
                       non_zero_data,
                       indices_data,
                       non_zero_num,
                       sparse_dim);
}

TEST(DEV_API, sparse_coo_to_dense_batch_and_fp16) {
  std::vector<float> dense_data = {0.0,
                                   1.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   2.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   0.0,
                                   3.0,
                                   0.0,
                                   4.0,
                                   0.0,
                                   0.0};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 4.0};
  std::vector<int64_t> indices_data = {0, 0, 1, 1, 0, 2, 1, 2, 1, 0, 1, 0};
  const int non_zero_num = 4;
  const int sparse_dim = 3;
777 778
  DDim dense_dims = phi::make_ddim({2, 3, 3});
  using float16 = phi::dtype::float16;
Z
zhangkaihuo 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
  std::vector<float16> dense_data_fp16(dense_data.size()),
      non_zero_data_fp16(non_zero_num);
  for (uint64_t i = 0; i < dense_data.size(); i++) {
    dense_data_fp16[i] = static_cast<float16>(dense_data[i]);
  }
  for (int64_t i = 0; i < non_zero_num; i++) {
    non_zero_data_fp16[i] = static_cast<float16>(non_zero_data[i]);
  }
  TestSparseCooToDense(dense_dims,
                       dense_data_fp16,
                       non_zero_data_fp16,
                       indices_data,
                       non_zero_num,
                       sparse_dim);
}

template <typename T>
void TestSparseCsrToDense(const DDim& dense_dims,
                          const std::vector<T>& dense_data,
                          const std::vector<T>& non_zero_data,
                          const std::vector<int64_t>& crows_data,
                          const std::vector<int64_t>& cols_data,
                          const int64_t non_zero_num) {
  int batchs = 1;
  int rows = dense_dims[0];
  if (dense_dims.size() == 3) {
    batchs = dense_dims[0];
    rows = dense_dims[1];
  }
808 809 810 811 812
  phi::DenseTensorMeta crows_meta(
      DataType::INT64, phi::make_ddim({batchs * (rows + 1)}), DataLayout::NCHW);
  phi::DenseTensorMeta cols_meta(
      DataType::INT64, phi::make_ddim({non_zero_num}), DataLayout::NCHW);
  phi::DenseTensorMeta values_meta(
Z
zhangkaihuo 已提交
813
      paddle::experimental::CppTypeToDataType<T>::Type(),
814
      phi::make_ddim({non_zero_num}),
Z
zhangkaihuo 已提交
815 816 817 818
      DataLayout::NCHW);
  const auto alloc = std::make_shared<paddle::experimental::DefaultAllocator>(
      paddle::platform::CPUPlace());

819 820 821 822
  phi::CPUPlace place;
  phi::DenseTensor crows(alloc.get(), crows_meta);
  phi::DenseTensor cols(alloc.get(), cols_meta);
  phi::DenseTensor values(alloc.get(), values_meta);
Z
zhangkaihuo 已提交
823 824 825 826 827 828 829 830 831
  memcpy(crows.mutable_data<int64_t>(place),
         crows_data.data(),
         crows_data.size() * sizeof(int64_t));
  memcpy(cols.mutable_data<int64_t>(place),
         cols_data.data(),
         cols_data.size() * sizeof(int64_t));
  memcpy(values.mutable_data<T>(place),
         non_zero_data.data(),
         non_zero_data.size() * sizeof(T));
832
  phi::SparseCsrTensor csr(crows, cols, values, dense_dims);
Z
zhangkaihuo 已提交
833 834

  // 1. test cpu
835
  phi::CPUContext dev_ctx_cpu;
Z
zhangkaihuo 已提交
836 837 838 839 840 841 842 843 844 845 846
  DenseTensor cpu_sparse_out = sparse::SparseCsrToDense<T>(dev_ctx_cpu, csr);
  int cmp_cpu = memcmp(cpu_sparse_out.data<T>(),
                       dense_data.data(),
                       sizeof(T) * dense_data.size());
  ASSERT_EQ(cmp_cpu, 0);

// 2. test cuda
#if defined(PADDLE_WITH_CUDA)
  const auto cuda_alloc =
      std::make_shared<paddle::experimental::DefaultAllocator>(
          paddle::platform::CUDAPlace());
847
  phi::GPUContext dev_ctx_gpu;
Z
zhangkaihuo 已提交
848 849 850 851 852 853 854
  dev_ctx_gpu.PartialInitWithoutAllocator();
  dev_ctx_gpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(dev_ctx_gpu.GetPlace(), dev_ctx_gpu.stream())
          .get());
  dev_ctx_gpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
855
          .GetAllocator(phi::CPUPlace())
Z
zhangkaihuo 已提交
856 857
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();
858 859 860 861 862 863 864
  phi::DenseTensor d_crows(cuda_alloc.get(), crows_meta);
  phi::DenseTensor d_cols(cuda_alloc.get(), cols_meta);
  phi::DenseTensor d_values(cuda_alloc.get(), values_meta);
  phi::Copy(dev_ctx_gpu, crows, true, &d_crows);
  phi::Copy(dev_ctx_gpu, cols, true, &d_cols);
  phi::Copy(dev_ctx_gpu, values, true, &d_values);
  phi::SparseCsrTensor d_csr(d_crows, d_cols, d_values, dense_dims);
Z
zhangkaihuo 已提交
865
  auto cuda_sparse_out = sparse::SparseCsrToDense<T>(dev_ctx_gpu, d_csr);
866 867
  phi::DenseTensor h_out(alloc.get(), cpu_sparse_out.meta());
  phi::Copy(dev_ctx_gpu, cuda_sparse_out, true, &h_out);
Z
zhangkaihuo 已提交
868 869 870 871 872 873 874
  int cmp_cuda =
      memcmp(h_out.data<T>(), dense_data.data(), sizeof(T) * dense_data.size());
  ASSERT_EQ(cmp_cuda, 0);
#endif
}

TEST(DEV_API, sparse_csr_to_dense) {
875
  DDim dense_dims = phi::make_ddim({3, 3});
Z
zhangkaihuo 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  std::vector<float> dense_data = {0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 3.2, 0.0, 0.0};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> cols_data = {1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4};
  const int64_t non_zero_num = 4;

  TestSparseCsrToDense(dense_dims,
                       dense_data,
                       non_zero_data,
                       crows_data,
                       cols_data,
                       non_zero_num);
}

TEST(DEV_API, sparse_csr_to_dense_batch_and_fp16) {
891
  DDim dense_dims = phi::make_ddim({2, 3, 3});
Z
zhangkaihuo 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  std::vector<float> dense_data = {0.0,
                                   1.0,
                                   0.0,
                                   2.0,
                                   0.0,
                                   3.0,
                                   3.2,
                                   0.0,
                                   0.0,
                                   0.0,
                                   1.0,
                                   0.0,
                                   2.0,
                                   0.0,
                                   3.0,
                                   3.2,
                                   0.0,
                                   0.0};
  std::vector<float> non_zero_data = {1.0, 2.0, 3.0, 3.2, 1.0, 2.0, 3.0, 3.2};
  std::vector<int64_t> cols_data = {1, 0, 2, 0, 1, 0, 2, 0};
  std::vector<int64_t> crows_data = {0, 1, 3, 4, 0, 1, 3, 4};
  const int64_t non_zero_num = 8;

915
  using float16 = phi::dtype::float16;
Z
zhangkaihuo 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
  std::vector<float16> dense_data_fp16(dense_data.size()),
      non_zero_data_fp16(non_zero_num);
  for (uint64_t i = 0; i < dense_data.size(); i++) {
    dense_data_fp16[i] = static_cast<float16>(dense_data[i]);
  }
  for (int64_t i = 0; i < non_zero_num; i++) {
    non_zero_data_fp16[i] = static_cast<float16>(non_zero_data[i]);
  }
  TestSparseCsrToDense<float16>(dense_dims,
                                dense_data_fp16,
                                non_zero_data_fp16,
                                crows_data,
                                cols_data,
                                non_zero_num);
}

932
}  // namespace tests
933
}  // namespace phi