pooling.cu 114.3 KB
Newer Older
F
From00 已提交
1
/* Copyright (c) 2022 paddlepaddle Authors. All Rights Reserved.
C
chengduoZH 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

C
chengduo 已提交
15 16
#include <algorithm>
#include <vector>
17

F
From00 已提交
18
#include "paddle/phi/backends/gpu/gpu_launch_config.h"
W
Wang Xin 已提交
19
#include "paddle/phi/backends/gpu/gpu_primitives.h"
20
#include "paddle/phi/kernels/funcs/pooling.h"
21
#include "paddle/phi/kernels/funcs/reduce_function.h"
22
#include "paddle/phi/kernels/primitive/datamover_primitives.h"
C
chengduoZH 已提交
23

F
From00 已提交
24 25
namespace phi {
namespace funcs {
C
chengduoZH 已提交
26

L
limingshu 已提交
27 28
struct FastDivModForPooling {
 public:
29 30 31
  phi::kps::details::FastDivMod channel;
  phi::kps::details::FastDivMod width;
  phi::kps::details::FastDivMod height;
L
limingshu 已提交
32 33 34 35

  explicit HOSTDEVICE FastDivModForPooling(const int channels,
                                           const int output_width,
                                           const int output_height) {
36 37 38
    channel = phi::kps::details::FastDivMod(channels);
    width = phi::kps::details::FastDivMod(output_width);
    height = phi::kps::details::FastDivMod(output_height);
L
limingshu 已提交
39 40 41
  }
};

42 43
struct FastDivModForPooling3D {
 public:
44 45 46 47
  phi::kps::details::FastDivMod channel;
  phi::kps::details::FastDivMod width;
  phi::kps::details::FastDivMod height;
  phi::kps::details::FastDivMod depth;
48 49 50 51 52

  explicit HOSTDEVICE FastDivModForPooling3D(const int channels,
                                             const int output_width,
                                             const int output_height,
                                             const int output_depth) {
53 54 55 56
    channel = phi::kps::details::FastDivMod(channels);
    width = phi::kps::details::FastDivMod(output_width);
    height = phi::kps::details::FastDivMod(output_height);
    depth = phi::kps::details::FastDivMod(output_depth);
57 58 59
  }
};

L
limingshu 已提交
60 61
struct FastDivModForPoolingWithMoreStaff {
 public:
62 63 64 65 66 67 68
  phi::kps::details::FastDivMod channel;
  phi::kps::details::FastDivMod width;
  phi::kps::details::FastDivMod height;
  phi::kps::details::FastDivMod ksize_w;
  phi::kps::details::FastDivMod ksize_h;
  phi::kps::details::FastDivMod stride_w;
  phi::kps::details::FastDivMod stride_h;
L
limingshu 已提交
69 70

  explicit HOSTDEVICE FastDivModForPoolingWithMoreStaff(
F
From00 已提交
71 72 73 74 75 76
      const int channels,
      const int input_width,
      const int input_height,
      const int ksize_width,
      const int ksize_height,
      const int stride_width,
L
limingshu 已提交
77
      const int stride_height) {
78 79 80 81 82 83 84
    channel = phi::kps::details::FastDivMod(channels);
    width = phi::kps::details::FastDivMod(input_width);
    height = phi::kps::details::FastDivMod(input_height);
    ksize_w = phi::kps::details::FastDivMod(ksize_width);
    ksize_h = phi::kps::details::FastDivMod(ksize_height);
    stride_w = phi::kps::details::FastDivMod(stride_width);
    stride_h = phi::kps::details::FastDivMod(stride_height);
L
limingshu 已提交
85 86 87 88
  }
};

template <typename FastDivModForPooling>
F
From00 已提交
89 90 91 92 93 94 95 96 97 98 99
__device__ void OffsetPreparationFor4Dimension(int index,
                                               bool channel_last,
                                               FastDivModForPooling divmods,
                                               const int pad_width,
                                               const int pad_height,
                                               const int aux_width,
                                               const int aux_height,
                                               int* w_offset,
                                               int* h_offset,
                                               int* c_offset,
                                               int* stride) {
L
limingshu 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  if (!channel_last) { /* NCHW */
    auto input_width_divmod = divmods.width.Divmod(index);
    auto input_height_divmod = divmods.height.Divmod(input_width_divmod.val[0]);
    auto channel_divmod = divmods.channel.Divmod(input_height_divmod.val[0]);
    *w_offset = input_width_divmod.val[1] + pad_width;
    *h_offset = input_height_divmod.val[1] + pad_height;
    *c_offset = channel_divmod.val[1];
    *stride = (channel_divmod.val[0] * divmods.channel.divisor + *c_offset) *
              aux_height * aux_width;
  } else { /* NHWC */
    auto c_divmod = divmods.channel.Divmod(index);
    auto input_width_divmod = divmods.width.Divmod(c_divmod.val[0]);
    auto input_height_divmod = divmods.height.Divmod(input_width_divmod.val[0]);
    *c_offset = c_divmod.val[1];
    *w_offset = input_width_divmod.val[1] + pad_width;
    *h_offset = input_height_divmod.val[1] + pad_height;
    *stride = input_height_divmod.val[0] * aux_height * aux_width *
              divmods.channel.divisor;
  }
}

121
template <typename PoolProcess, typename T>
F
From00 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
__global__ void KernelPool2D(const int nthreads,
                             const T* input_data,
                             const int channels,
                             const int input_height,
                             const int input_width,
                             const int output_height,
                             const int output_width,
                             const int ksize_height,
                             const int ksize_width,
                             const int stride_height,
                             const int stride_width,
                             const int padding_height,
                             const int padding_width,
                             FastDivModForPooling divmods,
                             PoolProcess pool_process,
                             bool exclusive,
                             T* output_data,
                             bool channel_last = false) {
140 141
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
142 143
    int hstart, hend, wstart, wend;
    int w_offset, h_offset, c_offset, input_offset;
F
From00 已提交
144 145 146 147 148 149 150 151 152 153 154
    OffsetPreparationFor4Dimension<FastDivModForPooling>(index,
                                                         channel_last,
                                                         divmods,
                                                         0,
                                                         0,
                                                         input_width,
                                                         input_height,
                                                         &w_offset,
                                                         &h_offset,
                                                         &c_offset,
                                                         &input_offset);
L
limingshu 已提交
155
    input_data += input_offset;
156

157 158 159 160 161 162
    hstart = h_offset * stride_height - padding_height;
    hend = min(hstart + ksize_height, input_height);
    hstart = max(hstart, 0);
    wstart = w_offset * stride_width - padding_width;
    wend = min(wstart + ksize_width, input_width);
    wstart = max(wstart, 0);
163

164
    T ele = pool_process.initial();
165 166
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
L
limingshu 已提交
167 168 169
        auto input_idx = channel_last
                             ? (h * input_width + w) * channels + c_offset
                             : h * input_width + w;
170
        pool_process.compute(input_data[input_idx], &ele);
171 172
      }
    }
173 174
    int pool_size = exclusive ? (hend - hstart) * (wend - wstart)
                              : ksize_height * ksize_width;
C
chengduo 已提交
175
    pool_process.finalize(static_cast<T>(pool_size), &ele);
176 177 178
    output_data[index] = ele;
  }
}
L
limingshu 已提交
179

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
template <typename PoolProcess, typename T>
__global__ void AdaptiveKernelPool2D(const int nthreads,
                                     const T* input_data,
                                     const int channels,
                                     const int input_height,
                                     const int input_width,
                                     const int output_height,
                                     const int output_width,
                                     const int ksize_height,
                                     const int ksize_width,
                                     const int stride_height,
                                     const int stride_width,
                                     const int padding_height,
                                     const int padding_width,
                                     FastDivModForPooling divmods,
                                     PoolProcess pool_process,
                                     bool exclusive,
                                     T* output_data,
                                     bool channel_last = false) {
  const int n_offset = blockIdx.y;
  const int c_offset = blockIdx.x * blockDim.y + threadIdx.y;
  if (c_offset >= channels) {
    return;
  }
  int hstart, hend, wstart, wend;
  int input_offset =
      channel_last
          ? n_offset * input_height * input_width * channels
          : (n_offset * channels + c_offset) * input_height * input_width;
  int output_offset =
      channel_last
          ? n_offset * output_height * output_width * channels
          : (n_offset * channels + c_offset) * output_height * output_width;
  for (int hw_offset = threadIdx.x; hw_offset < output_height * output_width;
       hw_offset += blockDim.x) {
    int w_offset = hw_offset % output_width;
    int h_offset = hw_offset / output_width;
    hstart = AdaptStartIndex(h_offset, input_height, output_height);
    hend = AdaptEndIndex(h_offset, input_height, output_height);
    wstart = AdaptStartIndex(w_offset, input_width, output_width);
    wend = AdaptEndIndex(w_offset, input_width, output_width);

    T ele = pool_process.initial();
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
        auto input_idx = channel_last
                             ? (h * input_width + w) * channels + c_offset
                             : h * input_width + w;
        pool_process.compute(input_data[input_offset + input_idx], &ele);
      }
    }
    int pool_size = (hend - hstart) * (wend - wstart);
    pool_process.finalize(static_cast<T>(pool_size), &ele);
    int output_idx =
        channel_last
            ? (h_offset * output_width + w_offset) * channels + c_offset
            : h_offset * output_width + w_offset;
    output_data[output_offset + output_idx] = ele;
  }
}

