test_sparse_pool_dev_api.cc 13.9 KB
Newer Older
Z
zhangkaihuo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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>
16

Z
zhangkaihuo 已提交
17 18
#include <memory>

19 20
#include "paddle/fluid/memory/allocation/allocator_facade.h"
#include "paddle/phi/api/lib/utils/allocator.h"
Z
zhangkaihuo 已提交
21 22
#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/common/place.h"
23
#include "paddle/phi/core/kernel_registry.h"
Z
zhangkaihuo 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#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"

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;
}
39 40
template <typename T, typename IntT = int>
void TestMaxPoolBase(const std::vector<IntT>& indices,
Z
zhangkaihuo 已提交
41 42
                     const std::vector<T>& features,
                     const DDim& x_dims,
43
                     const std::vector<IntT>& correct_out_indices,
Z
zhangkaihuo 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
                     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
  dev_ctx_cpu.Init();

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

68
  auto indices_dtype = paddle::experimental::CppTypeToDataType<IntT>::Type();
Z
zhangkaihuo 已提交
69 70
  DenseTensor indices_tensor = phi::Empty(
      dev_ctx_cpu,
71 72 73 74
      DenseTensorMeta(indices_dtype, {4, non_zero_num}, DataLayout::NCHW));
  memcpy(indices_tensor.data<IntT>(),
         indices.data(),
         indices.size() * sizeof(IntT));
Z
zhangkaihuo 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  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) {
93
    DenseTensor rulebook;
Z
zhangkaihuo 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    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(),
109 110
                             out.non_zero_indices().data<IntT>(),
                             correct_out_indices.size() * sizeof(IntT));
Z
zhangkaihuo 已提交
111 112 113 114 115
    ASSERT_EQ(cmp_indices, 0);

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

    if (backward) {
116 117 118
      SparseCooTensor x_grad = sparse::MaxPoolGrad<T>(
          dev_ctx_cpu, x_tensor, rulebook, out, out, kernel_sizes);
      f_verify(x_grad.non_zero_elements().data<T>(), features_grad);
Z
zhangkaihuo 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    }
  }

// 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());
W
wanghuancoder 已提交
134 135 136 137
  dev_ctx_gpu.SetPinnedAllocator(
      paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(paddle::platform::CUDAPinnedPlace())
          .get());
Z
zhangkaihuo 已提交
138 139 140 141
  dev_ctx_gpu.PartialInitWithAllocator();

  DenseTensor d_indices_tensor = phi::Empty(
      dev_ctx_gpu,
142
      DenseTensorMeta(indices_dtype, {4, non_zero_num}, DataLayout::NCHW));
Z
zhangkaihuo 已提交
143 144 145
  phi::Copy(
      dev_ctx_gpu, indices_tensor, phi::GPUPlace(), true, &d_indices_tensor);

146 147
  DenseTensor d_features_tensor =
      phi::EmptyLike<T>(dev_ctx_gpu, features_tensor);
Z
zhangkaihuo 已提交
148 149 150 151 152
  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);

153
  DenseTensor d_rulebook;
Z
zhangkaihuo 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  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,
170
      DenseTensorMeta(indices_dtype, {4, d_out.nnz()}, DataLayout::NCHW));
Z
zhangkaihuo 已提交
171 172 173 174 175 176 177
  phi::Copy(dev_ctx_gpu,
            d_out.non_zero_indices(),
            phi::CPUPlace(),
            true,
            &h_indices_tensor);

  int cmp_indices2 = memcmp(correct_out_indices.data(),
178 179
                            h_indices_tensor.data<IntT>(),
                            correct_out_indices.size() * sizeof(IntT));
Z
zhangkaihuo 已提交
180 181
  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

  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) {
193 194 195 196 197 198 199 200 201
    SparseCooTensor x_grad = sparse::MaxPoolGrad<T>(
        dev_ctx_gpu, d_x_tensor, d_rulebook, d_out, d_out, kernel_sizes);
    DenseTensor h_features_grad =
        phi::EmptyLike<T>(dev_ctx_cpu, x_grad.non_zero_elements());
    phi::Copy(dev_ctx_gpu,
              x_grad.non_zero_elements(),
              phi::CPUPlace(),
              true,
              &h_features_grad);
Z
zhangkaihuo 已提交
202 203 204 205 206
    f_verify(h_features_grad.data<T>(), features_grad);
  }
#endif
}

207 208
template <typename IntT = int>
void TestMaxPool(const std::vector<IntT>& indices,
Z
zhangkaihuo 已提交
209 210
                 const std::vector<float>& features,
                 const DDim& x_dims,
211
                 const std::vector<IntT>& correct_out_indices,
Z
zhangkaihuo 已提交
212 213 214 215 216 217 218 219 220 221 222
                 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
223 224 225 226 227 228 229 230 231 232 233 234 235 236
  TestMaxPoolBase<float, IntT>(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);
Z
zhangkaihuo 已提交
237
  // test double
238 239 240 241 242 243 244 245 246 247 248 249 250 251
  TestMaxPoolBase<double, IntT>(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));
Z
zhangkaihuo 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
}

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 = {
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      1,
      0,
      1,
Z
zhangkaihuo 已提交
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
  };
  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 = {
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      1,
      0,
      1,
Z
zhangkaihuo 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  };
  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 = {
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      1,
      0,
      1,
Z
zhangkaihuo 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  };
  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