pool_op.h 13.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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

#pragma once

17
#include <algorithm>
18 19
#include <string>
#include <vector>
20

Y
Yi Wang 已提交
21 22 23 24
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/pooling.h"
25 26 27 28
#ifdef __NVCC__
#include "paddle/fluid/operators/reduce_ops/cub_reduce.h"
#endif

29 30
namespace paddle {
namespace operators {
31 32 33 34 35 36 37 38
template <typename T>
struct DivideFunctor {
  HOSTDEVICE explicit inline DivideFunctor(int n) : n_inv((T)(1.0 / n)) {}
  HOSTDEVICE inline T operator()(const T& x) const { return x * n_inv; }

 private:
  T n_inv;
};
39 40

using Tensor = framework::Tensor;
41 42 43 44 45 46

class PoolOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override;
47 48 49 50

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override;
51 52 53

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
54
      const framework::OpKernelType& expected_kernel_type) const override;
55 56 57 58 59 60 61
};

class PoolOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override;
62 63 64 65

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override;
66 67 68 69

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const override;
70 71 72 73
};

class Pool2dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
74
  void Make() override;
75 76 77 78
};

class Pool3dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
79
  void Make() override;
80
};
81 82 83

template <typename T = int>
inline void UpdatePadding(std::vector<T>* paddings, const bool global_pooling,
84 85 86
                          const bool adaptive,
                          const std::string padding_algorithm,
                          const framework::DDim data_dims,
87 88
                          const std::vector<T>& strides,
                          const std::vector<T>& ksize) {
89
  // set padding size == data_dims.size() * 2
90
  auto data_shape = framework::vectorize<T>(data_dims);
91 92
  if (static_cast<int>(paddings->size()) == data_dims.size()) {
    for (int i = 0; i < data_dims.size(); ++i) {
93
      T copy_pad = *(paddings->begin() + 2 * i);
94 95 96
      paddings->insert(paddings->begin() + 2 * i + 1, copy_pad);
    }
  } else {
97 98 99 100 101
    PADDLE_ENFORCE_EQ(data_dims.size() * 2, paddings->size(),
                      platform::errors::InvalidArgument(
                          "Paddings size %d should be the same or twice as the "
                          "pooling size %d.",
                          paddings->size(), data_dims.size() * 2));
102 103
  }

104
  // when padding_algorithm is "VALID" or "SAME"
105
  if (padding_algorithm == "SAME") {
106
    for (int i = 0; i < data_dims.size(); ++i) {
107 108
      T out_size = (data_dims[i] + strides[i] - 1) / strides[i];
      T pad_sum =
109 110
          std::max((out_size - 1) * strides[i] + ksize[i] - data_shape[i],
                   static_cast<T>(0));
111 112
      T pad_0 = pad_sum / 2;
      T pad_1 = pad_sum - pad_0;
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      *(paddings->begin() + i * 2) = pad_0;
      *(paddings->begin() + i * 2 + 1) = pad_1;
    }
  } else if (padding_algorithm == "VALID") {
    for (auto it = paddings->begin(); it != paddings->end(); it++) {
      *it = 0;
    }
  }

  // if global_pooling == true or adaptive == true, padding will be ignore
  if (global_pooling || adaptive) {
    for (auto it = paddings->begin(); it != paddings->end(); it++) {
      *it = 0;
    }
  }
}

130 131
template <typename T = int>
inline void UpdateKsize(std::vector<T>* ksize,
132 133 134
                        const framework::DDim data_dims) {
  ksize->resize(static_cast<size_t>(data_dims.size()));
  for (size_t i = 0; i < ksize->size(); ++i) {
135
    *(ksize->begin() + i) = static_cast<T>(data_dims[i]);
136 137
  }
}
138

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
inline int getReduceNum(const framework::Tensor& input,
                        const framework::Tensor* output,
                        const std::string data_format,
                        std::vector<int>* reduce_dim) {
  // data_format only can be NCHW
  bool channel_last = (data_format == "NHWC");
  if (channel_last) {
    return 0;
  }
  int reduce_num = 0;
  const int output_height = output->dims()[2];
  const int output_width = output->dims()[3];
  if ((output_height == 1) && (output_width == 1)) {
    reduce_dim->push_back(2);
    reduce_dim->push_back(3);
    reduce_num = input.dims()[2] * input.dims()[3];
  }
  return reduce_num;
}