L
limingshu 已提交
241
template <typename T, typename PoolProcess>
F
From00 已提交
242 243 244
__global__ void KernelPool2DGrad(const int nthreads,
                                 const T* __restrict__ input_data,
                                 const T* __restrict__ output_data,
245
                                 const T* __restrict__ output_grad,
F
From00 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                                 const int output_width,
                                 const int output_height,
                                 const int input_width,
                                 const int input_height,
                                 const int ksize_width,
                                 const int ksize_height,
                                 const int stride_width,
                                 const int stride_height,
                                 const int padding_width,
                                 const int padding_height,
                                 FastDivModForPoolingWithMoreStaff divmods,
                                 PoolProcess pool_process,
                                 bool exclusive,
                                 bool adaptive,
                                 T* __restrict__ input_grad,
                                 bool channel_last = false) {
262 263
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
264 265 266 267
    T input = static_cast<T>(0);
    T input_grad_data = static_cast<T>(0);
    int phstart, phend, pwstart, pwend;
    int w_offset, h_offset, c_offset, output_offset;
F
From00 已提交
268 269 270 271 272 273 274 275 276 277 278
    OffsetPreparationFor4Dimension<>(index,
                                     channel_last,
                                     divmods,
                                     padding_width,
                                     padding_height,
                                     output_width,
                                     output_height,
                                     &w_offset,
                                     &h_offset,
                                     &c_offset,
                                     &output_offset);
L
limingshu 已提交
279 280 281
    if (pool_process.use_x) {
      input = input_data[index];
      output_data += output_offset;
282
    }
L
limingshu 已提交
283
    output_grad += output_offset;
284

285
    if (adaptive) {
L
limingshu 已提交
286 287 288 289 290 291
      auto tmp_phend = divmods.height.Divmod((h_offset + 1) * output_height);
      auto tmp_pwend = divmods.width.Divmod((w_offset + 1) * output_width);
      phstart = divmods.height.Div(h_offset * output_height);
      pwstart = divmods.width.Div(w_offset * output_width);
      phend = tmp_phend.val[1] > 0 ? tmp_phend.val[0] + 1 : tmp_phend.val[0];
      pwend = tmp_pwend.val[1] > 0 ? tmp_pwend.val[0] + 1 : tmp_pwend.val[0];
292

L
limingshu 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
      for (int ph = phstart; ph < phend; ++ph) {
        for (int pw = pwstart; pw < pwend; ++pw) {
          auto ksize_w_divmod = divmods.ksize_w.Divmod(input_width);
          auto ksize_h_divmod = divmods.ksize_h.Divmod(input_height);
          auto tmp_width = ksize_w_divmod.val[1] > 0 ? ksize_w_divmod.val[0] + 1
                                                     : ksize_w_divmod.val[0];
          auto tmp_height = ksize_h_divmod.val[1] > 0
                                ? ksize_h_divmod.val[0] + 1
                                : ksize_h_divmod.val[0];
          int pool_size = tmp_height * tmp_width;
          int tmp_idx = ph * output_width + pw;
          int output_sub_idx =
              channel_last ? tmp_idx * divmods.channel.divisor + c_offset
                           : tmp_idx;
          T ouput_value = pool_process.use_x ? output_data[output_sub_idx]
                                             : static_cast<T>(0);
F
From00 已提交
309 310 311
          pool_process.compute(input,
                               ouput_value,
                               output_grad[output_sub_idx],
L
limingshu 已提交
312 313 314 315
                               static_cast<T>(1.0 / pool_size),
                               &input_grad_data);
        }
      }
316
    } else {
L
limingshu 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
      auto stride_height_div = divmods.stride_h.Div(h_offset - ksize_height);
      auto stride_width_div = divmods.stride_w.Div(w_offset - ksize_width);
      phstart = (h_offset < ksize_height) ? 0 : stride_height_div + 1;
      pwstart = (w_offset < ksize_width) ? 0 : stride_width_div + 1;
      phend = min(divmods.stride_h.Div(h_offset) + 1, output_height);
      pwend = min(divmods.stride_w.Div(w_offset) + 1, output_width);

      if (exclusive) {
        for (int ph = phstart; ph < phend; ++ph) {
          for (int pw = pwstart; pw < pwend; ++pw) {
            int hstart = ph * stride_height - padding_height;
            int wstart = pw * stride_width - padding_width;
            int hend = min(hstart + ksize_height, input_height);
            int wend = min(wstart + ksize_width, input_width);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            int pool_size = (hend - hstart) * (wend - wstart);
            int tmp_idx = ph * output_width + pw;
            int output_sub_idx =
                channel_last ? tmp_idx * divmods.channel.divisor + c_offset
                             : tmp_idx;
            T ouput_value = pool_process.use_x ? output_data[output_sub_idx]
                                               : static_cast<T>(0);
F
From00 已提交
340 341 342 343 344
            pool_process.compute(input,
                                 ouput_value,
                                 output_grad[output_sub_idx],
                                 static_cast<T>(1.0 / pool_size),
                                 &input_grad_data);
L
limingshu 已提交
345 346 347 348 349 350 351 352 353 354 355 356
          }
        }
      } else {
        for (int ph = phstart; ph < phend; ++ph) {
          for (int pw = pwstart; pw < pwend; ++pw) {
            int pool_size = ksize_height * ksize_width;
            int tmp_idx = ph * output_width + pw;
            int output_sub_idx =
                channel_last ? tmp_idx * divmods.channel.divisor + c_offset
                             : tmp_idx;
            T ouput_value = pool_process.use_x ? output_data[output_sub_idx]
                                               : static_cast<T>(0);
F
From00 已提交
357 358 359 360 361
            pool_process.compute(input,
                                 ouput_value,
                                 output_grad[output_sub_idx],
                                 static_cast<T>(1.0 / pool_size),
                                 &input_grad_data);
L
limingshu 已提交
362
          }
363
        }
364 365
      }
    }
L
limingshu 已提交
366
    input_grad[index] = input_grad_data;
367 368 369
  }
}

370
template <typename T>
F
From00 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
__global__ void KernelMaxPool2DGrad(const int nthreads,
                                    const T* input_data,
                                    const T* output_data,
                                    const T* output_grad,
                                    const int channels,
                                    const int input_height,
                                    const int input_width,
                                    const int output_height,
                                    const int output_width,
                                    const int ksize_height,
                                    const int ksize_width,
                                    const int stride_height,
                                    const int stride_width,
                                    const int padding_height,
                                    const int padding_width,
                                    T* input_grad,
                                    FastDivModForPooling divmods,
                                    bool channel_last = false) {
389 390
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
391
    int w_offset, h_offset, c_offset, input_offset;
F
From00 已提交
392 393 394 395 396 397 398 399 400 401 402
    OffsetPreparationFor4Dimension<FastDivModForPooling>(index,
                                                         channel_last,
                                                         divmods,
                                                         0,
                                                         0,
                                                         input_width,
                                                         input_height,
                                                         &w_offset,
                                                         &h_offset,
                                                         &c_offset,
                                                         &input_offset);
L
limingshu 已提交
403 404 405 406
    input_data += input_offset;
    input_grad += input_offset;

    int hstart = h_offset * stride_height - padding_height;
407 408 409
    int hend = min(hstart + ksize_height, input_height);
    hstart = max(hstart, 0);

L
limingshu 已提交
410
    int wstart = w_offset * stride_width - padding_width;
411 412 413 414 415 416 417 418
    int wend = min(wstart + ksize_width, input_width);
    wstart = max(wstart, 0);

    T ele = output_data[index];
    int maxIndex = -1;
    bool stop = false;
    for (int h = hstart; h < hend && !stop; ++h) {
      for (int w = wstart; w < wend && !stop; ++w) {
L
limingshu 已提交
419 420 421
        int input_data_idx = channel_last
                                 ? (h * input_width + w) * channels + c_offset
                                 : h * input_width + w;
422 423
        if (ele == input_data[input_data_idx]) {
          maxIndex = input_data_idx;
424 425 426 427 428 429 430
          stop = true;
        }
      }
    }

    if (maxIndex != -1) {
      // atomic add
W
Wang Xin 已提交
431
      phi::CudaAtomicAdd(input_grad + maxIndex, output_grad[index]);
432 433 434 435
    }
  }
}

N
nhzlx 已提交
436 437
template <typename PoolProcess, typename T>
void Pool2dDirectCUDAFunctor<PoolProcess, T>::operator()(
F
From00 已提交
438 439 440 441 442 443 444 445 446 447
    const T* input,
    const std::vector<int>& input_shape,
    const std::vector<int>& output_shape,
    const std::vector<int>& ksize,
    const std::vector<int>& strides,
    const std::vector<int>& paddings,
    bool exclusive,
    bool adaptive,
    T* output,
    gpuStream_t stream,
448
    PoolProcess pool_compute) {
N
nhzlx 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462
  const int batch_size = input_shape[0];
  const int input_channels = input_shape[1];
  const int input_height = input_shape[2];
  const int input_width = input_shape[3];
  const int output_channels = output_shape[1];
  const int output_height = output_shape[2];
  const int output_width = output_shape[3];
  const int ksize_height = ksize[0];
  const int ksize_width = ksize[1];
  const int stride_height = strides[0];
  const int stride_width = strides[1];
  const int padding_height = paddings[0];
  const int padding_width = paddings[1];
  int nthreads = batch_size * output_channels * output_height * output_width;
L
limingshu 已提交
463 464
  auto pool_divmods =
      FastDivModForPooling(input_channels, output_width, output_height);
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  if (adaptive) {
    int max_threads = 512;
    int thread_num =
        std::min(phi::funcs::details::GetLastPow2(output_height * output_width),
                 max_threads);
    int blocks = std::min(max_threads / thread_num, output_channels);
    dim3 threads(thread_num, blocks, 1);
    dim3 grid(
        std::max((output_channels + blocks - 1) / blocks, 1), batch_size, 1);
    AdaptiveKernelPool2D<PoolProcess, T>
        <<<grid, threads, 0, stream>>>(nthreads,
                                       input,
                                       input_channels,
                                       input_height,
                                       input_width,
                                       output_height,
                                       output_width,
                                       ksize_height,
                                       ksize_width,
                                       stride_height,
                                       stride_width,
                                       padding_height,
                                       padding_width,
                                       pool_divmods,
                                       pool_compute,
                                       exclusive,
                                       output);
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
  } else {
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    // backends::gpu::ChangeThreadNum(context, &thread_num);
    thread_num = 512;
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
    dim3 grid(blocks, 1);
    KernelPool2D<PoolProcess, T><<<grid, threads, 0, stream>>>(nthreads,
                                                               input,
                                                               input_channels,
                                                               input_height,
                                                               input_width,
                                                               output_height,
                                                               output_width,
                                                               ksize_height,
                                                               ksize_width,
                                                               stride_height,
                                                               stride_width,
                                                               padding_height,
                                                               padding_width,
                                                               pool_divmods,
                                                               pool_compute,
                                                               exclusive,
                                                               output);
  }
N
nhzlx 已提交
520 521
}

C
chengduoZH 已提交
522
/*
523 524 525 526 527 528
 * Tensors are in NCHW or NHWC format.
 * Ksize, strides are two elements. These two elements represent height
 * and width, respectively.
 * Paddings are four elements. These four elements represent height_up,
 * height_down, width_left and width_right, respectively.
 */
529
template <typename PoolProcess, typename T>
F
From00 已提交
530
class Pool2dFunctor<phi::GPUContext, PoolProcess, T> {
531
 public:
F
From00 已提交
532 533 534
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
C
chengduo 已提交
535
                  const std::vector<int>& strides,
F
From00 已提交
536 537 538 539
                  const std::vector<int>& paddings,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* output,
540
                  PoolProcess pool_process) {
541 542 543 544
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_height = input.dims()[2];
    const int input_width = input.dims()[3];
C
chengduoZH 已提交
545 546 547
    const int output_channels = output->dims()[1];
    const int output_height = output->dims()[2];
    const int output_width = output->dims()[3];
548 549 550 551 552 553 554 555
    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];
    const int stride_height = strides[0];
    const int stride_width = strides[1];
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
F
From00 已提交
556
    T* output_data = context.template Alloc<T>(output);
557 558

    int nthreads = batch_size * output_channels * output_height * output_width;
