pool_op.h 13.8 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
#if defined(__HIPCC__) || defined(__NVCC__)
26
#include "paddle/fluid/operators/reduce_ops/reduce_op.cu.h"
27 28
#endif

29 30 31 32
namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
33 34 35 36 37 38

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

  void InferShape(framework::InferShapeContext* ctx) const override;
39 40 41 42

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override;
43 44 45

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
46
      const framework::OpKernelType& expected_kernel_type) const override;
47 48 49 50 51 52 53
};

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

  void InferShape(framework::InferShapeContext* ctx) const override;
54 55 56 57

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override;
58 59 60 61

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const override;
62 63 64 65
};

class Pool2dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
66
  void Make() override;
67 68 69 70
};

class Pool3dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
71
  void Make() override;
72
};
73 74 75

template <typename T = int>
inline void UpdatePadding(std::vector<T>* paddings, const bool global_pooling,
76 77 78
                          const bool adaptive,
                          const std::string padding_algorithm,
                          const framework::DDim data_dims,
79 80
                          const std::vector<T>& strides,
                          const std::vector<T>& ksize) {
81
  // set padding size == data_dims.size() * 2
82
  auto data_shape = framework::vectorize<T>(data_dims);
83 84
  if (static_cast<int>(paddings->size()) == data_dims.size()) {
    for (int i = 0; i < data_dims.size(); ++i) {
85
      T copy_pad = *(paddings->begin() + 2 * i);
86 87 88
      paddings->insert(paddings->begin() + 2 * i + 1, copy_pad);
    }
  } else {
89 90 91 92 93
    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));
94 95
  }

96
  // when padding_algorithm is "VALID" or "SAME"
97
  if (padding_algorithm == "SAME") {
98
    for (int i = 0; i < data_dims.size(); ++i) {
99 100
      T out_size = (data_dims[i] + strides[i] - 1) / strides[i];
      T pad_sum =
101 102
          std::max((out_size - 1) * strides[i] + ksize[i] - data_shape[i],
                   static_cast<T>(0));
103 104
      T pad_0 = pad_sum / 2;
      T pad_1 = pad_sum - pad_0;
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
      *(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;
    }
  }
}

122 123
template <typename T = int>
inline void UpdateKsize(std::vector<T>* ksize,
124 125 126
                        const framework::DDim data_dims) {
  ksize->resize(static_cast<size_t>(data_dims.size()));
  for (size_t i = 0; i < ksize->size(); ++i) {
127
    *(ksize->begin() + i) = static_cast<T>(data_dims[i]);
128 129
  }
}
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
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 已提交
151
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
152
class PoolKernel : public framework::OpKernel<T> {
153 154
 public:
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduoZH 已提交
155
    const Tensor* in_x = context.Input<Tensor>("X");
156
    Tensor* out = context.Output<Tensor>("Out");
157

C
chengduoZH 已提交
158
    std::string pooling_type = context.Attr<std::string>("pooling_type");
159 160 161
    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");
162
    std::string data_format = context.Attr<std::string>("data_format");
163
    bool exclusive = context.Attr<bool>("exclusive");
164
    bool adaptive = context.Attr<bool>("adaptive");
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    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);
182 183
    if (data_dims.size() * 2 == static_cast<int>(paddings.size())) {
      for (int i = 0; i < data_dims.size(); ++i) {
184
        paddings.erase(paddings.begin() + i + 1);
185 186
      }
    }
187 188 189 190

    if (global_pooling) {
      UpdateKsize(&ksize, data_dims);
    }
Q
QI JUN 已提交
191
    auto& dev_ctx = context.template device_context<DeviceContext>();
192 193 194
    switch (ksize.size()) {
      case 2: {
        if (pooling_type == "max") {
C
chengduoZH 已提交
195
          paddle::operators::math::Pool2dFunctor<
Q
QI JUN 已提交
196
              DeviceContext, paddle::operators::math::MaxPool<T>, T>
197
              pool2d_forward;
198
          paddle::operators::math::MaxPool<T> pool_process;
199
          pool2d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
200
                         true, false, out, pool_process);
201

C
chengduoZH 已提交
202
        } else if (pooling_type == "avg") {
203 204 205 206
          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
207
#if defined(__HIPCC__) || defined(__NVCC__)
208
            auto stream = dev_ctx.stream();
209 210 211 212
            TensorReduceFunctorImpl<T, T, kps::AddFunctor,
                                    kps::DivideFunctor<T>>(
                *in_x, out, kps::DivideFunctor<T>(reduce_num), reduce_dim,
                stream);
213 214 215 216 217 218
#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,
219
                           data_format, exclusive, adaptive, out, pool_process);
220 221 222 223 224 225 226
#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,
227
                           data_format, exclusive, adaptive, out, pool_process);
228
          }