Q
QI JUN 已提交
159
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
160
class PoolKernel : public framework::OpKernel<T> {
161 162
 public:
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduoZH 已提交
163
    const Tensor* in_x = context.Input<Tensor>("X");
164
    Tensor* out = context.Output<Tensor>("Out");
165

C
chengduoZH 已提交
166
    std::string pooling_type = context.Attr<std::string>("pooling_type");
167 168 169
    std::vector<int> ksize = context.Attr<std::vector<int>>("ksize");
    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
170
    std::string data_format = context.Attr<std::string>("data_format");
171
    bool exclusive = context.Attr<bool>("exclusive");
172
    bool adaptive = context.Attr<bool>("adaptive");
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    bool global_pooling = context.Attr<bool>("global_pooling");
    std::string padding_algorithm =
        context.Attr<std::string>("padding_algorithm");

    const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");

    // update paddings
    auto in_x_dims = in_x->dims();
    framework::DDim data_dims;
    if (channel_last) {
      data_dims = framework::slice_ddim(in_x_dims, 1, in_x_dims.size() - 1);
    } else {
      data_dims = framework::slice_ddim(in_x_dims, 2, in_x_dims.size());
    }

    UpdatePadding(&paddings, global_pooling, adaptive, padding_algorithm,
                  data_dims, strides, ksize);
190 191
    if (data_dims.size() * 2 == static_cast<int>(paddings.size())) {
      for (int i = 0; i < data_dims.size(); ++i) {
192
        paddings.erase(paddings.begin() + i + 1);
193 194
      }
    }
195 196 197 198

    if (global_pooling) {
      UpdateKsize(&ksize, data_dims);
    }
Q
QI JUN 已提交
199
    auto& dev_ctx = context.template device_context<DeviceContext>();
200 201 202
    switch (ksize.size()) {
      case 2: {
        if (pooling_type == "max") {
C
chengduoZH 已提交
203
          paddle::operators::math::Pool2dFunctor<
Q
QI JUN 已提交
204
              DeviceContext, paddle::operators::math::MaxPool<T>, T>
205
              pool2d_forward;
206
          paddle::operators::math::MaxPool<T> pool_process;
207
          pool2d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
208
                         true, false, out, pool_process);
209

C
chengduoZH 已提交
210
        } else if (pooling_type == "avg") {
211 212 213 214 215
          std::vector<int> reduce_dim;
          int reduce_num = getReduceNum(*in_x, out, data_format, &reduce_dim);

          if (reduce_num > 0 &&
              adaptive) {  // for adaptive_avg_pool2d && output_size == 1
216 217 218 219 220 221
#ifdef __HIPCC__
            auto stream = dev_ctx.stream();
            TensorReduce<T, T, hipcub::Sum, DivideFunctor<T>>(
                *in_x, out, reduce_dim, static_cast<T>(0), hipcub::Sum(),
                DivideFunctor<T>(reduce_num), stream);
#elif defined(__NVCC__)
222 223 224 225 226 227 228 229 230 231
            auto stream = dev_ctx.stream();
            TensorReduce<T, T, cub::Sum, DivideFunctor<T>>(
                *in_x, out, reduce_dim, static_cast<T>(0), cub::Sum(),
                DivideFunctor<T>(reduce_num), stream);
#else  // for cpu
            paddle::operators::math::Pool2dFunctor<
                DeviceContext, paddle::operators::math::AvgPool<T>, T>
                pool2d_forward;
            paddle::operators::math::AvgPool<T> pool_process;
            pool2d_forward(dev_ctx, *in_x, ksize, strides, paddings,
232
                           data_format, exclusive, adaptive, out, pool_process);
233 234 235 236 237 238 239
#endif
          } else {  // avgpool_2d or  adaptive_avg_pool2d && output_size != 1
            paddle::operators::math::Pool2dFunctor<
                DeviceContext, paddle::operators::math::AvgPool<T>, T>
                pool2d_forward;
            paddle::operators::math::AvgPool<T> pool_process;
            pool2d_forward(dev_ctx, *in_x, ksize, strides, paddings,
240
                           data_format, exclusive, adaptive, out, pool_process);
241
          }
242 243 244 245
        }
      } break;
      case 3: {
        if (pooling_type == "max") {
C
chengduoZH 已提交
246
          paddle::operators::math::Pool3dFunctor<
Q
QI JUN 已提交
247
              DeviceContext, paddle::operators::math::MaxPool<T>, T>
248
              pool3d_forward;
249
          paddle::operators::math::MaxPool<T> pool_process;
250
          pool3d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
251
                         true, false, out, pool_process);
252

C
chengduoZH 已提交
253
        } else if (pooling_type == "avg") {
C
chengduoZH 已提交
254
          paddle::operators::math::Pool3dFunctor<
Q
QI JUN 已提交
255
              DeviceContext, paddle::operators::math::AvgPool<T>, T>
256
              pool3d_forward;
257
          paddle::operators::math::AvgPool<T> pool_process;
258
          pool3d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
259
                         exclusive, adaptive, out, pool_process);
260 261
        }
      } break;