L
limingshu 已提交
559 560
    auto pool_divmods =
        FastDivModForPooling(input_channels, output_width, output_height);
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    if (adaptive) {
      int max_threads = 512;
      int thread_num = std::min(
          phi::funcs::details::GetLastPow2(output_height * output_width),
          max_threads);
      int blocks = std::min(max_threads / thread_num, output_channels);
      dim3 threads(thread_num, blocks, 1);
      dim3 grid(
          std::max((output_channels + blocks - 1) / blocks, 1), batch_size, 1);
      AdaptiveKernelPool2D<PoolProcess, T>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   pool_divmods,
                                                   pool_process,
                                                   exclusive,
                                                   output_data);
    } else {
      int thread_num = 1024;
#ifdef WITH_NV_JETSON
      backends::gpu::ChangeThreadNum(context, &thread_num);
#endif
      int blocks = (nthreads + thread_num - 1) / thread_num;
      dim3 threads(thread_num, 1);
      dim3 grid(blocks, 1);
      KernelPool2D<PoolProcess, T>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   pool_divmods,
                                                   pool_process,
                                                   exclusive,
                                                   output_data);
    }
615
  }
F
From00 已提交
616 617 618
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
619 620
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
621 622 623 624 625
                  const std::string data_format,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* output,
                  PoolProcess pool_process) {
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    bool channel_last = (data_format == "NHWC");
    const int batch_size = input.dims()[0];

    const int input_channels = channel_last ? input.dims()[3] : input.dims()[1];
    const int input_height = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_width = channel_last ? input.dims()[2] : input.dims()[3];

    const int output_channels =
        channel_last ? output->dims()[3] : output->dims()[1];
    const int output_height =
        channel_last ? output->dims()[1] : output->dims()[2];
    const int output_width =
        channel_last ? output->dims()[2] : output->dims()[3];

    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];

    const int stride_height = strides[0];
    const int stride_width = strides[1];
645

646 647 648 649
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
F
From00 已提交
650
    T* output_data = context.template Alloc<T>(output);
651 652

    int nthreads = batch_size * output_channels * output_height * output_width;
L
limingshu 已提交
653 654
    auto pool_divmods =
        FastDivModForPooling(input_channels, output_width, output_height);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    if (adaptive) {
      int max_threads = 512;
      int thread_num = std::min(
          phi::funcs::details::GetLastPow2(output_height * output_width),
          max_threads);
      int blocks = std::min(max_threads / thread_num, output_channels);
      dim3 threads(thread_num, blocks, 1);
      dim3 grid(
          std::max((output_channels + blocks - 1) / blocks, 1), batch_size, 1);
      AdaptiveKernelPool2D<PoolProcess, T>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   pool_divmods,
                                                   pool_process,
                                                   exclusive,
                                                   output_data,
                                                   channel_last);
    } else {
      int thread_num = 1024;
#ifdef WITH_NV_JETSON
      backends::gpu::ChangeThreadNum(context, &thread_num);
#endif
      int blocks = (nthreads + thread_num - 1) / thread_num;
      dim3 threads(thread_num, 1);
      dim3 grid(blocks, 1);
      KernelPool2D<PoolProcess, T>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   pool_divmods,
                                                   pool_process,
                                                   exclusive,
                                                   output_data,
                                                   channel_last);
    }
711 712
  }
};
C
chengduoZH 已提交
713
/*
714 715 716 717 718 719
 * Tensors are in NCHW or NHWC format.
 * Ksize, strides are two elements. These two elements represent height
 * and width, respectively.
 * Paddings are four elements. These four elements represent height_up,
 * height_down, width_left and width_right, respectively.
 */
720
template <typename PoolProcess, typename T>
F
From00 已提交
721
class Pool2dGradFunctor<phi::GPUContext, PoolProcess, T> {
722
 public:
F
From00 已提交
723 724 725 726
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
C
chengduo 已提交
727 728
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
F
From00 已提交
729 730 731 732
                  const std::vector<int>& paddings,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* input_grad,
733
                  PoolProcess pool_process) {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_height = input.dims()[2];
    const int input_width = input.dims()[3];
    const int output_height = output.dims()[2];
    const int output_width = output.dims()[3];
    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];
    const int stride_height = strides[0];
    const int stride_width = strides[1];
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
750
    T* input_grad_data = context.template Alloc<T>(input_grad);
751 752

    int nthreads = batch_size * input_channels * input_height * input_width;
F
From00 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    auto pool_divmods = FastDivModForPoolingWithMoreStaff(input_channels,
                                                          input_width,
                                                          input_height,
                                                          ksize_width,
                                                          ksize_height,
                                                          stride_width,
                                                          stride_height);

    auto config = phi::backends::gpu::GetGpuLaunchConfig1D(context, nthreads);
    KernelPool2DGrad<T, PoolProcess><<<config.block_per_grid,
                                       config.thread_per_block,
                                       0,
                                       context.stream()>>>(nthreads,
                                                           input_data,
                                                           output_data,
                                                           output_grad_data,
                                                           output_width,
                                                           output_height,
                                                           input_width,
                                                           input_height,
                                                           ksize_width,
                                                           ksize_height,
                                                           stride_width,
                                                           stride_height,
                                                           padding_width,
                                                           padding_height,
                                                           pool_divmods,
                                                           pool_process,
                                                           exclusive,
                                                           adaptive,
                                                           input_grad_data);
784
  }
F
From00 已提交
785 786 787 788
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
789 790 791
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
792 793 794 795 796
                  const std::string data_format,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* input_grad,
                  PoolProcess pool_process) {
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    bool channel_last = (data_format == "NHWC");

    const int batch_size = input.dims()[0];
    const int input_channels = channel_last ? input.dims()[3] : input.dims()[1];
    const int input_height = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_width = channel_last ? input.dims()[2] : input.dims()[3];

    const int output_channels =
        channel_last ? output.dims()[3] : output.dims()[1];
    const int output_height =
        channel_last ? output.dims()[1] : output.dims()[2];
    const int output_width = channel_last ? output.dims()[2] : output.dims()[3];

    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];

    const int stride_height = strides[0];
    const int stride_width = strides[1];

    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
822
    T* input_grad_data = context.template Alloc<T>(input_grad);
823 824

    int nthreads = batch_size * input_channels * input_height * input_width;
F
From00 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
    auto pool_divmods = FastDivModForPoolingWithMoreStaff(input_channels,
                                                          input_width,
                                                          input_height,
                                                          ksize_width,
                                                          ksize_height,
                                                          stride_width,
                                                          stride_height);

    auto config = phi::backends::gpu::GetGpuLaunchConfig1D(context, nthreads);
    KernelPool2DGrad<T, PoolProcess><<<config.block_per_grid,
                                       config.thread_per_block,
                                       0,
                                       context.stream()>>>(nthreads,
                                                           input_data,
                                                           output_data,
                                                           output_grad_data,
                                                           output_width,
                                                           output_height,
                                                           input_width,
                                                           input_height,
                                                           ksize_width,
                                                           ksize_height,
                                                           stride_width,
                                                           stride_height,
                                                           padding_width,
                                                           padding_height,
                                                           pool_divmods,
                                                           pool_process,
                                                           exclusive,
                                                           adaptive,
                                                           input_grad_data,
                                                           channel_last);
857
  }
858 859
};

C
chengduoZH 已提交
860
/*
861 862 863 864 865 866
 * Tensors are in NCHW or NHWC format.
 * Ksize, strides are two elements. These two elements represent height
 * and width, respectively.
 * Paddings are four elements. These four elements represent height_up,
 * height_down, width_left and width_right, respectively.
 */
867
template <typename T>
F
From00 已提交
868
class MaxPool2dGradFunctor<phi::GPUContext, T> {
869
 public:
F
From00 已提交
870 871 872 873
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
C
chengduo 已提交
874 875 876
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
877
                  DenseTensor* input_grad) {
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_height = input.dims()[2];
    const int input_width = input.dims()[3];
    const int output_channels = output.dims()[1];
    const int output_height = output.dims()[2];
    const int output_width = output.dims()[3];
    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];
    const int stride_height = strides[0];
    const int stride_width = strides[1];
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
895
    T* input_grad_data = context.template Alloc<T>(input_grad);
896 897 898 899 900 901

    int nthreads = batch_size * output_channels * output_height * output_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

L
limingshu 已提交
902 903
    auto pool_divmods =
        FastDivModForPooling(input_channels, output_width, output_height);
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    KernelMaxPool2DGrad<T>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 output_data,
                                                 output_grad_data,
                                                 input_channels,
                                                 input_height,
                                                 input_width,
                                                 output_height,
                                                 output_width,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_height,
                                                 stride_width,
                                                 padding_height,
                                                 padding_width,
                                                 input_grad_data,
                                                 pool_divmods);
922
  }
F
From00 已提交
923 924 925 926 927 928 929 930 931
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
                  const std::string data_format,
                  DenseTensor* input_grad) {
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    bool channel_last = (data_format == "NHWC");

    const int batch_size = input.dims()[0];

    const int input_channels = channel_last ? input.dims()[3] : input.dims()[1];
    const int input_height = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_width = channel_last ? input.dims()[2] : input.dims()[3];

    const int output_channels =
        channel_last ? output.dims()[3] : output.dims()[1];
    const int output_height =
        channel_last ? output.dims()[1] : output.dims()[2];
    const int output_width = channel_last ? output.dims()[2] : output.dims()[3];

    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];

    const int stride_height = strides[0];
    const int stride_width = strides[1];

    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
958
    T* input_grad_data = context.template Alloc<T>(input_grad);
959 960 961 962 963 964

    int nthreads = batch_size * output_channels * output_height * output_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

L
limingshu 已提交
965 966 967
    auto pool_divmods =
        FastDivModForPooling(input_channels, output_width, output_height);

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    KernelMaxPool2DGrad<T>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 output_data,
                                                 output_grad_data,
                                                 input_channels,
                                                 input_height,
                                                 input_width,
                                                 output_height,
                                                 output_width,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_height,
                                                 stride_width,
                                                 padding_height,
                                                 padding_width,
                                                 input_grad_data,
                                                 pool_divmods,
                                                 channel_last);
987
  }
988 989
};

F
From00 已提交
990 991 992 993 994 995
template class Pool2dDirectCUDAFunctor<MaxPool<float>, float>;
template class Pool2dDirectCUDAFunctor<AvgPool<float>, float>;

template class MaxPool2dGradFunctor<phi::GPUContext, float>;
template class MaxPool2dGradFunctor<phi::GPUContext, double>;
template class MaxPool2dGradFunctor<phi::GPUContext, dtype::float16>;
996
template class MaxPool2dGradFunctor<phi::GPUContext, dtype::bfloat16>;
F
From00 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