229 230 231 232
        }
      } break;
      case 3: {
        if (pooling_type == "max") {
C
chengduoZH 已提交
233
          paddle::operators::math::Pool3dFunctor<
Q
QI JUN 已提交
234
              DeviceContext, paddle::operators::math::MaxPool<T>, T>
235
              pool3d_forward;
236
          paddle::operators::math::MaxPool<T> pool_process;
237
          pool3d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
238
                         true, false, out, pool_process);
239

C
chengduoZH 已提交
240
        } else if (pooling_type == "avg") {
C
chengduoZH 已提交
241
          paddle::operators::math::Pool3dFunctor<
Q
QI JUN 已提交
242
              DeviceContext, paddle::operators::math::AvgPool<T>, T>
243
              pool3d_forward;
244
          paddle::operators::math::AvgPool<T> pool_process;
245
          pool3d_forward(dev_ctx, *in_x, ksize, strides, paddings, data_format,
246
                         exclusive, adaptive, out, pool_process);
247 248
        }
      } break;
249 250 251 252
      default: {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Pool op only supports 2D and 3D input."));
      }
253 254 255 256
    }
  }
};

Q
QI JUN 已提交
257
template <typename DeviceContext, typename T>
C
chengduoZH 已提交
258
class PoolGradKernel : public framework::OpKernel<T> {
259 260
 public:
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduoZH 已提交
261
    const Tensor* in_x = context.Input<Tensor>("X");
262 263 264
    const Tensor* out = context.Input<Tensor>("Out");
    const Tensor* out_grad =
        context.Input<Tensor>(framework::GradVarName("Out"));
C
chengduoZH 已提交
265
    Tensor* in_x_grad = context.Output<Tensor>(framework::GradVarName("X"));
266

C
chengduoZH 已提交
267
    std::string pooling_type = context.Attr<std::string>("pooling_type");
268 269 270
    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");
271
    bool exclusive = context.Attr<bool>("exclusive");
272
    bool adaptive = context.Attr<bool>("adaptive");
273 274 275 276 277 278
    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");
279

280 281 282 283 284 285 286 287 288 289
    // 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);
290 291
    if (data_dims.size() * 2 == static_cast<int>(paddings.size())) {
      for (int i = 0; i < data_dims.size(); ++i) {
292
        paddings.erase(paddings.begin() + i + 1);
C
fix bug  
chengduoZH 已提交
293
      }
294
    }
295 296 297 298 299

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

Q
QI JUN 已提交
300
    auto& dev_ctx = context.template device_context<DeviceContext>();
C
chengduoZH 已提交
301 302
    if (in_x_grad) {
      in_x_grad->mutable_data<T>(context.GetPlace());
Q
QI JUN 已提交
303
      paddle::operators::math::SetConstant<DeviceContext, T> set_constant;
304
      set_constant(dev_ctx, in_x_grad, static_cast<T>(0.0));
305 306 307 308

      switch (ksize.size()) {
        case 2: {
          if (pooling_type == "max") {
Q
QI JUN 已提交
309
            paddle::operators::math::MaxPool2dGradFunctor<DeviceContext, T>
310
                pool2d_backward;
Q
QI JUN 已提交
311
            pool2d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
312
                            paddings, data_format, in_x_grad);
C
chengduoZH 已提交
313
          } else if (pooling_type == "avg") {
C
chengduoZH 已提交
314
            paddle::operators::math::Pool2dGradFunctor<
Q
QI JUN 已提交
315
                DeviceContext, paddle::operators::math::AvgPoolGrad<T>, T>
316
                pool2d_backward;
317
            paddle::operators::math::AvgPoolGrad<T> pool_process;
Q
QI JUN 已提交
318
            pool2d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
319 320
                            paddings, data_format, exclusive, adaptive,
                            in_x_grad, pool_process);
321 322 323 324
          }
        } break;
        case 3: {
          if (pooling_type == "max") {
Q
QI JUN 已提交
325
            paddle::operators::math::MaxPool3dGradFunctor<DeviceContext, T>
326
                pool3d_backward;
Q
QI JUN 已提交
327
            pool3d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
328
                            paddings, data_format, in_x_grad);
C
chengduoZH 已提交
329
          } else if (pooling_type == "avg") {
C
chengduoZH 已提交
330
            paddle::operators::math::Pool3dGradFunctor<
Q
QI JUN 已提交
331
                DeviceContext, paddle::operators::math::AvgPoolGrad<T>, T>
332
                pool3d_backward;
333
            paddle::operators::math::AvgPoolGrad<T> pool_process;
Q
QI JUN 已提交
334
            pool3d_backward(dev_ctx, *in_x, *out, *out_grad, ksize, strides,
335 336
                            paddings, data_format, exclusive, adaptive,
                            in_x_grad, pool_process);
337 338
          }
        } break;
339 340 341 342
        default: {
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Pool op only supports 2D and 3D input."));
        }
343 344 345 346 347
      }
    }
  }
};

348 349 350 351 352 353 354 355 356 357 358 359 360 361
template <typename DeviceContext, typename T>
class PoolGradGradKernel : public PoolKernel<DeviceContext, T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    std::string pooling_type = context.Attr<std::string>("pooling_type");
    if (pooling_type == "max") {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Pool op grad grad only supports avgpool."));
    } else {
      PoolKernel<DeviceContext, T>::Compute(context);
    }
  }
};

362 363
}  // namespace operators
}  // namespace paddle