test_sparse_pool_dev_api.cc 13.7 KB
Newer Older
Z
zhangkaihuo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/* 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. */

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

#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_pool_grad_kernel.h"
#include "paddle/phi/kernels/sparse/sparse_pool_kernel.h"

#include "paddle/fluid/memory/allocation/allocator_facade.h"
#include "paddle/phi/api/lib/utils/allocator.h"
#include "paddle/phi/core/kernel_registry.h"

namespace phi {
namespace tests {

template <typename T1, typename T2>
std::vector<T2> cast(const std::vector<T1>& in) {
  std::vector<T2> out(in.size());
  for (uint64_t i = 0; i < in.size(); i++) {
    out[i] = static_cast<T2>(in[i]);
  }
  return out;
}
template <typename T>
void TestMaxPoolBase(const std::vector<int>& indices,
                     const std::vector<T>& features,
                     const DDim& x_dims,
                     const std::vector<int>& correct_out_indices,
                     const std::vector<T>& correct_out_features,
                     const DDim& correct_out_dims,
                     const int non_zero_num,
                     const std::vector<int>& kernel_sizes,
                     const std::vector<int>& paddings,
                     const std::vector<int>& strides,
                     const std::vector<int>& dilations,
                     const float diff = 1e-3,
                     const bool backward = false,
                     const std::vector<T> features_grad = {}) {
  phi::CPUContext dev_ctx_cpu;
  dev_ctx_cpu.SetAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(paddle::platform::CPUPlace())
          .get());
59 60 61 62
  dev_ctx_cpu.SetHostAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(phi::CPUPlace())
          .get());
Z
zhangkaihuo 已提交
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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  dev_ctx_cpu.Init();

  const int in_channels = x_dims[4];
  const int out_channels = in_channels;

  DenseTensor indices_tensor = phi::Empty(
      dev_ctx_cpu,
      DenseTensorMeta(DataType::INT32, {4, non_zero_num}, DataLayout::NCHW));
  memcpy(
      indices_tensor.data<int>(), indices.data(), indices.size() * sizeof(int));
  DenseTensor features_tensor = phi::Empty(
      dev_ctx_cpu,
      DenseTensorMeta(paddle::experimental::CppTypeToDataType<T>::Type(),
                      {non_zero_num, in_channels},
                      DataLayout::NHWC));
  memcpy(
      features_tensor.data<T>(), features.data(), features.size() * sizeof(T));

  SparseCooTensor x_tensor(indices_tensor, features_tensor, x_dims);

  auto f_verify = [&](const T* real_data, const std::vector<T>& correct_data) {
    for (uint64_t i = 0; i < correct_data.size(); i++) {
      float tmp = std::fabs(static_cast<float>(correct_data[i] - real_data[i]));
      ASSERT_LT(tmp, diff);
    }
  };

  if (!std::is_same<T, phi::dtype::float16>::value) {
    DenseTensor rulebook = phi::Empty(
        dev_ctx_cpu, DenseTensorMeta(DataType::INT32, {1}, DataLayout::NCHW));
    SparseCooTensor out = sparse::MaxPool<T>(dev_ctx_cpu,
                                             x_tensor,
                                             kernel_sizes,
                                             paddings,
                                             dilations,
                                             strides,
                                             &rulebook);

    ASSERT_EQ(correct_out_dims.size(), out.dims().size());
    for (int i = 0; i < correct_out_dims.size(); i++) {
      ASSERT_EQ(correct_out_dims[i], out.dims()[i]);
    }
    ASSERT_EQ((int64_t)correct_out_features.size() / out_channels, out.nnz());

    int cmp_indices = memcmp(correct_out_indices.data(),
                             out.non_zero_indices().data<int>(),
                             correct_out_indices.size() * sizeof(int));
    ASSERT_EQ(cmp_indices, 0);

    f_verify(out.non_zero_elements().data<T>(), correct_out_features);

    if (backward) {
      DenseTensor x_grad = sparse::MaxPoolGrad<T>(dev_ctx_cpu,
                                                  x_tensor,
                                                  rulebook,
                                                  out,
                                                  out.non_zero_elements(),
                                                  kernel_sizes);
      f_verify(x_grad.data<T>(), features_grad);
    }
  }

// test gpu
#if defined(PADDLE_WITH_CUDA)
  phi::GPUContext dev_ctx_gpu;
  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()
          .GetAllocator(phi::CPUPlace())
          .get());
  dev_ctx_gpu.PartialInitWithAllocator();

  DenseTensor d_indices_tensor = phi::Empty(
      dev_ctx_gpu,
      DenseTensorMeta(DataType::INT32, {4, non_zero_num}, DataLayout::NCHW));
  phi::Copy(
      dev_ctx_gpu, indices_tensor, phi::GPUPlace(), true, &d_indices_tensor);