template class Pool2dFunctor<phi::GPUContext, MaxPool<float>, float>;
template class Pool2dFunctor<phi::GPUContext, AvgPool<float>, float>;
template class Pool2dGradFunctor<phi::GPUContext, MaxPoolGrad<float>, float>;
template class Pool2dGradFunctor<phi::GPUContext, AvgPoolGrad<float>, float>;
template class Pool2dFunctor<phi::GPUContext, MaxPool<double>, double>;
template class Pool2dFunctor<phi::GPUContext, AvgPool<double>, double>;
template class Pool2dGradFunctor<phi::GPUContext, MaxPoolGrad<double>, double>;
template class Pool2dGradFunctor<phi::GPUContext, AvgPoolGrad<double>, double>;

template class Pool2dFunctor<phi::GPUContext,
                             MaxPool<dtype::float16>,
                             dtype::float16>;
template class Pool2dFunctor<phi::GPUContext,
                             AvgPool<dtype::float16>,
                             dtype::float16>;
template class Pool2dGradFunctor<phi::GPUContext,
                                 MaxPoolGrad<dtype::float16>,
                                 dtype::float16>;
template class Pool2dGradFunctor<phi::GPUContext,
                                 AvgPoolGrad<dtype::float16>,
                                 dtype::float16>;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
template class Pool2dFunctor<phi::GPUContext,
                             MaxPool<dtype::bfloat16>,
                             dtype::bfloat16>;
template class Pool2dFunctor<phi::GPUContext,
                             AvgPool<dtype::bfloat16>,
                             dtype::bfloat16>;
template class Pool2dGradFunctor<phi::GPUContext,
                                 MaxPoolGrad<dtype::bfloat16>,
                                 dtype::bfloat16>;
template class Pool2dGradFunctor<phi::GPUContext,
                                 AvgPoolGrad<dtype::bfloat16>,
                                 dtype::bfloat16>;
1031

1032
template <typename PoolProcess, typename T>
F
From00 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
__global__ void KernelPool3D(const int nthreads,
                             const T* input_data,
                             const int channels,
                             const int input_depth,
                             const int input_height,
                             const int input_width,
                             const int output_depth,
                             const int output_height,
                             const int output_width,
                             const int ksize_depth,
                             const int ksize_height,
                             const int ksize_width,
                             const int stride_depth,
                             const int stride_height,
                             const int stride_width,
                             const int padding_depth,
                             const int padding_height,
                             const int padding_width,
                             PoolProcess pool_process,
                             bool exclusive,
                             bool adaptive,
                             T* output_data,
                             bool channel_last = false) {
1056
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
1057
       index += blockDim.x * gridDim.x) {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    int pw, ph, pd, c, batch_idx;
    if (!channel_last) {
      pw = index % output_width;
      ph = (index / output_width) % output_height;
      pd = (index / output_width / output_height) % output_depth;
      c = (index / output_width / output_height / output_depth) % channels;
      batch_idx =
          index / output_width / output_height / output_depth / channels;
    } else {
      c = index % channels;
      pw = (index / channels) % output_width;
      ph = (index / channels / output_width) % output_height;
      pd = (index / channels / output_width / output_height) % output_depth;
      batch_idx =
          index / channels / output_width / output_height / output_depth;
    }
1074 1075 1076 1077 1078

    int dstart, dend;
    int hstart, hend;
    int wstart, wend;
    if (adaptive) {
D
dengkaipeng 已提交
1079 1080
      dstart = AdaptStartIndex(pd, input_depth, output_depth);
      dend = AdaptEndIndex(pd, input_depth, output_depth);
1081

D
dengkaipeng 已提交
1082 1083
      hstart = AdaptStartIndex(ph, input_height, output_height);
      hend = AdaptEndIndex(ph, input_height, output_height);
1084

D
dengkaipeng 已提交
1085 1086
      wstart = AdaptStartIndex(pw, input_width, output_width);
      wend = AdaptEndIndex(pw, input_width, output_width);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    } else {
      dstart = pd * stride_depth - padding_depth;
      hstart = ph * stride_height - padding_height;
      wstart = pw * stride_width - padding_width;
      dend = min(dstart + ksize_depth, input_depth);
      hend = min(hstart + ksize_height, input_height);
      wend = min(wstart + ksize_width, input_width);
      dstart = max(dstart, 0);
      hstart = max(hstart, 0);
      wstart = max(wstart, 0);
    }
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

    int input_data_stride;
    if (!channel_last) { /* NCDHW */
      input_data_stride =
          (batch_idx * channels + c) * input_depth * input_height * input_width;
    } else { /* NDHWC */
      input_data_stride =
          batch_idx * input_depth * input_height * input_width * channels;
    }
    input_data += input_data_stride;

1109
    T ele = pool_process.initial();
1110 1111 1112
    for (int d = dstart; d < dend; ++d) {
      for (int h = hstart; h < hend; ++h) {
        for (int w = wstart; w < wend; ++w) {
1113 1114 1115 1116 1117
          auto input_data_idx =
              channel_last
                  ? ((d * input_height + h) * input_width + w) * channels + c
                  : (d * input_height + h) * input_width + w;
          pool_process.compute(input_data[input_data_idx], &ele);
1118 1119 1120
        }
      }
    }
1121
    int pool_size = (exclusive || adaptive)
1122 1123
                        ? (dend - dstart) * (hend - hstart) * (wend - wstart)
                        : ksize_depth * ksize_height * ksize_width;
C
chengduo 已提交
1124
    pool_process.finalize(static_cast<T>(pool_size), &ele);
1125 1126 1127 1128
    output_data[index] = ele;
  }
}

L
limingshu 已提交
1129
template <typename T, typename PoolProcess>
F
From00 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
__global__ void KernelPool3DGrad(const int nthreads,
                                 const T* __restrict__ input_data,
                                 const T* __restrict__ output_data,
                                 const T* __restrict__ output_grad,
                                 const int channels,
                                 const int input_depth,
                                 const int input_height,
                                 const int input_width,
                                 const int output_depth,
                                 const int output_height,
                                 const int output_width,
                                 const int ksize_depth,
                                 const int ksize_height,
                                 const int ksize_width,
                                 const int stride_depth,
                                 const int stride_height,
                                 const int stride_width,
                                 const int padding_depth,
                                 const int padding_height,
                                 const int padding_width,
                                 PoolProcess pool_process,
                                 bool exclusive,
                                 bool adaptive,
                                 T* input_grad,
                                 bool channel_last = false) {
1155
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
1156
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
1157 1158
    int w_offset, h_offset, d_offset, c_offset, batch_idx, output_stride;
    T input = static_cast<T>(0);
1159 1160 1161 1162 1163
    if (!channel_last) { /* "NCDHW" */
      w_offset = index % input_width + padding_width;
      h_offset = (index / input_width) % input_height + padding_height;
      d_offset =
          (index / input_width / input_height) % input_depth + padding_depth;
L
limingshu 已提交
1164
      c_offset = (index / input_width / input_height / input_depth) % channels;
1165
      batch_idx = index / input_width / input_height / input_depth / channels;
L
limingshu 已提交
1166 1167
      output_stride = (batch_idx * channels + c_offset) * output_depth *
                      output_height * output_width;
1168
    } else { /* "NDHWC" */
L
limingshu 已提交
1169
      c_offset = index % channels;
1170 1171 1172 1173 1174 1175
      w_offset = (index / channels) % input_width + padding_width;
      h_offset =
          (index / channels / input_width) % input_height + padding_height;
      d_offset = (index / channels / input_width / input_height) % input_depth +
                 padding_depth;
      batch_idx = index / channels / input_width / input_height / input_depth;
L
limingshu 已提交
1176 1177
      output_stride =
          batch_idx * output_depth * output_height * output_width * channels;
1178
    }
1179

1180 1181 1182 1183
    int pdstart, pdend;
    int phstart, phend;
    int pwstart, pwend;
    if (adaptive) {
1184 1185 1186 1187 1188 1189 1190 1191
      pdstart = AdaptStartIndex(d_offset, output_depth, input_depth);
      pdend = AdaptEndIndex(d_offset, output_depth, input_depth);

      phstart = AdaptStartIndex(h_offset, output_height, input_height);
      phend = AdaptEndIndex(h_offset, output_height, input_height);

      pwstart = AdaptStartIndex(w_offset, output_width, input_width);
      pwend = AdaptEndIndex(w_offset, output_width, input_width);
1192
    } else {
D
dengkaipeng 已提交
1193
      pdstart = (d_offset < ksize_depth)
1194
                    ? 0
D
dengkaipeng 已提交
1195 1196
                    : (d_offset - ksize_depth) / stride_depth + 1;
      phstart = (h_offset < ksize_height)
1197
                    ? 0
D
dengkaipeng 已提交
1198 1199
                    : (h_offset - ksize_height) / stride_height + 1;
      pwstart = (w_offset < ksize_width)
1200
                    ? 0
D
dengkaipeng 已提交
1201 1202 1203 1204
                    : (w_offset - ksize_width) / stride_width + 1;
      pdend = min((d_offset) / stride_depth + 1, output_depth);
      phend = min((h_offset) / stride_height + 1, output_height);
      pwend = min((w_offset) / stride_width + 1, output_width);
1205
    }
L
limingshu 已提交
1206 1207 1208
    if (pool_process.use_x) {
      input = input_data[index];
      output_data += output_stride;
1209 1210
    }
    output_grad += output_stride;
L
limingshu 已提交
1211
    T input_grad_data = static_cast<T>(0.0);
1212 1213 1214 1215 1216

    for (int pd = pdstart; pd < pdend; ++pd) {
      for (int ph = phstart; ph < phend; ++ph) {
        for (int pw = pwstart; pw < pwend; ++pw) {
          // figure out the pooling size
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
          int pool_size;
          if (adaptive) {
            pool_size =
                static_cast<int>(
                    ceil(static_cast<double>(input_depth) / ksize_depth)) *
                static_cast<int>(
                    ceil(static_cast<double>(input_height) / ksize_height)) *
                static_cast<int>(
                    ceil(static_cast<double>(input_width) / ksize_width));
          } else {
            int dstart = pd * stride_depth - padding_depth;
            int hstart = ph * stride_height - padding_height;
            int wstart = pw * stride_width - padding_width;
            int dend = min(dstart + ksize_depth, input_depth);
            int hend = min(hstart + ksize_height, input_height);
            int wend = min(wstart + ksize_width, input_width);
            dstart = max(dstart, 0);
            hstart = max(hstart, 0);
            wstart = max(wstart, 0);
            pool_size =
                exclusive ? (dend - dstart) * (hend - hstart) * (wend - wstart)
                          : ksize_depth * ksize_height * ksize_width;
          }
1240 1241 1242 1243

          int output_sub_idx =
              channel_last
                  ? ((pd * output_height + ph) * output_width + pw) * channels +
L
limingshu 已提交
1244
                        c_offset
1245
                  : (pd * output_height + ph) * output_width + pw;
L
limingshu 已提交
1246 1247
          T ouput_value = pool_process.use_x ? output_data[output_sub_idx]
                                             : static_cast<T>(0);
F
From00 已提交
1248 1249 1250
          pool_process.compute(input,
                               ouput_value,
                               output_grad[output_sub_idx],
L
limingshu 已提交
1251 1252
                               static_cast<T>(1.0 / pool_size),
                               &input_grad_data);
1253 1254 1255
        }
      }
    }
L
limingshu 已提交
1256
    input_grad[index] = input_grad_data;
1257 1258 1259
  }
}

1260
template <typename T>
F
From00 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
__global__ void KernelMaxPool3DGrad(const int nthreads,
                                    const T* input_data,
                                    const T* output_data,
                                    const T* output_grad,
                                    const int channels,
                                    const int input_depth,
                                    const int input_height,
                                    const int input_width,
                                    const int output_depth,
                                    const int output_height,
                                    const int output_width,
                                    const int ksize_depth,
                                    const int ksize_height,
                                    const int ksize_width,
                                    const int stride_depth,
                                    const int stride_height,
                                    const int stride_width,
                                    const int padding_depth,
                                    const int padding_height,
                                    const int padding_width,
                                    T* input_grad,
                                    bool channel_last = false) {
1283
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
1284
       index += blockDim.x * gridDim.x) {
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    int pw, ph, pd, c, batch_idx;

    if (!channel_last) { /*NCDHW*/
      pw = index % output_width;
      ph = (index / output_width) % output_height;
      pd = (index / output_width / output_height) % output_depth;
      c = (index / output_width / output_height / output_depth) % channels;
      batch_idx =
          index / output_width / output_height / output_depth / channels;
    } else { /*NDHWC*/
      c = index % channels;
      pw = (index / channels) % output_width;
      ph = (index / channels / output_width) % output_height;
      pd = (index / channels / output_width / output_height) % output_depth;
      batch_idx =
          index / channels / output_width / output_height / output_depth;
    }

1303 1304 1305
    int dstart = pd * stride_depth - padding_depth;
    int hstart = ph * stride_height - padding_height;
    int wstart = pw * stride_width - padding_width;
1306

1307 1308 1309
    int dend = min(dstart + ksize_depth, input_depth);
    int hend = min(hstart + ksize_height, input_height);
    int wend = min(wstart + ksize_width, input_width);
1310

1311 1312 1313
    dstart = max(dstart, 0);
    hstart = max(hstart, 0);
    wstart = max(wstart, 0);
1314

1315 1316 1317 1318
    T ele = output_data[index];
    bool stop = false;
    int maxIdx = -1;

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    int input_stride;
    if (!channel_last) {
      input_stride =
          (batch_idx * channels + c) * input_depth * input_height * input_width;
    } else {
      input_stride =
          batch_idx * input_depth * input_height * input_width * channels;
    }
    input_data += input_stride;
    input_grad += input_stride;
1329 1330 1331
    for (int d = dstart; d < dend && !stop; ++d) {
      for (int h = hstart; h < hend && !stop; ++h) {
        for (int w = wstart; w < wend && !stop; ++w) {
1332 1333 1334 1335 1336
          int input_data_idx =
              channel_last
                  ? ((d * input_height + h) * input_width + w) * channels + c
                  : (d * input_height + h) * input_width + w;
          if (ele == input_data[input_data_idx]) {
1337
            stop = true;
1338
            maxIdx = input_data_idx;
1339 1340 1341 1342 1343 1344
          }
        }
      }
    }
    if (maxIdx != -1) {
      // atomic add
W
Wang Xin 已提交
1345
      phi::CudaAtomicAdd(input_grad + maxIdx, output_grad[index]);
1346 1347 1348 1349
    }
  }
}

F
feng_shuai 已提交
1350 1351
template <typename PoolProcess, typename T>
void Pool3dDirectCUDAFunctor<PoolProcess, T>::operator()(
F
From00 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    const T* input,
    const std::vector<int>& input_shape,
    const std::vector<int>& output_shape,
    const std::vector<int>& ksize,
    const std::vector<int>& strides,
    const std::vector<int>& paddings,
    bool exclusive,
    bool adaptive,
    T* output,
    gpuStream_t stream,
F
feng_shuai 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    PoolProcess pool_compute) {
  const int batch_size = input_shape[0];
  const int input_channels = input_shape[1];
  const int input_depth = input_shape[2];
  const int input_height = input_shape[3];
  const int input_width = input_shape[4];
  const int output_channels = output_shape[1];
  const int output_depth = output_shape[2];
  const int output_height = output_shape[3];
  const int output_width = output_shape[4];
  const int ksize_depth = ksize[0];
  const int ksize_height = ksize[1];
  const int ksize_width = ksize[2];
  const int stride_depth = strides[0];
  const int stride_height = strides[1];
  const int stride_width = strides[2];
  const int padding_depth = paddings[0];
  const int padding_height = paddings[1];
  const int padding_width = paddings[2];

  int nthreads = batch_size * output_channels * output_depth * output_height *
                 output_width;
  int thread_num = 1024;
#ifdef WITH_NV_JETSON
  thread_num = 512;
#endif
  int blocks = (nthreads + thread_num - 1) / thread_num;
  dim3 threads(thread_num, 1);
  dim3 grid(blocks, 1);

F
From00 已提交
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
  KernelPool3D<PoolProcess, T><<<grid, threads, 0, stream>>>(nthreads,
                                                             input,
                                                             input_channels,
                                                             input_depth,
                                                             input_height,
                                                             input_width,
                                                             output_depth,
                                                             output_height,
                                                             output_width,
                                                             ksize_depth,
                                                             ksize_height,
                                                             ksize_width,
                                                             stride_depth,
                                                             stride_height,
                                                             stride_width,
                                                             padding_depth,
                                                             padding_height,
                                                             padding_width,
                                                             pool_compute,
                                                             exclusive,
                                                             adaptive,
                                                             output);
F
feng_shuai 已提交
1414 1415
}

C
chengduoZH 已提交
1416
/*
1417 1418 1419 1420 1421 1422 1423
 * Tensors are in NCDHW or NDHWC format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 * Paddings are six elements. These six elements represent depth_forth,
 * depth_back,
 * height_up, height_down, width_left and width_right, respectively.
 */
1424
template <typename PoolProcess, class T>
F
From00 已提交
1425
class Pool3dFunctor<phi::GPUContext, PoolProcess, T> {
1426
 public:
F
From00 已提交
1427 1428 1429
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
C
chengduo 已提交
1430
                  const std::vector<int>& strides,
F
From00 已提交
1431 1432 1433 1434
                  const std::vector<int>& paddings,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* output,
1435
                  PoolProcess pool_process) {
1436 1437 1438 1439 1440
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_depth = input.dims()[2];
    const int input_height = input.dims()[3];
    const int input_width = input.dims()[4];
C
chengduoZH 已提交
1441 1442 1443 1444
    const int output_channels = output->dims()[1];
    const int output_depth = output->dims()[2];
    const int output_height = output->dims()[3];
    const int output_width = output->dims()[4];
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];
    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];
    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
F
From00 已提交
1456
    T* output_data = context.template Alloc<T>(output);
1457 1458 1459

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
F
feng_shuai 已提交
1460 1461
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
1462
    backends::gpu::ChangeThreadNum(context, &thread_num);
F
feng_shuai 已提交
1463 1464 1465
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
1466 1467
    dim3 grid(blocks, 1);

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    KernelPool3D<PoolProcess, T>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 pool_process,
                                                 exclusive,
                                                 adaptive,
                                                 output_data);
1491
  }
F
From00 已提交
1492 1493 1494
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
1495 1496
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
1497 1498 1499 1500 1501
                  const std::string data_format,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* output,
                  PoolProcess pool_process) {
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    bool channel_last = (data_format == "NDHWC");
    const int batch_size = input.dims()[0];

    const int input_channels = channel_last ? input.dims()[4] : input.dims()[1];
    const int input_depth = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_height = channel_last ? input.dims()[2] : input.dims()[3];
    const int input_width = channel_last ? input.dims()[3] : input.dims()[4];

    const int output_channels =
        channel_last ? output->dims()[4] : output->dims()[1];
    const int output_depth =
        channel_last ? output->dims()[1] : output->dims()[2];
    const int output_height =
        channel_last ? output->dims()[2] : output->dims()[3];
    const int output_width =
        channel_last ? output->dims()[3] : output->dims()[4];

    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];

    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];

    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
F
From00 已提交
1532
    T* output_data = context.template Alloc<T>(output);
1533 1534 1535

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
F
feng_shuai 已提交
1536 1537
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
1538
    backends::gpu::ChangeThreadNum(context, &thread_num);
F
feng_shuai 已提交
1539 1540 1541
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
1542 1543
    dim3 grid(blocks, 1);

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    KernelPool3D<PoolProcess, T>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 pool_process,
                                                 exclusive,
                                                 adaptive,
                                                 output_data,
                                                 channel_last);
1568
  }
1569 1570
};

C
chengduoZH 已提交
1571
/*
1572 1573 1574 1575 1576 1577 1578
 * Tensors are in NCDHW or NDHWC format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 * Paddings are six elements. These six elements represent depth_forth,
 * depth_back,
 * height_up, height_down, width_left and width_right, respectively.
 */
1579
template <typename PoolProcess, class T>
F
From00 已提交
1580
class Pool3dGradFunctor<phi::GPUContext, PoolProcess, T> {
1581
 public:
F
From00 已提交
1582 1583 1584 1585
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
C
chengduo 已提交
1586 1587
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
F
From00 已提交
1588 1589 1590 1591
                  const std::vector<int>& paddings,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* input_grad,
1592
                  PoolProcess pool_process) {
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_depth = input.dims()[2];
    const int input_height = input.dims()[3];
    const int input_width = input.dims()[4];
    const int output_channels = output.dims()[1];
    const int output_depth = output.dims()[2];
    const int output_height = output.dims()[3];
    const int output_width = output.dims()[4];
    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];
    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];
    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
1615
    T* input_grad_data = context.template Alloc<T>(input_grad);
1616

1617 1618
    int nthreads =
        batch_size * input_channels * input_depth * input_height * input_width;
1619 1620 1621 1622
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
    KernelPool3DGrad<T, PoolProcess>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 output_data,
                                                 output_grad_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 pool_process,
                                                 exclusive,
                                                 adaptive,
                                                 input_grad_data);
1648
  }
F
From00 已提交
1649 1650 1651 1652
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
1653 1654 1655
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
1656 1657 1658 1659 1660
                  const std::string data_format,
                  bool exclusive,
                  bool adaptive,
                  DenseTensor* input_grad,
                  PoolProcess pool_process) {
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
    bool channel_last = (data_format == "NDHWC");

    const int batch_size = input.dims()[0];
    const int input_channels = channel_last ? input.dims()[4] : input.dims()[1];
    const int input_depth = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_height = channel_last ? input.dims()[2] : input.dims()[3];
    const int input_width = channel_last ? input.dims()[3] : input.dims()[4];

    const int output_channels =
        channel_last ? output.dims()[4] : output.dims()[1];
    const int output_depth = channel_last ? output.dims()[1] : output.dims()[2];
    const int output_height =
        channel_last ? output.dims()[2] : output.dims()[3];
    const int output_width = channel_last ? output.dims()[3] : output.dims()[4];

    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];

    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];

    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