262 263 264 265
      default: {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Pool op only supports 2D and 3D input."));
      }
266 267 268 269
    }
  }
};

Q
QI JUN 已提交
270
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
271
class PoolGradKernel : public framework::OpKernel<T> {
272 273
 public:
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduoZH 已提交
274
    const Tensor* in_x = context.Input<Tensor>("X");
275 276 277
    const Tensor* out = context.Input<Tensor>("Out");
    const Tensor* out_grad =
        context.Input<Tensor>(framework::GradVarName("Out"));
C
chengduoZH 已提交
278
    Tensor* in_x_grad = context.Output<Tensor>(framework::GradVarName("X"));
279

C
chengduoZH 已提交
280
    std::string pooling_type = context.Attr<std::string>("pooling_type");
281 282 283
    std::vector<int> ksize = context.Attr<std::vector<int>>("ksize");
    std::vector<int> strides = context.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
284
    bool exclusive = context.Attr<bool>("exclusive");
285
    bool adaptive = context.Attr<bool>("adaptive");
286 287 288 289 290 291
    std::string data_format = context.Attr<std::string>("data_format");
    bool global_pooling = context.Attr<bool>("global_pooling");
    std::string padding_algorithm =
        context.Attr<std::string>("padding_algorithm");

    const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");
292

293 294 295 296 297 298 299 300 301 302
    // update paddings
    auto in_x_dims = in_x->dims();
    framework::DDim data_dims;
    if (channel_last) {
      data_dims = framework::slice_ddim(in_x_dims, 1, in_x_dims.size() - 1);
    } else {
      data_dims = framework::slice_ddim(in_x_dims, 2, in_x_dims.size());
    }
    UpdatePadding(&paddings, global_pooling, adaptive, padding_algorithm,
                  data_dims, strides, ksize);
303 304
    if (data_dims.size() * 2 == static_cast<int>(paddings.size())) {
      for (int i = 0; i < data_dims.size(); ++i) {
305
        paddings.erase(paddings.begin() + i + 1);
C
fix bug  
chengduoZH 已提交
306
      }
307
    }
308 309 310 311 312

    if (global_pooling) {
      UpdateKsize(&ksize, data_dims);
    }

Q
QI JUN 已提交
313
    auto& dev_ctx = context.template device_context<DeviceContext>();
C
chengduoZH 已提交
314 315
    if (in_x_grad) {
      in_x_grad->mutable_data<T>(context.GetPlace());
Q
QI JUN 已提交
316
      paddle::operators::math::SetConstant<DeviceContext, T> set_constant;
317
      set_constant(dev_ctx, in_x_grad, static_cast<T>(0.0));
318 319 320 321

      switch (ksize.size()) {
        case 2: {
          if (pooling_type == "max") {
Q
QI JUN 已提交
322
            paddle::operators::math::MaxPool2dGradFunctor<DeviceContext, T>
323
                pool2d_backward;
Q
QI JUN 已提交
324
            pool2d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
325
                            paddings, data_format, in_x_grad);
C
chengduoZH 已提交
326
          } else if (pooling_type == "avg") {
C
chengduoZH 已提交
327
            paddle::operators::math::Pool2dGradFunctor<
Q
QI JUN 已提交
328
                DeviceContext, paddle::operators::math::AvgPoolGrad<T>, T>
329
                pool2d_backward;
330
            paddle::operators::math::AvgPoolGrad<T> pool_process;
Q
QI JUN 已提交
331
            pool2d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
332 333
                            paddings, data_format, exclusive, adaptive,
                            in_x_grad, pool_process);
334 335 336 337
          }
        } break;
        case 3: {
          if (pooling_type == "max") {
Q
QI JUN 已提交
338
            paddle::operators::math::MaxPool3dGradFunctor<DeviceContext, T>
339
                pool3d_backward;
Q
QI JUN 已提交
340
            pool3d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
341
                            paddings, data_format, in_x_grad);
C
chengduoZH 已提交
342
          } else if (pooling_type == "avg") {
C
chengduoZH 已提交
343
            paddle::operators::math::Pool3dGradFunctor<
Q
QI JUN 已提交
344
                DeviceContext, paddle::operators::math::AvgPoolGrad<T>, T>
345
                pool3d_backward;
346
            paddle::operators::math::AvgPoolGrad<T> pool_process;
Q
QI JUN 已提交
347
            pool3d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
348 349
                            paddings, data_format, exclusive, adaptive,
                            in_x_grad, pool_process);
350 351
          }
        } break;
352 353 354 355
        default: {
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Pool op only supports 2D and 3D input."));
        }
356 357 358 359 360 361 362
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle