pooling.cu 72.2 KB
Newer Older
1
/* Copyright (c) 2016 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

Y
Yi Wang 已提交
18
#include "paddle/fluid/operators/math/pooling.h"
D
dzhwinter 已提交
19
#include "paddle/fluid/platform/cuda_primitives.h"
F
feng_shuai 已提交
20
#include "paddle/fluid/platform/gpu_launch_config.h"
C
chengduoZH 已提交
21 22 23 24 25

namespace paddle {
namespace operators {
namespace math {

26
template <typename PoolProcess, typename T>
27
__global__ void KernelPool2D(const int nthreads, const T* input_data,
C
chengduoZH 已提交
28 29 30 31 32 33
                             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, PoolProcess pool_process,
34 35
                             bool exclusive, bool adaptive, T* output_data,
                             bool channel_last = false) {
36 37
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
38 39 40 41 42 43 44 45 46 47 48 49
    int pw, ph, c, batch_idx;
    if (!channel_last) { /*NCHW*/
      pw = index % output_width;
      ph = (index / output_width) % output_height;
      c = (index / output_width / output_height) % channels;
      batch_idx = index / output_width / output_height / channels;
    } else { /*NHWC*/
      c = index % channels;
      pw = (index / channels) % output_width;
      ph = (index / channels / output_width) % output_height;
      batch_idx = index / channels / output_width / output_height;
    }
50

51 52
    int hstart, hend;
    int wstart, wend;
D
dengkaipeng 已提交
53
    if (adaptive) {
D
dengkaipeng 已提交
54 55
      hstart = AdaptStartIndex(ph, input_height, output_height);
      hend = AdaptEndIndex(ph, input_height, output_height);
56

D
dengkaipeng 已提交
57 58
      wstart = AdaptStartIndex(pw, input_width, output_width);
      wend = AdaptEndIndex(pw, input_width, output_width);
D
dengkaipeng 已提交
59
    } else {
60 61
      hstart = ph * stride_height - padding_height;
      hend = min(hstart + ksize_height, input_height);
D
dengkaipeng 已提交
62 63
      hstart = max(hstart, 0);

64 65
      wstart = pw * stride_width - padding_width;
      wend = min(wstart + ksize_width, input_width);
D
dengkaipeng 已提交
66 67
      wstart = max(wstart, 0);
    }
68

69 70 71 72 73
    if (!channel_last) {
      input_data += (batch_idx * channels + c) * input_height * input_width;
    } else {
      input_data += batch_idx * input_height * input_width * channels;
    }
74
    T ele = pool_process.initial();
75 76
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
77 78 79
        auto input_idx = channel_last ? (h * input_width + w) * channels + c
                                      : h * input_width + w;
        pool_process.compute(input_data[input_idx], &ele);
80 81
      }
    }
D
dengkaipeng 已提交
82 83
    int pool_size = (exclusive || adaptive) ? (hend - hstart) * (wend - wstart)
                                            : ksize_height * ksize_width;
C
chengduo 已提交
84
    pool_process.finalize(static_cast<T>(pool_size), &ele);
85 86 87 88
    output_data[index] = ele;
  }
}
template <typename PoolProcess, typename T>
89
__global__ void KernelPool2DGrad(
90
    const int nthreads, const T* input_data, const T* output_data,
C
chengduoZH 已提交
91 92 93 94
    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,
95 96
    PoolProcess pool_process, bool exclusive, bool adaptive, T* input_grad,
    bool channel_last = false) {
97 98
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
99 100 101 102 103 104 105 106 107 108 109 110 111
    int w_offset, h_offset, offsetC, batch_idx;
    if (!channel_last) { /* NCHW */
      w_offset = index % input_width + padding_width;
      h_offset = (index / input_width) % input_height + padding_height;
      offsetC = (index / input_width / input_height) % channels;
      batch_idx = index / input_width / input_height / channels;
    } else { /* NHWC */
      offsetC = index % channels;
      w_offset = (index / channels) % input_width + padding_width;
      h_offset =
          (index / channels / input_width) % input_height + padding_height;
      batch_idx = index / channels / input_width / input_height;
    }
112

113 114 115
    int phstart, phend;
    int pwstart, pwend;
    if (adaptive) {
116 117 118 119 120
      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);
121
    } else {
D
dengkaipeng 已提交
122
      phstart = (h_offset < ksize_height)
123
                    ? 0
D
dengkaipeng 已提交
124 125
                    : (h_offset - ksize_height) / stride_height + 1;
      pwstart = (w_offset < ksize_width)
126
                    ? 0
D
dengkaipeng 已提交
127 128 129
                    : (w_offset - ksize_width) / stride_width + 1;
      phend = min(h_offset / stride_height + 1, output_height);
      pwend = min(w_offset / stride_width + 1, output_width);
130
    }
131
    T gradient = static_cast<T>(0.0);
132
    T input = input_data[index];
133 134 135 136 137 138 139 140 141 142 143 144

    int output_stride;
    if (!channel_last) {
      output_stride =
          (batch_idx * channels + offsetC) * output_height * output_width;
    } else {
      output_stride = batch_idx * output_height * output_width * channels;
    }

    output_data += output_stride;
    output_grad += output_stride;

145 146
    for (int ph = phstart; ph < phend; ++ph) {
      for (int pw = pwstart; pw < pwend; ++pw) {
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        int pool_size;
        if (adaptive) {
          pool_size = static_cast<int>(ceil(static_cast<double>(input_height) /
                                            ksize_height)) *
                      static_cast<int>(
                          ceil(static_cast<double>(input_width) / ksize_width));
        } else {
          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);
          pool_size = exclusive ? (hend - hstart) * (wend - wstart)
                                : ksize_height * ksize_width;
        }
163

164 165 166
        int output_sub_idx = channel_last
                                 ? (ph * output_width + pw) * channels + offsetC
                                 : ph * output_width + pw;
167
        pool_process.compute(input, output_data[output_sub_idx],
C
chengduo 已提交
168 169
                             output_grad[output_sub_idx],
                             static_cast<T>(1.0 / pool_size), &gradient);
170 171 172 173 174 175
      }
    }
    input_grad[index] = gradient;
  }
}

176
template <typename T>
177
__global__ void KernelMaxPool2DGrad(
178
    const int nthreads, const T* input_data, const T* output_data,
C
chengduoZH 已提交
179 180 181 182
    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,
183
    T* input_grad, bool channel_last = false) {
184 185
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
       index += blockDim.x * gridDim.x) {
186 187 188 189 190 191 192 193 194 195 196 197
    int pw, ph, c, batch_idx;
    if (!channel_last) { /* NCHW */
      pw = index % output_width;
      ph = (index / output_width) % output_height;
      c = (index / output_width / output_height) % channels;
      batch_idx = index / output_width / output_height / channels;
    } else { /* NHWC */
      c = index % channels;
      pw = (index / channels) % output_width;
      ph = (index / channels / output_width) % output_height;
      batch_idx = index / channels / output_width / output_height;
    }
198 199 200 201 202 203 204 205
    int hstart = ph * stride_height - padding_height;
    int hend = min(hstart + ksize_height, input_height);
    hstart = max(hstart, 0);

    int wstart = pw * stride_width - padding_width;
    int wend = min(wstart + ksize_width, input_width);
    wstart = max(wstart, 0);

206 207 208 209 210 211 212 213
    int input_stride;
    if (!channel_last) {
      input_stride = (batch_idx * channels + c) * input_height * input_width;
    } else {
      input_stride = batch_idx * input_height * input_width * channels;
    }
    input_data += input_stride;
    input_grad += input_stride;
214 215 216 217 218 219

    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) {
220 221 222 223
        int input_data_idx = channel_last ? (h * input_width + w) * channels + c
                                          : h * input_width + w;
        if (ele == input_data[input_data_idx]) {
          maxIndex = input_data_idx;
224 225 226 227 228 229 230
          stop = true;
        }
      }
    }

    if (maxIndex != -1) {
      // atomic add
C
chengduoZH 已提交
231
      platform::CudaAtomicAdd(input_grad + maxIndex, output_grad[index]);
232 233 234 235
    }
  }
}

N
nhzlx 已提交
236 237 238 239 240
template <typename PoolProcess, typename T>
void Pool2dDirectCUDAFunctor<PoolProcess, T>::operator()(
    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,
241 242
    bool exclusive, bool adaptive, T* output, gpuStream_t stream,
    PoolProcess pool_compute) {
N
nhzlx 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  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;
F
feng_shuai 已提交
258 259 260 261 262 263 264
  int thread_num = 1024;
#ifdef WITH_NV_JETSON
  // platform::ChangeThreadNum(context, &thread_num);
  thread_num = 512;
#endif
  int blocks = (nthreads + thread_num - 1) / thread_num;
  dim3 threads(thread_num, 1);
N
nhzlx 已提交
265 266 267 268 269
  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,
270
      padding_height, padding_width, pool_compute, exclusive, adaptive, output);
N
nhzlx 已提交
271 272
}

C
chengduoZH 已提交
273
/*
274 275 276 277 278 279
 * 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.
 */
280
template <typename PoolProcess, typename T>
Q
QI JUN 已提交
281
class Pool2dFunctor<platform::CUDADeviceContext, PoolProcess, T> {
282
 public:
Q
QI JUN 已提交
283
  void operator()(const platform::CUDADeviceContext& context,
C
chengduo 已提交
284 285
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
286 287 288
                  const std::vector<int>& paddings, bool exclusive,
                  bool adaptive, framework::Tensor* output,
                  PoolProcess pool_process) {
289 290 291 292
    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 已提交
293 294 295
    const int output_channels = output->dims()[1];
    const int output_height = output->dims()[2];
    const int output_width = output->dims()[3];
296 297 298 299 300 301 302 303
    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>();
C
chengduoZH 已提交
304
    T* output_data = output->mutable_data<T>(context.GetPlace());
305 306

    int nthreads = batch_size * output_channels * output_height * output_width;
F
feng_shuai 已提交
307 308 309 310 311 312
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
313
    dim3 grid(blocks, 1);
Q
QI JUN 已提交
314
    KernelPool2D<PoolProcess, T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
315 316
        nthreads, input_data, input_channels, input_height, input_width,
        output_height, output_width, ksize_height, ksize_width, stride_height,
317
        stride_width, padding_height, padding_width, pool_process, exclusive,
318
        adaptive, output_data);
319
  }
320 321 322 323
  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
324 325
                  const std::string data_format, bool exclusive, bool adaptive,
                  framework::Tensor* output, PoolProcess pool_process) {
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    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];
345

346 347 348 349 350 351 352
    const int padding_height = paddings[0];
    const int padding_width = paddings[1];

    const T* input_data = input.data<T>();
    T* output_data = output->mutable_data<T>(context.GetPlace());

    int nthreads = batch_size * output_channels * output_height * output_width;
F
feng_shuai 已提交
353 354 355 356 357 358
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
359 360 361 362 363 364 365 366
    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_process, exclusive,
        adaptive, output_data, channel_last);
  }
};
C
chengduoZH 已提交
367
/*
368 369 370 371 372 373
 * 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.
 */
374
template <typename PoolProcess, typename T>
Q
QI JUN 已提交
375
class Pool2dGradFunctor<platform::CUDADeviceContext, PoolProcess, T> {
376
 public:
Q
QI JUN 已提交
377
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
378
                  const framework::Tensor& input,
379
                  const framework::Tensor& output,
C
chengduo 已提交
380 381 382
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
383 384 385
                  const std::vector<int>& paddings, bool exclusive,
                  bool adaptive, framework::Tensor* input_grad,
                  PoolProcess pool_process) {
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    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>();
C
chengduoZH 已提交
402
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());
403 404 405 406 407 408

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

Q
QI JUN 已提交
409
    KernelPool2DGrad<PoolProcess, T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
410 411 412
        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,
413
        pool_process, exclusive, adaptive, input_grad_data);
414
  }
415 416 417 418 419 420 421 422 423
  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input,
                  const framework::Tensor& output,
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
                  const std::string data_format, bool exclusive, bool adaptive,
                  framework::Tensor* input_grad, PoolProcess pool_process) {
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    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>();

    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());

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

    KernelPool2DGrad<PoolProcess, 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,
        pool_process, exclusive, adaptive, input_grad_data, channel_last);
  }
464 465
};

C
chengduoZH 已提交
466
/*
467 468 469 470 471 472
 * 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.
 */
473
template <typename T>
Q
QI JUN 已提交
474
class MaxPool2dGradFunctor<platform::CUDADeviceContext, T> {
475
 public:
Q
QI JUN 已提交
476
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
477
                  const framework::Tensor& input,
478
                  const framework::Tensor& output,
C
chengduo 已提交
479 480 481 482
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
C
chengduoZH 已提交
483
                  framework::Tensor* input_grad) {
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    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>();
C
chengduoZH 已提交
501
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());
502 503 504 505 506 507

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

Q
QI JUN 已提交
508
    KernelMaxPool2DGrad<T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
509 510 511 512
        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);
513
  }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
  void operator()(
      const platform::CUDADeviceContext& context,
      const framework::Tensor& input, const framework::Tensor& output,
      const framework::Tensor& output_grad, const std::vector<int>& ksize,
      const std::vector<int>& strides, const std::vector<int>& paddings,
      const std::string data_format, framework::Tensor* input_grad) {
    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>();
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());

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

    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, channel_last);
  }
559 560
};

N
nhzlx 已提交
561 562 563 564 565
template class Pool2dDirectCUDAFunctor<paddle::operators::math::MaxPool<float>,
                                       float>;
template class Pool2dDirectCUDAFunctor<paddle::operators::math::AvgPool<float>,
                                       float>;

Q
QI JUN 已提交
566 567
template class MaxPool2dGradFunctor<platform::CUDADeviceContext, float>;
template class MaxPool2dGradFunctor<platform::CUDADeviceContext, double>;
568 569
template class MaxPool2dGradFunctor<platform::CUDADeviceContext,
                                    paddle::platform::float16>;
C
chengduoZH 已提交
570

Q
QI JUN 已提交
571
template class Pool2dFunctor<platform::CUDADeviceContext,
572
                             paddle::operators::math::MaxPool<float>, float>;
Q
QI JUN 已提交
573
template class Pool2dFunctor<platform::CUDADeviceContext,
574
                             paddle::operators::math::AvgPool<float>, float>;
Q
QI JUN 已提交
575 576 577 578 579 580 581
template class Pool2dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::MaxPoolGrad<float>,
                                 float>;
template class Pool2dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::AvgPoolGrad<float>,
                                 float>;
template class Pool2dFunctor<platform::CUDADeviceContext,
582
                             paddle::operators::math::MaxPool<double>, double>;
Q
QI JUN 已提交
583
template class Pool2dFunctor<platform::CUDADeviceContext,
584
                             paddle::operators::math::AvgPool<double>, double>;
Q
QI JUN 已提交
585 586 587 588 589 590
template class Pool2dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::MaxPoolGrad<double>,
                                 double>;
template class Pool2dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::AvgPoolGrad<double>,
                                 double>;
591

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
template class Pool2dFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::MaxPool<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool2dFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::AvgPool<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool2dGradFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::MaxPoolGrad<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool2dGradFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::AvgPoolGrad<paddle::platform::float16>,
    paddle::platform::float16>;

609
template <typename PoolProcess, typename T>
610
__global__ void KernelPool3D(
611 612 613
    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,
614
    const int ksize_depth, const int ksize_height, const int ksize_width,
615
    const int stride_depth, const int stride_height, const int stride_width,
616
    const int padding_depth, const int padding_height, const int padding_width,
617 618
    PoolProcess pool_process, bool exclusive, bool adaptive, T* output_data,
    bool channel_last = false) {
619
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
620
       index += blockDim.x * gridDim.x) {
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    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;
    }
637 638 639 640 641

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

D
dengkaipeng 已提交
645 646
      hstart = AdaptStartIndex(ph, input_height, output_height);
      hend = AdaptEndIndex(ph, input_height, output_height);
647

D
dengkaipeng 已提交
648 649
      wstart = AdaptStartIndex(pw, input_width, output_width);
      wend = AdaptEndIndex(pw, input_width, output_width);
650 651 652 653 654 655 656 657 658 659 660
    } 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);
    }
661 662 663 664 665 666 667 668 669 670 671

    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;

672
    T ele = pool_process.initial();
673 674 675
    for (int d = dstart; d < dend; ++d) {
      for (int h = hstart; h < hend; ++h) {
        for (int w = wstart; w < wend; ++w) {
676 677 678 679 680
          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);
681 682 683
        }
      }
    }
684
    int pool_size = (exclusive || adaptive)
685 686
                        ? (dend - dstart) * (hend - hstart) * (wend - wstart)
                        : ksize_depth * ksize_height * ksize_width;
C
chengduo 已提交
687
    pool_process.finalize(static_cast<T>(pool_size), &ele);
688 689 690 691 692
    output_data[index] = ele;
  }
}

template <typename PoolProcess, typename T>
693
__global__ void KernelPool3DGrad(
694
    const int nthreads, const T* input_data, const T* output_data,
C
chengduoZH 已提交
695 696 697 698 699 700
    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, PoolProcess pool_process,
701
    bool exclusive, bool adaptive, T* input_grad, bool channel_last = false) {
702
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
703
       index += blockDim.x * gridDim.x) {
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    int w_offset, h_offset, d_offset, offsetC, batch_idx;
    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;
      offsetC = (index / input_width / input_height / input_depth) % channels;
      batch_idx = index / input_width / input_height / input_depth / channels;

    } else { /* "NDHWC" */
      offsetC = index % channels;
      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;
    }
722

723 724 725 726
    int pdstart, pdend;
    int phstart, phend;
    int pwstart, pwend;
    if (adaptive) {
727 728 729 730 731 732 733 734
      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);