1691
    T* input_grad_data = context.template Alloc<T>(input_grad);
1692 1693 1694 1695 1696 1697 1698

    int nthreads =
        batch_size * input_channels * input_depth * input_height * input_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

L
limingshu 已提交
1699
    KernelPool3DGrad<T, PoolProcess><<<grid, threads, 0, context.stream()>>>(
F
From00 已提交
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
        nthreads,
        input_data,
        output_data,
        output_grad_data,
        input_channels,
        input_depth,
        input_height,
        input_width,
        output_depth,
        output_height,
        output_width,
        ksize_depth,
        ksize_height,
        ksize_width,
        stride_depth,
        stride_height,
        stride_width,
        padding_depth,
        padding_height,
        padding_width,
        pool_process,
        exclusive,
        adaptive,
        input_grad_data,
1724 1725
        channel_last);  // add channel_last
  }
1726 1727
};

C
chengduoZH 已提交
1728
/*
1729 1730 1731 1732 1733 1734 1735
 * tensors are in NCDHW or NDHWC format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 * Paddings are six elements. These six elements represent depth_forth,
 * depth_back,
 * height_up, height_down, width_left and width_right, respectively.
 */
1736
template <class T>
F
From00 已提交
1737
class MaxPool3dGradFunctor<phi::GPUContext, T> {
1738
 public:
F
From00 已提交
1739 1740 1741 1742
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
C
chengduo 已提交
1743 1744 1745
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
F
From00 已提交
1746
                  DenseTensor* input_grad) {
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_depth = input.dims()[2];
    const int input_height = input.dims()[3];
    const int input_width = input.dims()[4];
    const int output_channels = output.dims()[1];
    const int output_depth = output.dims()[2];
    const int output_height = output.dims()[3];
    const int output_width = output.dims()[4];
    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];
    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];
    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
1769
    T* input_grad_data = context.template Alloc<T>(input_grad);
1770 1771 1772 1773 1774 1775 1776

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
    KernelMaxPool3DGrad<T>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 input_data,
                                                 output_data,
                                                 output_grad_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 input_grad_data);
1799
  }
F
From00 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const DenseTensor& output,
                  const DenseTensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
                  const std::string data_format,
                  DenseTensor* input_grad) {
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
    bool channel_last = (data_format == "NDHWC");
    const int batch_size = input.dims()[0];

    const int input_channels = channel_last ? input.dims()[4] : input.dims()[1];
    const int input_depth = channel_last ? input.dims()[1] : input.dims()[2];
    const int input_height = channel_last ? input.dims()[2] : input.dims()[3];
    const int input_width = channel_last ? input.dims()[3] : input.dims()[4];

    const int output_channels =
        channel_last ? output.dims()[4] : output.dims()[1];
    const int output_depth = channel_last ? output.dims()[1] : output.dims()[2];
    const int output_height =
        channel_last ? output.dims()[2] : output.dims()[3];
    const int output_width = channel_last ? output.dims()[3] : output.dims()[4];

    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];

    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];

    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

    const T* input_data = input.data<T>();
    const T* output_data = output.data<T>();
    const T* output_grad_data = output_grad.data<T>();
F
From00 已提交
1839
    T* input_grad_data = context.template Alloc<T>(input_grad);
1840 1841 1842 1843 1844 1845 1846 1847

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

    KernelMaxPool3DGrad<T><<<grid, threads, 0, context.stream()>>>(
F
From00 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
        nthreads,
        input_data,
        output_data,
        output_grad_data,
        input_channels,
        input_depth,
        input_height,
        input_width,
        output_depth,
        output_height,
        output_width,
        ksize_depth,
        ksize_height,
        ksize_width,
        stride_depth,
        stride_height,
        stride_width,
        padding_depth,
        padding_height,
        padding_width,
        input_grad_data,
        channel_last);  // add channel_last
1870
  }
1871 1872
};

F
From00 已提交
1873 1874 1875 1876 1877 1878
template class Pool3dDirectCUDAFunctor<MaxPool<float>, float>;
template class Pool3dDirectCUDAFunctor<AvgPool<float>, float>;

template class MaxPool3dGradFunctor<phi::GPUContext, float>;
template class MaxPool3dGradFunctor<phi::GPUContext, double>;
template class MaxPool3dGradFunctor<phi::GPUContext, dtype::float16>;
1879
template class MaxPool3dGradFunctor<phi::GPUContext, dtype::bfloat16>;
F
From00 已提交
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895

template class Pool3dFunctor<phi::GPUContext, MaxPool<float>, float>;
template class Pool3dFunctor<phi::GPUContext, AvgPool<float>, float>;
template class Pool3dGradFunctor<phi::GPUContext, MaxPoolGrad<float>, float>;
template class Pool3dGradFunctor<phi::GPUContext, AvgPoolGrad<float>, float>;
template class Pool3dFunctor<phi::GPUContext, MaxPool<double>, double>;
template class Pool3dFunctor<phi::GPUContext, AvgPool<double>, double>;
template class Pool3dGradFunctor<phi::GPUContext, MaxPoolGrad<double>, double>;
template class Pool3dGradFunctor<phi::GPUContext, AvgPoolGrad<double>, double>;

template class Pool3dFunctor<phi::GPUContext,
                             MaxPool<dtype::float16>,
                             dtype::float16>;
template class Pool3dFunctor<phi::GPUContext,
                             AvgPool<dtype::float16>,
                             dtype::float16>;
1896 1897 1898 1899 1900 1901
template class Pool3dFunctor<phi::GPUContext,
                             MaxPool<dtype::bfloat16>,
                             dtype::bfloat16>;
template class Pool3dFunctor<phi::GPUContext,
                             AvgPool<dtype::bfloat16>,
                             dtype::bfloat16>;
F
From00 已提交
1902 1903 1904 1905 1906 1907
template class Pool3dGradFunctor<phi::GPUContext,
                                 MaxPoolGrad<dtype::float16>,
                                 dtype::float16>;
template class Pool3dGradFunctor<phi::GPUContext,
                                 AvgPoolGrad<dtype::float16>,
                                 dtype::float16>;
1908 1909 1910 1911 1912 1913
template class Pool3dGradFunctor<phi::GPUContext,
                                 MaxPoolGrad<dtype::bfloat16>,
                                 dtype::bfloat16>;
template class Pool3dGradFunctor<phi::GPUContext,
                                 AvgPoolGrad<dtype::bfloat16>,
                                 dtype::bfloat16>;
1914

C
chengduoZH 已提交
1915
template <typename T1, typename T2>
F
From00 已提交
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
__global__ void KernelMaxPool2dWithIdx(const int nthreads,
                                       const T1* input_data,
                                       const int channels,
                                       const int input_height,
                                       const int input_width,
                                       const int output_height,
                                       const int output_width,
                                       const int ksize_height,
                                       const int ksize_width,
                                       const int stride_height,
                                       const int stride_width,
                                       const int padding_height,
                                       const int padding_width,
                                       bool adaptive,
                                       T1* output_data,
                                       T2* mask_data,
                                       FastDivModForPooling divmods) {
C
chengduoZH 已提交
1933
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
1934
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
1935 1936
    int hstart, hend, wstart, wend;
    int w_offset, h_offset, c_offset, input_offset;
F
From00 已提交
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
    OffsetPreparationFor4Dimension<FastDivModForPooling>(index,
                                                         false,
                                                         divmods,
                                                         0,
                                                         0,
                                                         input_width,
                                                         input_height,
                                                         &w_offset,
                                                         &h_offset,
                                                         &c_offset,
                                                         &input_offset);
L
limingshu 已提交
1948
    input_data += input_offset;
C
chengduoZH 已提交
1949

1950
    if (adaptive) {
L
limingshu 已提交
1951 1952
      hstart = AdaptStartIndex(h_offset, input_height, output_height);
      hend = AdaptEndIndex(h_offset, input_height, output_height);
C
chengduoZH 已提交
1953

L
limingshu 已提交
1954 1955
      wstart = AdaptStartIndex(w_offset, input_width, output_width);
      wend = AdaptEndIndex(w_offset, input_width, output_width);
1956
    } else {
L
limingshu 已提交
1957
      hstart = h_offset * stride_height - padding_height;
1958 1959 1960
      hend = min(hstart + ksize_height, input_height);
      hstart = max(hstart, 0);

L
limingshu 已提交
1961
      wstart = w_offset * stride_width - padding_width;
1962 1963 1964
      wend = min(wstart + ksize_width, input_width);
      wstart = max(wstart, 0);
    }
C
chengduoZH 已提交
1965

C
chengduoZH 已提交
1966
    T1 ele = -FLT_MAX;
C
chengduoZH 已提交
1967
    int max_index = -1;
C
chengduoZH 已提交
1968 1969
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
C
chengduoZH 已提交
1970 1971 1972 1973
        int input_index = h * input_width + w;
        if (ele < input_data[input_index]) {
          max_index = input_index;
          ele = input_data[input_index];
C
chengduoZH 已提交
1974 1975 1976 1977
        }
      }
    }
    output_data[index] = ele;
C
chengduoZH 已提交
1978
    mask_data[index] = max_index;
C
chengduoZH 已提交
1979 1980 1981
  }
}

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
template <typename T1, typename T2>
__global__ void AdaptiveKernelMaxPool2dWithIdx(const int nthreads,
                                               const T1* input_data,
                                               const int channels,
                                               const int input_height,
                                               const int input_width,
                                               const int output_height,
                                               const int output_width,
                                               const int ksize_height,
                                               const int ksize_width,
                                               const int stride_height,
                                               const int stride_width,
                                               const int padding_height,
                                               const int padding_width,
                                               T1* output_data,
                                               T2* mask_data,
                                               FastDivModForPooling divmods) {
  const int n_offset = blockIdx.y;
  const int c_offset = blockIdx.x * blockDim.y + threadIdx.y;
  if (c_offset >= channels) {
    return;
  }
  int hstart, hend, wstart, wend;
  int input_offset =
      (n_offset * channels + c_offset) * input_height * input_width;
  int output_offset =
      (n_offset * channels + c_offset) * output_height * output_width;
  for (int hw_offset = threadIdx.x; hw_offset < output_height * output_width;
       hw_offset += blockDim.x) {
    int w_offset = hw_offset % output_width;
    int h_offset = hw_offset / output_width;
    hstart = AdaptStartIndex(h_offset, input_height, output_height);
    hend = AdaptEndIndex(h_offset, input_height, output_height);
    wstart = AdaptStartIndex(w_offset, input_width, output_width);
    wend = AdaptEndIndex(w_offset, input_width, output_width);

    T1 ele = -FLT_MAX;
    int max_index = -1;
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
        int input_index = h * input_width + w;
        if (ele < input_data[input_offset + input_index]) {
          max_index = input_index;
          ele = input_data[input_offset + input_index];
        }
      }
    }
    int output_idx = output_offset + h_offset * output_width + w_offset;
    output_data[output_idx] = ele;
    mask_data[output_idx] = max_index;
  }
}