145 146
  DenseTensor d_features_tensor =
      phi::EmptyLike<T>(dev_ctx_gpu, features_tensor);
Z
zhangkaihuo 已提交
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 172 173 174 175 176 177 178 179 180 181
  phi::Copy(
      dev_ctx_gpu, features_tensor, phi::GPUPlace(), true, &d_features_tensor);

  SparseCooTensor d_x_tensor(d_indices_tensor, d_features_tensor, x_dims);

  DenseTensor d_rulebook = phi::Empty(
      dev_ctx_gpu, DenseTensorMeta(DataType::INT32, {1}, DataLayout::NCHW));
  SparseCooTensor d_out = sparse::MaxPool<T>(dev_ctx_gpu,
                                             d_x_tensor,
                                             kernel_sizes,
                                             paddings,
                                             dilations,
                                             strides,
                                             &d_rulebook);

  ASSERT_EQ(correct_out_dims.size(), d_out.dims().size());
  ASSERT_EQ((int64_t)correct_out_features.size() / out_channels, d_out.nnz());
  for (int i = 0; i < correct_out_dims.size(); i++) {
    ASSERT_EQ(correct_out_dims[i], d_out.dims()[i]);
  }

  DenseTensor h_indices_tensor = phi::Empty(
      dev_ctx_cpu,
      DenseTensorMeta(DataType::INT32, {4, d_out.nnz()}, DataLayout::NCHW));
  phi::Copy(dev_ctx_gpu,
            d_out.non_zero_indices(),
            phi::CPUPlace(),
            true,
            &h_indices_tensor);

  int cmp_indices2 = memcmp(correct_out_indices.data(),
                            h_indices_tensor.data<int>(),
                            correct_out_indices.size() * sizeof(int));
  ASSERT_EQ(cmp_indices2, 0);

182 183
  DenseTensor h_features_tensor =
      phi::EmptyLike<T>(dev_ctx_cpu, d_out.non_zero_elements());
Z
zhangkaihuo 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

  phi::Copy(dev_ctx_gpu,
            d_out.non_zero_elements(),
            phi::CPUPlace(),
            true,
            &h_features_tensor);
  f_verify(h_features_tensor.data<T>(), correct_out_features);

  if (backward) {
    DenseTensor x_grad = sparse::MaxPoolGrad<T>(dev_ctx_gpu,
                                                d_x_tensor,
                                                d_rulebook,
                                                d_out,
                                                d_out.non_zero_elements(),
                                                kernel_sizes);
199
    DenseTensor h_features_grad = phi::EmptyLike<T>(dev_ctx_cpu, x_grad);
Z
zhangkaihuo 已提交
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 229 230 231 232 233 234 235 236 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 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    phi::Copy(dev_ctx_gpu, x_grad, phi::CPUPlace(), true, &h_features_grad);
    f_verify(h_features_grad.data<T>(), features_grad);
  }
#endif
}

void TestMaxPool(const std::vector<int>& indices,
                 const std::vector<float>& features,
                 const DDim& x_dims,
                 const std::vector<int>& correct_out_indices,
                 const std::vector<float>& correct_out_features,
                 const DDim& correct_out_dims,
                 const int non_zero_num,
                 const std::vector<int>& kernel_sizes,
                 const std::vector<int>& paddings,
                 const std::vector<int>& strides,
                 const std::vector<int>& dilations,
                 const float diff = 1e-3,
                 const bool backward = false,
                 const std::vector<float> features_grad = {}) {
  // test float
  TestMaxPoolBase<float>(indices,
                         features,
                         x_dims,
                         correct_out_indices,
                         correct_out_features,
                         correct_out_dims,
                         non_zero_num,
                         kernel_sizes,
                         paddings,
                         strides,
                         dilations,
                         diff,
                         backward,
                         features_grad);
  // test double
  TestMaxPoolBase<double>(indices,
                          cast<float, double>(features),
                          x_dims,
                          correct_out_indices,
                          cast<float, double>(correct_out_features),
                          correct_out_dims,
                          non_zero_num,
                          kernel_sizes,
                          paddings,
                          strides,
                          dilations,
                          diff,
                          backward,
                          cast<float, double>(features_grad));
}

