pad_constant_like_op.cc 7.6 KB
Newer Older
C
chengduo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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

#include "paddle/fluid/operators/pad_constant_like_op.h"
16
#include <memory>
C
chengduo 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

namespace paddle {
namespace operators {

using framework::Tensor;

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of PadConstantLikeOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Y"),
                   "Input(Y) of PadConstantLikeOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of PadConstantLikeOp should not be null.");

    auto x_dim = ctx->GetInputDim("X");
    auto y_dim = ctx->GetInputDim("Y");

    PADDLE_ENFORCE_EQ(x_dim.size(), y_dim.size(),
T
tianshuo78520a 已提交
39
                      "The dimension of X and Y should be the same.");
C
chengduo 已提交
40 41

    for (int i = 0; i < x_dim.size(); ++i) {
42 43 44
      if ((!ctx->IsRuntime()) && ((x_dim[i] == -1) || (y_dim[i] == -1))) {
        continue;
      } else {
S
SunGaofeng 已提交
45 46 47 48
        PADDLE_ENFORCE_GE(
            x_dim[i], y_dim[i],
            "expected X_dim[i] >= Y_dim[i], but received %d < %d for dim %d",
            x_dim[i], y_dim[i], i);
49
      }
C
chengduo 已提交
50
    }
51

C
chengduo 已提交
52 53 54
    ctx->SetOutputDim("Out", x_dim);
    ctx->ShareLoD("X", /*->*/ "Out");
  }
C
chengduo 已提交
55 56 57 58

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
59 60 61
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Y"),
        ctx.device_context());
C
chengduo 已提交
62
  }
C
chengduo 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
};

class PadConstantLikeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input of pad_constant_like op. "
             "The input should be a k-D tensor(k > 0 and k < 7)");
    AddInput("Y",
             "The input of pad_constant_like op. "
             "The input should be a k-D tensor(k > 0 and k < 7)");
    AddOutput("Out",
              "The output of pad_constant_like op. "
              "A tensor with the same shape as X.");
    AddAttr<float>("pad_value",
                   "(float, default 0.0) "
                   "The value to fill the padded areas.")
        .SetDefault(0.0f);
    AddComment(R"DOC(
PadConstantLikeOp Operator.

Pad input(Y) with a pad_value, the number of values padded to the edges of each
axis is specified by the difference of the shape of X and Y.
P
peizhilin 已提交
86
((0, shape_x_0 - shape_y_0), ... (0, shape_x_n - shape_y_n)) unique pad widths for
C
chengduo 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
each axis.
The input should be a k-D tensor(k > 0 and k < 7). As an example:

case1:
    Given:
        X = [[1, 2],
             [3, 4],
             [1, 2],
             [3, 4]]],
        X.shape = (4, 2)

        Y = [[5, 6],
            [7, 8]],
        Y.shape = (2, 2)

    And
        pad_value = 0,

    Return:
        Out = [[5, 6],
               [7, 8],
               [0, 0],
               [0, 0]]
        Out.shape = (4, 2)

case2:
    Given:
        X = [[[[ 0,  1,  2],
               [ 3,  4,  5]],
              [[ 6,  7,  8],
               [ 9, 10, 11]],
              [[12, 13, 14],
               [15, 16, 17]]],
             [[[18, 19, 20],
               [21, 22, 23]],
              [[24, 25, 26],
               [27, 28, 29]],
              [[30, 31, 32],
               [33, 34, 35]]]]
        X.shape = (2, 3, 2, 3)

        Y = [[[[35, 36, 37]],
              [[38, 39, 40]],
              [[41, 42, 43]]]]
        Y.shape = (1, 3, 1, 3)

    And
        pad_value = -1,

    Return:

        Out = [[[[35, 36, 37],
                 [-1, -1, -1]],
                [[38, 39, 40],
                 [-1, -1, -1]],
                [[41, 42, 43],
                 [-1, -1, -1]]],
               [[[-1, -1, -1],
                 [-1, -1, -1]],
                [[-1, -1, -1],
                 [-1, -1, -1]],
                [[-1, -1, -1],
                 [-1, -1, -1]]]]
        Out.shape = (2, 3, 2, 3)
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null");
    auto y_dim = ctx->GetInputDim("Y");
    auto dout_dim = ctx->GetInputDim(framework::GradVarName("Out"));

    PADDLE_ENFORCE_EQ(dout_dim.size(), y_dim.size(),
T
tianshuo78520a 已提交
167
                      "The dimension of X and Y should be the same.");
C
chengduo 已提交
168 169 170 171 172 173 174

    auto y_grad_name = framework::GradVarName("Y");
    if (ctx->HasOutput(y_grad_name)) {
      ctx->SetOutputDim(y_grad_name, y_dim);
      ctx->ShareLoD("Y", /*->*/ y_grad_name);

      for (int i = 0; i < y_dim.size(); ++i) {
175 176 177
        if ((!ctx->IsRuntime()) && ((dout_dim[i] == -1) || (y_dim[i] == -1))) {
          continue;
        } else {
S
SunGaofeng 已提交
178 179 180 181
          PADDLE_ENFORCE_GE(dout_dim[i], y_dim[i],
                            "expected Out_dim[i] >= Y_dim[i], but received %d "
                            "< %d for dim %d",
                            dout_dim[i], y_dim[i], i);
182
        }
C
chengduo 已提交
183 184 185
      }
    }
  }
C
chengduo 已提交
186 187 188 189

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
190 191 192
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Y"),
        ctx.device_context());
C
chengduo 已提交
193
  }
C
chengduo 已提交
194 195
};

H
hong 已提交
196 197
template <typename T>
class PadConstantLikeOpGradMaker : public framework::SingleGradOpMaker<T> {
C
chengduo 已提交
198
 public:
H
hong 已提交
199
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
C
chengduo 已提交
200 201

 protected:
202
  void Apply(GradOpPtr<T> bind) const override {
C
chengduo 已提交
203
    bind->SetType("pad_constant_like_grad");
H
hong 已提交
204 205 206 207
    bind->SetInput("Y", this->Input("Y"));
    bind->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    bind->SetOutput(framework::GradVarName("Y"), this->InputGrad("Y"));
    bind->SetAttrMap(this->Attrs());
C
chengduo 已提交
208 209 210 211 212 213 214 215 216
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(pad_constant_like, ops::PadConstantLikeOp,
H
hong 已提交
217 218 219
                  ops::PadConstantLikeOpMaker,
                  ops::PadConstantLikeOpGradMaker<paddle::framework::OpDesc>,
                  ops::PadConstantLikeOpGradMaker<paddle::imperative::OpBase>);
C
chengduo 已提交
220 221 222 223 224
REGISTER_OPERATOR(pad_constant_like_grad, ops::PadConstantLikeOpGrad);

REGISTER_OP_CPU_KERNEL(
    pad_constant_like,
    ops::PadConstantLikeKernel<paddle::platform::CPUDeviceContext, float>,
225 226 227
    ops::PadConstantLikeKernel<paddle::platform::CPUDeviceContext, double>,
    ops::PadConstantLikeKernel<paddle::platform::CPUDeviceContext, int>,
    ops::PadConstantLikeKernel<paddle::platform::CPUDeviceContext, int64_t>);
C
chengduo 已提交
228 229 230
REGISTER_OP_CPU_KERNEL(
    pad_constant_like_grad,
    ops::PadConstantLikeGradKernel<paddle::platform::CPUDeviceContext, float>,
231 232 233 234
    ops::PadConstantLikeGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::PadConstantLikeGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::PadConstantLikeGradKernel<paddle::platform::CPUDeviceContext,
                                   int64_t>);