C
chengduoZH 已提交
2035
template <typename T1, typename T2>
F
From00 已提交
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
__global__ void KernelMaxPool2DWithIdxGrad(const int nthreads,
                                           const T1* output_grad,
                                           const T2* mask_data,
                                           const int channels,
                                           const int input_height,
                                           const int input_width,
                                           const int output_height,
                                           const int output_width,
                                           const int ksize_height,
                                           const int ksize_width,
                                           const int stride_height,
                                           const int stride_width,
                                           const int padding_height,
                                           const int padding_width,
                                           bool adaptive,
                                           T1* input_grad,
                                           FastDivModForPooling divmods) {
C
chengduoZH 已提交
2053
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
2054
       index += blockDim.x * gridDim.x) {
L
limingshu 已提交
2055 2056
    int phstart, phend, pwstart, pwend;
    int w_offset, h_offset, c_offset, output_offset;
F
From00 已提交
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    OffsetPreparationFor4Dimension<FastDivModForPooling>(index,
                                                         false,
                                                         divmods,
                                                         0,
                                                         0,
                                                         output_width,
                                                         output_height,
                                                         &w_offset,
                                                         &h_offset,
                                                         &c_offset,
                                                         &output_offset);
L
limingshu 已提交
2068 2069
    mask_data += output_offset;
    output_grad += output_offset;
C
chengduoZH 已提交
2070

2071
    if (adaptive) {
D
dengkaipeng 已提交
2072
      phstart = h_offset * output_height / input_height;
2073
      phend =
D
dengkaipeng 已提交
2074 2075 2076 2077
          min((h_offset + 1) * output_height / input_height + 1, output_height);
      pwstart = w_offset * output_width / input_width;
      pwend =
          min((w_offset + 1) * output_width / input_width + 1, output_width);
2078 2079
    } else {
      phstart =
D
dengkaipeng 已提交
2080
          (h_offset + padding_height < ksize_height)
2081
              ? 0
D
dengkaipeng 已提交
2082
              : (h_offset + padding_height - ksize_height) / stride_height + 1;
2083
      pwstart =
D
dengkaipeng 已提交
2084
          (w_offset + padding_width < ksize_width)
2085
              ? 0
D
dengkaipeng 已提交
2086
              : (w_offset + padding_width - ksize_width) / stride_width + 1;
2087
      phend =
D
dengkaipeng 已提交
2088 2089
          min((h_offset + padding_height) / stride_height + 1, output_height);
      pwend = min((w_offset + padding_width) / stride_width + 1, output_width);
2090
    }
C
chengduoZH 已提交
2091

L
limingshu 已提交
2092
    T1 input_grad_data = 0;
D
dengkaipeng 已提交
2093
    int input_current_featuremap_idx = h_offset * input_width + w_offset;
2094 2095
    for (int ph = phstart; ph < phend; ++ph) {
      for (int pw = pwstart; pw < pwend; ++pw) {
C
chengduoZH 已提交
2096
        if (mask_data[ph * output_width + pw] == input_current_featuremap_idx)
L
limingshu 已提交
2097
          input_grad_data += output_grad[ph * output_width + pw];
C
chengduoZH 已提交
2098 2099
      }
    }
L
limingshu 已提交
2100
    input_grad[index] = input_grad_data;
C
chengduoZH 已提交
2101 2102 2103
  }
}

C
chengduoZH 已提交
2104 2105 2106 2107 2108
/*
 * All tensors are in NCHW format.
 * Ksize, strides, paddings are two elements. These two elements represent
 * height and width, respectively.
 */
C
chengduoZH 已提交
2109
template <typename T1, typename T2>
F
From00 已提交
2110
class MaxPool2dWithIndexFunctor<phi::GPUContext, T1, T2> {
C
chengduoZH 已提交
2111
 public:
F
From00 已提交
2112 2113 2114
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
C
chengduo 已提交
2115
                  const std::vector<int>& strides,
F
From00 已提交
2116 2117 2118 2119
                  const std::vector<int>& paddings,
                  bool adaptive,
                  DenseTensor* output,
                  DenseTensor* mask) {
C
chengduoZH 已提交
2120 2121 2122 2123
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_height = input.dims()[2];
    const int input_width = input.dims()[3];
C
chengduoZH 已提交
2124 2125 2126
    const int output_channels = output->dims()[1];
    const int output_height = output->dims()[2];
    const int output_width = output->dims()[3];
C
chengduoZH 已提交
2127 2128 2129 2130 2131 2132 2133
    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];
    const int stride_height = strides[0];
    const int stride_width = strides[1];
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

C
chengduoZH 已提交
2134
    const T1* input_data = input.data<T1>();
F
From00 已提交
2135 2136
    T1* output_data = context.template Alloc<T1>(output);
    T2* mask_data = context.template Alloc<T2>(mask);
C
chengduoZH 已提交
2137 2138

    int nthreads = batch_size * output_channels * output_height * output_width;
L
limingshu 已提交
2139 2140
    auto pool_divmods =
        FastDivModForPooling(input_channels, output_width, output_height);
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
    if (adaptive && output_height > 1 && output_width > 1) {
      int max_threads = 512;
      int thread_num = std::min(
          phi::funcs::details::GetLastPow2(output_height * output_width),
          max_threads);
      int blocks = std::min(max_threads / thread_num, output_channels);
      dim3 threads(thread_num, blocks, 1);
      dim3 grid(
          std::max((output_channels + blocks - 1) / blocks, 1), batch_size, 1);
      AdaptiveKernelMaxPool2dWithIdx<T1, T2>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   output_data,
                                                   mask_data,
                                                   pool_divmods);
    } else {
      int thread_num = 1024;
#ifdef WITH_NV_JETSON
      backends::gpu::ChangeThreadNum(context, &thread_num);
#endif
      int blocks = (nthreads + thread_num - 1) / thread_num;
      dim3 threads(thread_num, 1);
      dim3 grid(blocks, 1);
      KernelMaxPool2dWithIdx<T1, T2>
          <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                   input_data,
                                                   input_channels,
                                                   input_height,
                                                   input_width,
                                                   output_height,
                                                   output_width,
                                                   ksize_height,
                                                   ksize_width,
                                                   stride_height,
                                                   stride_width,
                                                   padding_height,
                                                   padding_width,
                                                   adaptive,
                                                   output_data,
                                                   mask_data,
                                                   pool_divmods);
    }
C
chengduoZH 已提交
2194 2195 2196
  }
};

C
chengduoZH 已提交
2197 2198 2199 2200 2201
/*
 * All tensors are in NCHW format.
 * Ksize, strides, paddings are two elements. These two elements represent
 * height and width, respectively.
 */
C
chengduoZH 已提交
2202
template <typename T1, typename T2>
F
From00 已提交
2203
class MaxPool2dWithIndexGradFunctor<phi::GPUContext, T1, T2> {
C
chengduoZH 已提交
2204
 public:
F
From00 已提交
2205 2206 2207 2208
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& output_grad,
                  const DenseTensor& mask,
                  const std::vector<int>& ksize,
C
chengduo 已提交
2209
                  const std::vector<int>& strides,
F
From00 已提交
2210 2211 2212
                  const std::vector<int>& paddings,
                  bool adaptive,
                  DenseTensor* input_grad) {
C
chengduoZH 已提交
2213 2214 2215 2216
    const int batch_size = input_grad->dims()[0];
    const int input_channels = input_grad->dims()[1];
    const int input_height = input_grad->dims()[2];
    const int input_width = input_grad->dims()[3];
C
chengduoZH 已提交
2217 2218 2219 2220 2221 2222 2223 2224 2225
    const int output_height = output_grad.dims()[2];
    const int output_width = output_grad.dims()[3];
    const int ksize_height = ksize[0];
    const int ksize_width = ksize[1];
    const int stride_height = strides[0];
    const int stride_width = strides[1];
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

C
chengduoZH 已提交
2226 2227
    const T2* mask_data = mask.data<T2>();
    const T1* output_grad_data = output_grad.data<T1>();
F
From00 已提交
2228
    T1* input_grad_data = context.template Alloc<T1>(input_grad);
C
chengduoZH 已提交
2229 2230 2231 2232 2233 2234

    int nthreads = batch_size * input_channels * input_height * input_width;
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

L
limingshu 已提交
2235 2236
    auto pool_divmods =
        FastDivModForPooling(input_channels, input_width, input_height);
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
    KernelMaxPool2DWithIdxGrad<T1, T2>
        <<<grid, threads, 0, context.stream()>>>(nthreads,
                                                 output_grad_data,
                                                 mask_data,
                                                 input_channels,
                                                 input_height,
                                                 input_width,
                                                 output_height,
                                                 output_width,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_height,
                                                 stride_width,
                                                 padding_height,
                                                 padding_width,
                                                 adaptive,
                                                 input_grad_data,
                                                 pool_divmods);
C
chengduoZH 已提交
2255 2256 2257
  }
};

F
From00 已提交
2258 2259 2260 2261
template class MaxPool2dWithIndexFunctor<phi::GPUContext, float, int>;
template class MaxPool2dWithIndexGradFunctor<phi::GPUContext, float, int>;
template class MaxPool2dWithIndexFunctor<phi::GPUContext, double, int>;
template class MaxPool2dWithIndexGradFunctor<phi::GPUContext, double, int>;
C
chengduoZH 已提交
2262