735
    } else {
D
dengkaipeng 已提交
736
      pdstart = (d_offset < ksize_depth)
737
                    ? 0
D
dengkaipeng 已提交
738 739
                    : (d_offset - ksize_depth) / stride_depth + 1;
      phstart = (h_offset < ksize_height)
740
                    ? 0
D
dengkaipeng 已提交
741 742
                    : (h_offset - ksize_height) / stride_height + 1;
      pwstart = (w_offset < ksize_width)
743
                    ? 0
D
dengkaipeng 已提交
744 745 746 747
                    : (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);
748
    }
749

750
    T gradient = static_cast<T>(0.0);
751
    T input = input_data[index];
752 753 754 755 756 757 758 759 760 761 762

    int output_stride;
    if (!channel_last) {
      output_stride = (batch_idx * channels + offsetC) * output_depth *
                      output_height * output_width;
    } else {
      output_stride =
          batch_idx * output_depth * output_height * output_width * channels;
    }
    output_data += output_stride;
    output_grad += output_stride;
763 764 765 766 767

    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
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
          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;
          }
791 792 793 794 795 796 797

          int output_sub_idx =
              channel_last
                  ? ((pd * output_height + ph) * output_width + pw) * channels +
                        offsetC
                  : (pd * output_height + ph) * output_width + pw;

798
          pool_process.compute(input, output_data[output_sub_idx],
C
chengduo 已提交
799 800
                               output_grad[output_sub_idx],
                               static_cast<T>(1.0 / pool_size), &gradient);
801 802 803 804 805 806 807
        }
      }
    }
    input_grad[index] = gradient;
  }
}

808
template <typename T>
809
__global__ void KernelMaxPool3DGrad(
810
    const int nthreads, const T* input_data, const T* output_data,
C
chengduoZH 已提交
811 812 813 814 815
    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,
816 817
    const int padding_height, const int padding_width, T* input_grad,
    bool channel_last = false) {
818
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
819
       index += blockDim.x * gridDim.x) {
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    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;
    }

838 839 840
    int dstart = pd * stride_depth - padding_depth;
    int hstart = ph * stride_height - padding_height;
    int wstart = pw * stride_width - padding_width;
841

842 843 844
    int dend = min(dstart + ksize_depth, input_depth);
    int hend = min(hstart + ksize_height, input_height);
    int wend = min(wstart + ksize_width, input_width);
845

846 847 848
    dstart = max(dstart, 0);
    hstart = max(hstart, 0);
    wstart = max(wstart, 0);
849

850 851 852 853
    T ele = output_data[index];
    bool stop = false;
    int maxIdx = -1;

854 855 856 857 858 859 860 861 862 863
    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;
864 865 866
    for (int d = dstart; d < dend && !stop; ++d) {
      for (int h = hstart; h < hend && !stop; ++h) {
        for (int w = wstart; w < wend && !stop; ++w) {
867 868 869 870 871
          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]) {
872
            stop = true;
873
            maxIdx = input_data_idx;
874 875 876 877 878 879
          }
        }
      }
    }
    if (maxIdx != -1) {
      // atomic add
C
chengduoZH 已提交
880
      platform::CudaAtomicAdd(input_grad + maxIdx, output_grad[index]);
881 882 883 884
    }
  }
}

C
chengduoZH 已提交
885
/*
886 887 888 889 890 891 892
 * 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.
 */
893
template <typename PoolProcess, class T>
Q
QI JUN 已提交
894
class Pool3dFunctor<platform::CUDADeviceContext, PoolProcess, T> {
895
 public:
Q
QI JUN 已提交
896
  void operator()(const platform::CUDADeviceContext& context,
C
chengduo 已提交
897 898
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
899 900 901
                  const std::vector<int>& paddings, bool exclusive,
                  bool adaptive, framework::Tensor* output,
                  PoolProcess pool_process) {
902 903 904 905 906
    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 已提交
907 908 909 910
    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];
911 912 913 914 915 916 917 918 919 920 921
    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>();
C
chengduoZH 已提交
922
    T* output_data = output->mutable_data<T>(context.GetPlace());
923 924 925

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
F
feng_shuai 已提交
926 927 928 929 930 931
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
932 933
    dim3 grid(blocks, 1);

Q
QI JUN 已提交
934
    KernelPool3D<PoolProcess, T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
935 936 937
        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,
938
        padding_depth, padding_height, padding_width, pool_process, exclusive,
939
        adaptive, output_data);
940
  }
941 942 943 944
  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
945 946
                  const std::string data_format, bool exclusive, bool adaptive,
                  framework::Tensor* output, PoolProcess pool_process) {
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    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>();
    T* output_data = output->mutable_data<T>(context.GetPlace());

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
F
feng_shuai 已提交
981 982 983 984 985 986
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
987 988 989 990 991 992 993 994 995
    dim3 grid(blocks, 1);

    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);
  }
996 997
};

C
chengduoZH 已提交
998
/*
999 1000 1001 1002 1003 1004 1005
 * 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.
 */
1006
template <typename PoolProcess, class T>
Q
QI JUN 已提交
1007
class Pool3dGradFunctor<platform::CUDADeviceContext, PoolProcess, T> {
1008
 public:
Q
QI JUN 已提交
1009
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
1010
                  const framework::Tensor& input,
1011
                  const framework::Tensor& output,
C
chengduo 已提交
1012 1013 1014
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
1015 1016 1017
                  const std::vector<int>& paddings, bool exclusive,
                  bool adaptive, framework::Tensor* input_grad,
                  PoolProcess pool_process) {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    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>();
C
chengduoZH 已提交
1040
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());
1041

1042 1043
    int nthreads =
        batch_size * input_channels * input_depth * input_height * input_width;
1044 1045 1046 1047
    int blocks = (nthreads + 1024 - 1) / 1024;
    dim3 threads(1024, 1);
    dim3 grid(blocks, 1);

Q
QI JUN 已提交
1048
    KernelPool3DGrad<PoolProcess, T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1049 1050 1051 1052
        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,
1053
        padding_width, pool_process, exclusive, adaptive, input_grad_data);
1054
  }
1055 1056 1057 1058 1059 1060 1061 1062 1063
  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input,
                  const framework::Tensor& output,
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
                  const std::string data_format, bool exclusive, bool adaptive,
                  framework::Tensor* input_grad, PoolProcess pool_process) {
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    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>();
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());

    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);

    KernelPool3DGrad<PoolProcess, 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, pool_process, exclusive, adaptive, input_grad_data,
        channel_last);  // add channel_last
  }
1110 1111
};

C
chengduoZH 已提交
1112
/*
1113 1114 1115 1116 1117 1118 1119
 * 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.
 */
1120
template <class T>
Q
QI JUN 已提交
1121
class MaxPool3dGradFunctor<platform::CUDADeviceContext, T> {
1122
 public:
Q
QI JUN 已提交
1123
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
1124
                  const framework::Tensor& input,
1125
                  const framework::Tensor& output,
C
chengduo 已提交
1126 1127 1128 1129
                  const framework::Tensor& output_grad,
                  const std::vector<int>& ksize,
                  const std::vector<int>& strides,
                  const std::vector<int>& paddings,
C
chengduoZH 已提交
1130
                  framework::Tensor* input_grad) {
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    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>();
C
chengduoZH 已提交
1153
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());
1154 1155 1156 1157 1158 1159 1160

    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);

Q
QI JUN 已提交
1161
    KernelMaxPool3DGrad<T><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1162 1163 1164 1165 1166
        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);
1167
  }
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  void operator()(
      const platform::CUDADeviceContext& context,
      const framework::Tensor& input, const framework::Tensor& output,
      const framework::Tensor& output_grad, const std::vector<int>& ksize,
      const std::vector<int>& strides, const std::vector<int>& paddings,
      const std::string data_format, framework::Tensor* input_grad) {
    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>();
    T* input_grad_data = input_grad->mutable_data<T>(context.GetPlace());

    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()>>>(
        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
  }
1219 1220
};

Q
QI JUN 已提交
1221 1222
template class MaxPool3dGradFunctor<platform::CUDADeviceContext, float>;
template class MaxPool3dGradFunctor<platform::CUDADeviceContext, double>;
1223 1224
template class MaxPool3dGradFunctor<platform::CUDADeviceContext,
                                    paddle::platform::float16>;
C
chengduoZH 已提交
1225

Q
QI JUN 已提交
1226
template class Pool3dFunctor<platform::CUDADeviceContext,
1227
                             paddle::operators::math::MaxPool<float>, float>;
Q
QI JUN 已提交
1228
template class Pool3dFunctor<platform::CUDADeviceContext,
1229
                             paddle::operators::math::AvgPool<float>, float>;
Q
QI JUN 已提交
1230 1231 1232 1233 1234 1235 1236
template class Pool3dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::MaxPoolGrad<float>,
                                 float>;
template class Pool3dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::AvgPoolGrad<float>,
                                 float>;
template class Pool3dFunctor<platform::CUDADeviceContext,
1237
                             paddle::operators::math::MaxPool<double>, double>;
Q
QI JUN 已提交
1238
template class Pool3dFunctor<platform::CUDADeviceContext,
1239
                             paddle::operators::math::AvgPool<double>, double>;
Q
QI JUN 已提交
1240 1241 1242 1243 1244 1245
template class Pool3dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::MaxPoolGrad<double>,
                                 double>;
template class Pool3dGradFunctor<platform::CUDADeviceContext,
                                 paddle::operators::math::AvgPoolGrad<double>,
                                 double>;
1246

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
template class Pool3dFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::MaxPool<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool3dFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::AvgPool<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool3dGradFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::MaxPoolGrad<paddle::platform::float16>,
    paddle::platform::float16>;
template class Pool3dGradFunctor<
    platform::CUDADeviceContext,
    paddle::operators::math::AvgPoolGrad<paddle::platform::float16>,
    paddle::platform::float16>;

C
chengduoZH 已提交
1264
template <typename T1, typename T2>
C
chengduoZH 已提交
1265
__global__ void KernelMaxPool2dWithIdx(
C
chengduoZH 已提交
1266
    const int nthreads, const T1* input_data, const int channels,
C
chengduoZH 已提交
1267 1268 1269
    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,
1270
    const int padding_width, bool adaptive, T1* output_data, T2* mask_data) {
C
chengduoZH 已提交
1271
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
1272
       index += blockDim.x * gridDim.x) {
C
chengduoZH 已提交
1273 1274 1275 1276 1277
    int pw = index % output_width;
    int ph = (index / output_width) % output_height;
    int c = (index / output_width / output_height) % channels;
    int batch_idx = index / output_width / output_height / channels;

1278 1279 1280
    int hstart, hend;
    int wstart, wend;
    if (adaptive) {
D
dengkaipeng 已提交
1281 1282
      hstart = AdaptStartIndex(ph, input_height, output_height);
      hend = AdaptEndIndex(ph, input_height, output_height);
C
chengduoZH 已提交
1283

D
dengkaipeng 已提交
1284 1285
      wstart = AdaptStartIndex(pw, input_width, output_width);
      wend = AdaptEndIndex(pw, input_width, output_width);
1286 1287 1288 1289 1290 1291 1292 1293 1294
    } else {
      hstart = ph * stride_height - padding_height;
      hend = min(hstart + ksize_height, input_height);
      hstart = max(hstart, 0);

      wstart = pw * stride_width - padding_width;
      wend = min(wstart + ksize_width, input_width);
      wstart = max(wstart, 0);
    }
C
chengduoZH 已提交
1295 1296

    input_data += (batch_idx * channels + c) * input_height * input_width;
C
chengduoZH 已提交
1297
    T1 ele = -FLT_MAX;
C
chengduoZH 已提交
1298
    int max_index = -1;
C
chengduoZH 已提交
1299 1300
    for (int h = hstart; h < hend; ++h) {
      for (int w = wstart; w < wend; ++w) {
C
chengduoZH 已提交
1301 1302 1303 1304
        int input_index = h * input_width + w;
        if (ele < input_data[input_index]) {
          max_index = input_index;
          ele = input_data[input_index];
C
chengduoZH 已提交
1305 1306 1307 1308
        }
      }
    }
    output_data[index] = ele;
C
chengduoZH 已提交
1309
    mask_data[index] = max_index;
C
chengduoZH 已提交
1310 1311 1312
  }
}

C
chengduoZH 已提交
1313
template <typename T1, typename T2>
C
chengduoZH 已提交
1314
__global__ void KernelMaxPool2DWithIdxGrad(
C
chengduoZH 已提交
1315
    const int nthreads, const T1* output_grad, const T2* mask_data,
C
chengduoZH 已提交
1316 1317 1318
    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,
1319 1320
    const int padding_height, const int padding_width, bool adaptive,
    T1* input_grad) {
C
chengduoZH 已提交
1321
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
1322
       index += blockDim.x * gridDim.x) {
D
dengkaipeng 已提交
1323 1324
    int w_offset = index % input_width;
    int h_offset = (index / input_width) % input_height;
1325
    int offsetC = (index / input_width / input_height) % channels;
C
chengduoZH 已提交
1326 1327
    int batch_idx = index / input_width / input_height / channels;

1328 1329 1330
    int phstart, phend;
    int pwstart, pwend;
    if (adaptive) {
D
dengkaipeng 已提交
1331
      phstart = h_offset * output_height / input_height;
1332
      phend =
D
dengkaipeng 已提交
1333 1334 1335 1336
          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);
1337 1338
    } else {
      phstart =
D
dengkaipeng 已提交
1339
          (h_offset + padding_height < ksize_height)
1340
              ? 0
D
dengkaipeng 已提交
1341
              : (h_offset + padding_height - ksize_height) / stride_height + 1;
1342
      pwstart =
D
dengkaipeng 已提交
1343
          (w_offset + padding_width < ksize_width)
1344
              ? 0
D
dengkaipeng 已提交
1345
              : (w_offset + padding_width - ksize_width) / stride_width + 1;
1346
      phend =
D
dengkaipeng 已提交
1347 1348
          min((h_offset + padding_height) / stride_height + 1, output_height);
      pwend = min((w_offset + padding_width) / stride_width + 1, output_width);
1349
    }
C
chengduoZH 已提交
1350

C
chengduoZH 已提交
1351
    T1 gradient = 0;
D
dengkaipeng 已提交
1352
    int input_current_featuremap_idx = h_offset * input_width + w_offset;
C
chengduoZH 已提交
1353
    int output_idx =
1354
        (batch_idx * channels + offsetC) * output_height * output_width;
C
chengduoZH 已提交
1355

C
chengduoZH 已提交
1356 1357
    mask_data += output_idx;
    output_grad += output_idx;
1358 1359
    for (int ph = phstart; ph < phend; ++ph) {
      for (int pw = pwstart; pw < pwend; ++pw) {
C
chengduoZH 已提交
1360
        if (mask_data[ph * output_width + pw] == input_current_featuremap_idx)
C
chengduoZH 已提交
1361 1362 1363 1364 1365 1366 1367
          gradient += output_grad[ph * output_width + pw];
      }
    }
    input_grad[index] = gradient;
  }
}

C
chengduoZH 已提交
1368 1369 1370 1371 1372
/*
 * All tensors are in NCHW format.
 * Ksize, strides, paddings are two elements. These two elements represent
 * height and width, respectively.
 */
C
chengduoZH 已提交
1373
template <typename T1, typename T2>
Q
QI JUN 已提交
1374
class MaxPool2dWithIndexFunctor<platform::CUDADeviceContext, T1, T2> {
C
chengduoZH 已提交
1375
 public:
Q
QI JUN 已提交
1376
  void operator()(const platform::CUDADeviceContext& context,
C
chengduo 已提交
1377 1378
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
1379 1380
                  const std::vector<int>& paddings, bool adaptive,
                  framework::Tensor* output, framework::Tensor* mask) {
C
chengduoZH 已提交
1381 1382 1383 1384
    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 已提交
1385 1386 1387
    const int output_channels = output->dims()[1];
    const int output_height = output->dims()[2];
    const int output_width = output->dims()[3];
C
chengduoZH 已提交
1388 1389 1390 1391 1392 1393 1394
    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 已提交
1395 1396 1397
    const T1* input_data = input.data<T1>();
    T1* output_data = output->mutable_data<T1>(context.GetPlace());
    T2* mask_data = mask->mutable_data<T2>(context.GetPlace());
C
chengduoZH 已提交
1398 1399

    int nthreads = batch_size * output_channels * output_height * output_width;
F
feng_shuai 已提交
1400 1401 1402 1403
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif
C
chengduoZH 已提交
1404

F
feng_shuai 已提交
1405 1406 1407
    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
    dim3 grid(blocks, 1);
Q
QI JUN 已提交
1408
    KernelMaxPool2dWithIdx<T1, T2><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1409 1410
        nthreads, input_data, input_channels, input_height, input_width,
        output_height, output_width, ksize_height, ksize_width, stride_height,
1411 1412
        stride_width, padding_height, padding_width, adaptive, output_data,
        mask_data);
C
chengduoZH 已提交
1413 1414 1415
  }
};

C
chengduoZH 已提交
1416 1417 1418 1419 1420
/*
 * All tensors are in NCHW format.
 * Ksize, strides, paddings are two elements. These two elements represent
 * height and width, respectively.
 */
C
chengduoZH 已提交
1421
template <typename T1, typename T2>
Q
QI JUN 已提交
1422
class MaxPool2dWithIndexGradFunctor<platform::CUDADeviceContext, T1, T2> {
C
chengduoZH 已提交
1423
 public:
Q
QI JUN 已提交
1424
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
1425
                  const framework::Tensor& output_grad,
C
chengduo 已提交
1426 1427
                  const framework::Tensor& mask, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
1428
                  const std::vector<int>& paddings, bool adaptive,
C
chengduoZH 已提交
1429 1430 1431 1432 1433
                  framework::Tensor* input_grad) {
    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 已提交
1434 1435 1436 1437 1438 1439 1440 1441 1442
    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 已提交
1443 1444 1445
    const T2* mask_data = mask.data<T2>();
    const T1* output_grad_data = output_grad.data<T1>();
    T1* input_grad_data = input_grad->mutable_data<T1>(context.GetPlace());
C
chengduoZH 已提交
1446 1447 1448 1449 1450 1451

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

Q
QI JUN 已提交
1452
    KernelMaxPool2DWithIdxGrad<T1, T2><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1453 1454
        nthreads, output_grad_data, mask_data, input_channels, input_height,
        input_width, output_height, output_width, ksize_height, ksize_width,
1455
        stride_height, stride_width, padding_height, padding_width, adaptive,
C
chengduoZH 已提交
1456
        input_grad_data);
C
chengduoZH 已提交
1457 1458 1459
  }
};

Q
QI JUN 已提交
1460 1461 1462 1463 1464 1465 1466 1467
template class MaxPool2dWithIndexFunctor<platform::CUDADeviceContext, float,
                                         int>;
template class MaxPool2dWithIndexGradFunctor<platform::CUDADeviceContext, float,
                                             int>;
template class MaxPool2dWithIndexFunctor<platform::CUDADeviceContext, double,
                                         int>;
template class MaxPool2dWithIndexGradFunctor<platform::CUDADeviceContext,
                                             double, int>;
C
chengduoZH 已提交
1468

C
chengduoZH 已提交
1469
template <typename T1, typename T2>
C
chengduoZH 已提交
1470
__global__ void KernelMaxPool3DWithIdx(
C
chengduoZH 已提交
1471
    const int nthreads, const T1* input_data, const int channels,
C
chengduoZH 已提交
1472 1473 1474 1475 1476
    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,
1477
    bool adaptive, T1* output_data, T2* mask_data) {
C
chengduoZH 已提交
1478
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
1479 1480 1481 1482 1483 1484 1485
       index += blockDim.x * gridDim.x) {
    int pw = index % output_width;
    int ph = (index / output_width) % output_height;
    int pd = (index / output_width / output_height) % output_depth;
    int c = (index / output_width / output_height / output_depth) % channels;
    int batch_idx =
        index / output_width / output_height / output_depth / channels;
C
chengduoZH 已提交
1486

1487 1488 1489 1490
    int dstart, dend;
    int hstart, hend;
    int wstart, wend;
    if (adaptive) {
D
dengkaipeng 已提交
1491 1492
      dstart = AdaptStartIndex(pd, input_depth, output_depth);
      dend = AdaptEndIndex(pd, input_depth, output_depth);
1493

D
dengkaipeng 已提交
1494 1495
      hstart = AdaptStartIndex(ph, input_height, output_height);
      hend = AdaptEndIndex(ph, input_height, output_height);
1496

D
dengkaipeng 已提交
1497 1498
      wstart = AdaptStartIndex(pw, input_width, output_width);
      wend = AdaptEndIndex(pw, input_width, output_width);
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    } 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);
    }
C
chengduoZH 已提交
1510

C
chengduoZH 已提交
1511
    T1 ele = -FLT_MAX;
C
chengduoZH 已提交
1512
    int max_index = -1;
C
chengduoZH 已提交
1513 1514 1515 1516 1517 1518 1519
    input_data +=
        (batch_idx * channels + c) * input_depth * input_height * input_width;

    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[(d * input_height + h) * input_width + w]) {
C
chengduoZH 已提交
1520 1521
            max_index = (d * input_height + h) * input_width + w;
            ele = input_data[max_index];
C
chengduoZH 已提交
1522 1523 1524 1525 1526
          }
        }
      }
    }
    output_data[index] = ele;
C
chengduoZH 已提交
1527
    mask_data[index] = max_index;
C
chengduoZH 已提交
1528 1529 1530
  }
}

C
chengduoZH 已提交
1531
template <typename T1, typename T2>
C
chengduoZH 已提交
1532
__global__ void KernelMaxPool3DWithIdxGrad(
C
chengduoZH 已提交
1533 1534 1535 1536 1537 1538
    const int nthreads, 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,
1539
    const int padding_width, bool adaptive, T1* input_grad) {
C
chengduoZH 已提交
1540
  for (int index = blockIdx.x * blockDim.x + threadIdx.x; index < nthreads;
C
chengduoZH 已提交
1541
       index += blockDim.x * gridDim.x) {
D
dengkaipeng 已提交
1542 1543 1544
    int w_offset = index % input_width;
    int h_offset = (index / input_width) % input_height;
    int d_offset = (index / input_width / input_height) % input_depth;
1545
    int offsetC = (index / input_width / input_height / input_depth) % channels;
C
chengduoZH 已提交
1546 1547
    int batch_idx = index / input_width / input_height / input_depth / channels;

1548 1549 1550 1551
    int pdstart, pdend;
    int phstart, phend;
    int pwstart, pwend;
    if (adaptive) {
D
dengkaipeng 已提交
1552 1553 1554 1555
      pdstart = d_offset * output_depth / input_depth;
      pdend =
          min((d_offset + 1) * output_depth / input_depth + 1, output_depth);
      phstart = h_offset * output_height / input_height;
1556
      phend =
D
dengkaipeng 已提交
1557 1558 1559 1560
          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);
1561 1562
    } else {
      pdstart =
D
dengkaipeng 已提交
1563
          (d_offset + padding_depth < ksize_depth)
1564
              ? 0
D
dengkaipeng 已提交
1565
              : (d_offset + padding_depth - ksize_depth) / stride_depth + 1;
1566
      phstart =
D
dengkaipeng 已提交
1567
          (h_offset + padding_height < ksize_height)
1568
              ? 0
D
dengkaipeng 已提交
1569
              : (h_offset + padding_height - ksize_height) / stride_height + 1;
1570
      pwstart =
D
dengkaipeng 已提交
1571
          (w_offset + padding_width < ksize_width)
1572
              ? 0
D
dengkaipeng 已提交
1573 1574
              : (w_offset + padding_width - ksize_width) / stride_width + 1;
      pdend = min((d_offset + padding_depth) / stride_depth + 1, output_depth);
1575
      phend =
D
dengkaipeng 已提交
1576 1577
          min((h_offset + padding_height) / stride_height + 1, output_height);
      pwend = min((w_offset + padding_width) / stride_width + 1, output_width);
1578
    }
C
chengduoZH 已提交
1579

C
chengduoZH 已提交
1580
    T1 gradient = 0;
C
chengduoZH 已提交
1581
    int input_current_feature_map_idx =
D
dengkaipeng 已提交
1582
        (d_offset * input_height + h_offset) * input_width + w_offset;
1583
    int output_idx = (batch_idx * channels + offsetC) * output_depth *
C
chengduoZH 已提交
1584 1585 1586 1587
                     output_height * output_width;
    mask += output_idx;
    output_grad += output_idx;

1588 1589 1590
    for (int pd = pdstart; pd < pdend; ++pd) {
      for (int ph = phstart; ph < phend; ++ph) {
        for (int pw = pwstart; pw < pwend; ++pw) {
C
chengduoZH 已提交
1591 1592
          if (mask[(pd * output_height + ph) * output_width + pw] ==
              input_current_feature_map_idx)
C
chengduoZH 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601
            gradient +=
                output_grad[(pd * output_height + ph) * output_width + pw];
        }
      }
    }
    input_grad[index] = gradient;
  }
}

C
chengduoZH 已提交
1602 1603 1604 1605 1606
/*
 * All tensors are in NCDHW format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 */
C
chengduoZH 已提交
1607
template <typename T1, typename T2>
Q
QI JUN 已提交
1608
class MaxPool3dWithIndexFunctor<platform::CUDADeviceContext, T1, T2> {
C
chengduoZH 已提交
1609
 public:
Q
QI JUN 已提交
1610
  void operator()(const platform::CUDADeviceContext& context,
C
chengduo 已提交
1611 1612
                  const framework::Tensor& input, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
1613 1614
                  const std::vector<int>& paddings, bool adaptive,
                  framework::Tensor* output, framework::Tensor* mask) {
C
chengduoZH 已提交
1615 1616 1617 1618 1619
    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 已提交
1620 1621 1622 1623
    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 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
    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 已提交
1634 1635 1636
    const T1* input_data = input.data<T1>();
    T1* output_data = output->mutable_data<T1>(context.GetPlace());
    T2* mask_data = mask->mutable_data<T2>(context.GetPlace());
C
chengduoZH 已提交
1637 1638 1639

    int nthreads = batch_size * output_channels * output_depth * output_height *
                   output_width;
F
feng_shuai 已提交
1640 1641 1642 1643 1644 1645 1646
    int thread_num = 1024;
#ifdef WITH_NV_JETSON
    platform::ChangeThreadNum(context, &thread_num);
#endif

    int blocks = (nthreads + thread_num - 1) / thread_num;
    dim3 threads(thread_num, 1);
C
chengduoZH 已提交
1647 1648
    dim3 grid(blocks, 1);

Q
QI JUN 已提交
1649
    KernelMaxPool3DWithIdx<T1, T2><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1650 1651 1652
        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,
1653 1654
        padding_depth, padding_height, padding_width, adaptive, output_data,
        mask_data);
C
chengduoZH 已提交
1655 1656 1657
  }
};

C
chengduoZH 已提交
1658 1659 1660 1661 1662
/*
 * All tensors are in NCDHW format.
 * Ksize, strides, paddings are three elements. These three elements represent
 * depth, height and width, respectively.
 */
C
chengduoZH 已提交
1663
template <typename T1, typename T2>
Q
QI JUN 已提交
1664
class MaxPool3dWithIndexGradFunctor<platform::CUDADeviceContext, T1, T2> {
C
chengduoZH 已提交
1665
 public:
Q
QI JUN 已提交
1666
  void operator()(const platform::CUDADeviceContext& context,
C
chengduoZH 已提交
1667
                  const framework::Tensor& output_grad,
C
chengduo 已提交
1668 1669
                  const framework::Tensor& mask, const std::vector<int>& ksize,
                  const std::vector<int>& strides,
1670
                  const std::vector<int>& paddings, bool adaptive,
C
chengduoZH 已提交
1671 1672 1673 1674 1675 1676
                  framework::Tensor* input_grad) {
    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 已提交
1677 1678 1679
    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 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
    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 已提交
1690 1691 1692
    const T1* output_grad_data = output_grad.data<T1>();
    const T2* mask_data = mask.data<T2>();
    T1* input_grad_data = input_grad->mutable_data<T1>(context.GetPlace());
C
chengduoZH 已提交
1693 1694 1695 1696 1697 1698 1699

    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);

Q
QI JUN 已提交
1700
    KernelMaxPool3DWithIdxGrad<T1, T2><<<grid, threads, 0, context.stream()>>>(
C
chengduoZH 已提交
1701 1702 1703
        nthreads, 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,
1704
        stride_width, padding_depth, padding_height, padding_width, adaptive,
C
chengduoZH 已提交
1705
        input_grad_data);
C
chengduoZH 已提交
1706 1707 1708
  }
};

Q
QI JUN 已提交
1709 1710 1711 1712 1713 1714 1715 1716
template class MaxPool3dWithIndexFunctor<platform::CUDADeviceContext, float,
                                         int>;
template class MaxPool3dWithIndexGradFunctor<platform::CUDADeviceContext, float,
                                             int>;
template class MaxPool3dWithIndexFunctor<platform::CUDADeviceContext, double,
                                         int>;
template class MaxPool3dWithIndexGradFunctor<platform::CUDADeviceContext,
                                             double, int>;
C
chengduoZH 已提交
1717 1718 1719 1720

}  // namespace math
}  // namespace operators
}  // namespace paddle