pad_op.h 2.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
W
wanghaoshuang 已提交
2

L
Luo Tao 已提交
3 4 5
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
W
wanghaoshuang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
W
wanghaoshuang 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
W
wanghaoshuang 已提交
14 15 16

#pragma once

17 18
#include <utility>
#include <vector>
Y
Yi Wang 已提交
19 20
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
C
chengduo 已提交
21
#include "paddle/fluid/operators/math/padding.h"
W
wanghaoshuang 已提交
22 23 24 25 26 27

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

Q
QI JUN 已提交
28
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
29
class PadKernel : public framework::OpKernel<T> {
W
wanghaoshuang 已提交
30 31
 public:
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduo 已提交
32 33 34 35 36 37 38 39 40
    auto pads = context.Attr<std::vector<int>>("paddings");
    T pad_value = context.Attr<T>("pad_value");
    auto* x = context.Input<Tensor>("X");
    auto* out = context.Output<Tensor>("Out");
    out->mutable_data<T>(context.GetPlace());

    int rank = x->dims().size();
    math::PaddingFunctor<DeviceContext, T>(rank, context, pads, pad_value, *x,
                                           out);
W
wanghaoshuang 已提交
41 42 43
  }
};

Q
QI JUN 已提交
44
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
45
class PadGradKernel : public framework::OpKernel<T> {
W
wanghaoshuang 已提交
46
 public:
W
wanghaoshuang 已提交
47
  void Compute(const framework::ExecutionContext& context) const override {
C
chengduo 已提交
48 49 50 51 52
    auto pads = context.Attr<std::vector<int>>("paddings");
    auto* d_out = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* d_x = context.Output<Tensor>(framework::GradVarName("X"));
    if (d_x == nullptr) {
      return;
W
wanghaoshuang 已提交
53
    }
C
chengduo 已提交
54 55 56 57 58

    d_x->mutable_data<T>(context.GetPlace());
    int rank = d_out->dims().size();
    math::PaddingGradFunctor<DeviceContext, T>(rank, context, pads, *d_out,
                                               d_x);
W
wanghaoshuang 已提交
59 60 61 62 63
  }
};

}  // namespace operators
}  // namespace paddle