C
chengduoZH 已提交
2263
template <typename T1, typename T2>
2264
__global__ void KernelMaxPool3DWithIdx(const int ncd,
F
From00 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
                                       const T1* input_data,
                                       const int channels,
                                       const int input_depth,
                                       const int input_height,
                                       const int input_width,
                                       const int output_depth,
                                       const int output_height,
                                       const int output_width,
                                       const int ksize_depth,
                                       const int ksize_height,
                                       const int ksize_width,
                                       const int stride_depth,
                                       const int stride_height,
                                       const int stride_width,
                                       const int padding_depth,
                                       const int padding_height,
                                       const int padding_width,
                                       bool adaptive,
                                       T1* output_data,
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
                                       T2* mask_data,
                                       FastDivModForPooling3D divmods_output) {
  int w_offset, h_offset, d_offset, nc_offset;
  int dstart, dend, hstart, hend, wstart, wend;
  const T1* input_data_cur;

  w_offset = blockIdx.x * blockDim.x + threadIdx.x;
  h_offset = blockIdx.y * blockDim.y + threadIdx.y;

  if (w_offset < output_width && h_offset < output_height) {
    for (int index_z = blockIdx.z * blockDim.z + threadIdx.z; index_z < ncd;
         index_z += gridDim.z * blockDim.z) {
      auto output_depth_divmod = divmods_output.depth.Divmod(index_z);
      d_offset = output_depth_divmod.val[1];
      nc_offset = output_depth_divmod.val[0];
      int output_index =
          nc_offset * output_depth * output_height * output_width +
          d_offset * output_height * output_width + h_offset * output_width +
          w_offset;
      int input_offset = nc_offset * input_depth * input_height * input_width;
      input_data_cur = input_data + input_offset;

      if (adaptive) {
        dstart = AdaptStartIndex(d_offset, input_depth, output_depth);
        dend = AdaptEndIndex(d_offset, input_depth, output_depth);

        hstart = AdaptStartIndex(h_offset, input_height, output_height);
        hend = AdaptEndIndex(h_offset, input_height, output_height);

        wstart = AdaptStartIndex(w_offset, input_width, output_width);
        wend = AdaptEndIndex(w_offset, input_width, output_width);
      } else {
        dstart = d_offset * stride_depth - padding_depth;
        hstart = h_offset * stride_height - padding_height;
        wstart = w_offset * stride_width - padding_width;
        dend = min(dstart + ksize_depth, input_depth);
        hend = min(hstart + ksize_height, input_height);
        wend = min(wstart + ksize_width, input_width);
        dstart = max(dstart, 0);
        hstart = max(hstart, 0);
        wstart = max(wstart, 0);
      }
C
chengduoZH 已提交
2326

2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
      T1 ele = -FLT_MAX;
      int max_index = -1;
      for (int d = dstart; d < dend; ++d) {
        for (int h = hstart; h < hend; ++h) {
          for (int w = wstart; w < wend; ++w) {
            if (ele <
                input_data_cur[(d * input_height + h) * input_width + w]) {
              max_index = (d * input_height + h) * input_width + w;
              ele = input_data_cur[max_index];
            }
C
chengduoZH 已提交
2337 2338 2339
          }
        }
      }
2340 2341
      output_data[output_index] = ele;
      mask_data[output_index] = max_index;
C
chengduoZH 已提交
2342 2343 2344 2345
    }
  }
}

C
chengduoZH 已提交
2346
template <typename T1, typename T2>
5
5u13 已提交
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
__global__ void KernelMaxPool3DWithIdxGrad(
    const int ncd,
    const T1* output_grad,
    const T2* mask,
    const int channels,
    const int input_depth,
    const int input_height,
    const int input_width,
    const int output_depth,
    const int output_height,
    const int output_width,
    const int ksize_depth,
    const int ksize_height,
    const int ksize_width,
    const int stride_depth,
    const int stride_height,
    const int stride_width,
    const int padding_depth,
    const int padding_height,
    const int padding_width,
    bool adaptive,
    T1* input_grad,
    FastDivModForPooling3D divmods_output) {
  int w_offset, h_offset, d_offset, nc_offset;
C
chengduoZH 已提交
2371

5
5u13 已提交
2372 2373
  w_offset = blockIdx.x * blockDim.x + threadIdx.x;
  h_offset = blockIdx.y * blockDim.y + threadIdx.y;
C
chengduoZH 已提交
2374

5
5u13 已提交
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
  if (w_offset < output_width && h_offset < output_height) {
    for (int index_z = blockIdx.z * blockDim.z + threadIdx.z; index_z < ncd;
         index_z += gridDim.z * blockDim.z) {
      auto output_depth_divmod = divmods_output.depth.Divmod(index_z);
      d_offset = output_depth_divmod.val[1];
      nc_offset = output_depth_divmod.val[0];
      int output_index =
          nc_offset * output_depth * output_height * output_width +
          d_offset * output_height * output_width + h_offset * output_width +
          w_offset;
      int max_index = mask[output_index];
      if (max_index != -1) {
W
Wang Xin 已提交
2387
        phi::CudaAtomicAdd(
5
5u13 已提交
2388 2389 2390
            &input_grad[nc_offset * input_depth * input_height * input_width +
                        max_index],
            output_grad[output_index]);
C
chengduoZH 已提交
2391 2392 2393 2394 2395
      }
    }
  }
}

C
chengduoZH 已提交
2396 2397 2398 2399 2400
/*
 * All tensors are in NCDHW format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 */
C
chengduoZH 已提交
2401
template <typename T1, typename T2>
F
From00 已提交
2402
class MaxPool3dWithIndexFunctor<phi::GPUContext, T1, T2> {
C
chengduoZH 已提交
2403
 public:
F
From00 已提交
2404 2405 2406
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& input,
                  const std::vector<int>& ksize,
C
chengduo 已提交
2407
                  const std::vector<int>& strides,
F
From00 已提交
2408 2409 2410 2411
                  const std::vector<int>& paddings,
                  bool adaptive,
                  DenseTensor* output,
                  DenseTensor* mask) {
C
chengduoZH 已提交
2412 2413 2414 2415 2416
    const int batch_size = input.dims()[0];
    const int input_channels = input.dims()[1];
    const int input_depth = input.dims()[2];
    const int input_height = input.dims()[3];
    const int input_width = input.dims()[4];
C
chengduoZH 已提交
2417 2418 2419 2420
    const int output_channels = output->dims()[1];
    const int output_depth = output->dims()[2];
    const int output_height = output->dims()[3];
    const int output_width = output->dims()[4];
C
chengduoZH 已提交
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];
    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];
    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

C
chengduoZH 已提交
2431
    const T1* input_data = input.data<T1>();
F
From00 已提交
2432 2433
    T1* output_data = context.template Alloc<T1>(output);
    T2* mask_data = context.template Alloc<T2>(mask);
C
chengduoZH 已提交
2434

2435
    int ncd = batch_size * input_channels * output_depth;
F
feng_shuai 已提交
2436

2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
    int thread_x = 32;
    int thread_y = 8;
    int thread_z = 1;
    dim3 threads(thread_x, thread_y, thread_z);
    std::array<int, 3> max_grid_dim = context.GetCUDAMaxGridDimSize();
    int block_x = (output_width + threads.x - 1) / threads.x;
    int block_y = (output_height + threads.y - 1) / threads.y;
    int block_z = (ncd > max_grid_dim[2] * threads.z)
                      ? max_grid_dim[2]
                      : (ncd + threads.z - 1) / threads.z;
    dim3 grid(block_x, block_y, block_z);

    auto pool_divmods_output = FastDivModForPooling3D(
        input_channels, output_width, output_height, output_depth);
C
chengduoZH 已提交
2451

2452
    KernelMaxPool3DWithIdx<T1, T2>
2453
        <<<grid, threads, 0, context.stream()>>>(ncd,
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
                                                 input_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 adaptive,
                                                 output_data,
2473 2474
                                                 mask_data,
                                                 pool_divmods_output);
C
chengduoZH 已提交
2475 2476 2477
  }
};

C
chengduoZH 已提交
2478 2479 2480 2481 2482
/*
 * All tensors are in NCDHW format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 */
C
chengduoZH 已提交
2483
template <typename T1, typename T2>
F
From00 已提交
2484
class MaxPool3dWithIndexGradFunctor<phi::GPUContext, T1, T2> {
C
chengduoZH 已提交
2485
 public:
F
From00 已提交
2486 2487 2488 2489
  void operator()(const phi::GPUContext& context,
                  const DenseTensor& output_grad,
                  const DenseTensor& mask,
                  const std::vector<int>& ksize,
C
chengduo 已提交
2490
                  const std::vector<int>& strides,
F
From00 已提交
2491 2492 2493
                  const std::vector<int>& paddings,
                  bool adaptive,
                  DenseTensor* input_grad) {
C
chengduoZH 已提交
2494 2495 2496 2497 2498
    const int batch_size = input_grad->dims()[0];
    const int input_channels = input_grad->dims()[1];
    const int input_depth = input_grad->dims()[2];
    const int input_height = input_grad->dims()[3];
    const int input_width = input_grad->dims()[4];
C
chengduoZH 已提交
2499 2500 2501
    const int output_depth = output_grad.dims()[2];
    const int output_height = output_grad.dims()[3];
    const int output_width = output_grad.dims()[4];
C
chengduoZH 已提交
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
    const int ksize_depth = ksize[0];
    const int ksize_height = ksize[1];
    const int ksize_width = ksize[2];
    const int stride_depth = strides[0];
    const int stride_height = strides[1];
    const int stride_width = strides[2];
    const int padding_depth = paddings[0];
    const int padding_height = paddings[1];
    const int padding_width = paddings[2];

C
chengduoZH 已提交
2512 2513
    const T1* output_grad_data = output_grad.data<T1>();
    const T2* mask_data = mask.data<T2>();
F
From00 已提交
2514
    T1* input_grad_data = context.template Alloc<T1>(input_grad);
C
chengduoZH 已提交
2515

5
5u13 已提交
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
    int ncd = batch_size * input_channels * output_depth;

    int thread_x = 32;
    int thread_y = 8;
    int thread_z = 1;
    dim3 threads(thread_x, thread_y, thread_z);
    std::array<int, 3> max_grid_dim = context.GetCUDAMaxGridDimSize();
    int block_x = (output_width + threads.x - 1) / threads.x;
    int block_y = (output_height + threads.y - 1) / threads.y;
    int block_z = (ncd > max_grid_dim[2] * threads.z)
                      ? max_grid_dim[2]
                      : (ncd + threads.z - 1) / threads.z;
    dim3 grid(block_x, block_y, block_z);

    auto pool_divmods_output = FastDivModForPooling3D(
        input_channels, output_width, output_height, output_depth);
C
chengduoZH 已提交
2532

2533
    KernelMaxPool3DWithIdxGrad<T1, T2>
5
5u13 已提交
2534
        <<<grid, threads, 0, context.stream()>>>(ncd,
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
                                                 output_grad_data,
                                                 mask_data,
                                                 input_channels,
                                                 input_depth,
                                                 input_height,
                                                 input_width,
                                                 output_depth,
                                                 output_height,
                                                 output_width,
                                                 ksize_depth,
                                                 ksize_height,
                                                 ksize_width,
                                                 stride_depth,
                                                 stride_height,
                                                 stride_width,
                                                 padding_depth,
                                                 padding_height,
                                                 padding_width,
                                                 adaptive,
5
5u13 已提交
2554 2555
                                                 input_grad_data,
                                                 pool_divmods_output);
C
chengduoZH 已提交
2556 2557 2558
  }
};

F
From00 已提交
2559 2560 2561 2562 2563 2564 2565
template class MaxPool3dWithIndexFunctor<phi::GPUContext, float, int>;
template class MaxPool3dWithIndexGradFunctor<phi::GPUContext, float, int>;
template class MaxPool3dWithIndexFunctor<phi::GPUContext, double, int>;
template class MaxPool3dWithIndexGradFunctor<phi::GPUContext, double, int>;

}  // namespace funcs
}  // namespace phi