TEST(DEV_API, sparse_maxpool) {
  const int channels = 1;
  DDim x_dims = {1, 1, 4, 4, channels};
  DDim out_dims = {1, 1, 2, 2, channels};
  std::vector<int> kernel_sizes = {1, 3, 3};
  std::vector<int> paddings = {0, 0, 0};
  std::vector<int> strides = {1, 1, 1};
  std::vector<int> dilations = {1, 1, 1};

  const int non_zero_num = 3;
  std::vector<int> indices = {0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 2};
  std::vector<float> features = {1, 2, 3};
  std::vector<int> out_indices = {
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,
  };
  std::vector<float> out_features = {2, 2, 3, 3};
  std::vector<float> x_grad = {0, 4, 6};

  TestMaxPool(indices,
              features,
              x_dims,
              out_indices,
              out_features,
              out_dims,
              non_zero_num,
              kernel_sizes,
              paddings,
              strides,
              dilations,
              1e-6,
              true,
              x_grad);
}

TEST(DEV_API, sparse_maxpool_stride) {
  const int channels = 1;
  DDim x_dims = {1, 1, 4, 4, channels};
  DDim out_dims = {1, 1, 1, 1, channels};
  std::vector<int> kernel_sizes = {1, 3, 3};
  std::vector<int> paddings = {0, 0, 0};
  std::vector<int> strides = {2, 2, 2};
  std::vector<int> dilations = {1, 1, 1};

  const int non_zero_num = 3;
  std::vector<int> indices = {0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 2};
  std::vector<float> features = {1, 2, 3};
  std::vector<int> out_indices = {0, 0, 0, 0};
  std::vector<float> out_features = {2};
  std::vector<float> x_grad = {0, 2, 0};

  TestMaxPool(indices,
              features,
              x_dims,
              out_indices,
              out_features,
              out_dims,
              non_zero_num,
              kernel_sizes,
              paddings,
              strides,
              dilations,
              1e-6,
              true,
              x_grad);
}

TEST(DEV_API, sparse_maxpool_channel) {
  const int channels = 2;
  DDim x_dims = {1, 1, 4, 4, channels};
  DDim out_dims = {1, 1, 2, 2, channels};
  std::vector<int> kernel_sizes = {1, 3, 3};
  std::vector<int> paddings = {0, 0, 0};
  std::vector<int> strides = {1, 1, 1};
  std::vector<int> dilations = {1, 1, 1};

  const int non_zero_num = 3;
  std::vector<int> indices = {0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 2};
  std::vector<float> features = {1, 1, 2, 2, 3, 3};
  std::vector<int> out_indices = {
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,
  };
  std::vector<float> out_features = {2, 2, 2, 2, 3, 3, 3, 3};
  std::vector<float> x_grad = {0, 0, 4, 4, 6, 6};

  TestMaxPool(indices,
              features,
              x_dims,
              out_indices,
              out_features,
              out_dims,
              non_zero_num,
              kernel_sizes,
              paddings,
              strides,
              dilations,
              1e-6,
              true,
              x_grad);
}

TEST(DEV_API, sparse_maxpool3d) {
  const int channels = 2;
  DDim x_dims = {1, 5, 4, 4, channels};
  DDim out_dims = {1, 3, 2, 2, channels};
  std::vector<int> kernel_sizes = {3, 3, 3};
  std::vector<int> paddings = {0, 0, 0};
  std::vector<int> strides = {1, 1, 1};
  std::vector<int> dilations = {1, 1, 1};

  const int non_zero_num = 3;
  std::vector<int> indices = {0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 2};
  std::vector<float> features = {1, 1, 2, 2, 3, 3};
  std::vector<int> out_indices = {
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,
  };
  std::vector<float> out_features = {2, 2, 2, 2, 3, 3, 3, 3};
  std::vector<float> x_grad = {0, 0, 4, 4, 6, 6};

  TestMaxPool(indices,
              features,
              x_dims,
              out_indices,
              out_features,
              out_dims,
              non_zero_num,
              kernel_sizes,
              paddings,
              strides,
              dilations,
              1e-6,
              true,
              x_grad);
}

}  // namespace tests
}  // namespace phi