expand_op.cc 10.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
yangyaming 已提交
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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/expand_op.h"
S
sneaxiy 已提交
16
#include <memory>
17
#include <string>
18
#include <vector>
Y
yangyaming 已提交
19 20 21 22 23 24 25 26 27 28 29

namespace paddle {
namespace operators {

using framework::Tensor;

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

 protected:
Y
yangyaming 已提交
30
  void InferShape(framework::InferShapeContext* ctx) const override {
31 32
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Expand");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Expand");
Y
yangyaming 已提交
33
    auto x_dims = ctx->GetInputDim("X");
L
liym27 已提交
34
    auto expand_times = ctx->Attrs().Get<std::vector<int>>("expand_times");
35

L
liym27 已提交
36 37
    if (expand_times.size() == 0) {
      expand_times = std::vector<int>(x_dims.size(), -1);
38
    }
Y
yangyaming 已提交
39

40 41 42 43 44 45 46 47 48 49 50 51 52
    PADDLE_ENFORCE_EQ(
        static_cast<size_t>(x_dims.size()), expand_times.size(),
        platform::errors::InvalidArgument(
            "The number of elements (%d) of 'expand_times' for "
            "Op(expand) must be equal to the number of dimensions "
            "(%d) of the input.",
            expand_times.size(), static_cast<size_t>(x_dims.size())));
    PADDLE_ENFORCE_LE(
        x_dims.size(), 6,
        platform::errors::InvalidArgument(
            "The number of dimensions of the input for Op(expand) "
            "must not be greater than 6, but the value received is %d.",
            x_dims.size()));
Y
yangyaming 已提交
53 54 55

    std::vector<int64_t> out_shape(x_dims.size());
    for (size_t i = 0; i < expand_times.size(); ++i) {
56 57 58
      if (x_dims[i] == -1 || expand_times[i] == -1) {
        out_shape[i] = -1;
      } else {
L
liym27 已提交
59 60
        PADDLE_ENFORCE_GT(
            expand_times[i], 0,
61 62 63 64
            platform::errors::InvalidArgument(
                "The %uth element of 'expand_times' for Op(expand) must be "
                "greater than 0, but the value given is %d.",
                i, expand_times[i]));
65 66
        out_shape[i] = x_dims[i] * expand_times[i];
      }
M
minqiyang 已提交
67 68
    }

Y
yangyaming 已提交
69
    ctx->SetOutputDim("Out", framework::make_ddim(out_shape));
70 71 72
    if (out_shape[0] == x_dims[0]) {
      ctx->ShareLoD("X", "Out");
    }
Y
yangyaming 已提交
73
  }
74 75 76 77

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
78 79 80
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
81 82 83 84 85
  }

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const override {
L
liym27 已提交
86
    if (var_name == "expand_times_tensor" || var_name == "ExpandTimes") {
87 88 89 90 91
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
Y
yangyaming 已提交
92 93 94 95
};

class ExpandOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
96
  void Make() override {
Y
yangyaming 已提交
97
    AddInput("X",
C
caoying03 已提交
98 99
             "(Tensor, default Tensor<float>). A tensor with rank in [1, 6]."
             "X is the input to be expanded.");
L
liym27 已提交
100 101 102 103 104 105 106 107 108
    AddInput("ExpandTimes",
             "(Tensor<int>), optional). If provided, expand according to "
             "this given expand times. It has a higher priority than "
             "expand_times_tensor and expand_times.")
        .AsDispensable();
    AddInput("expand_times_tensor",
             "(Tensor Tensor<int>), epxand times for X."
             "It has a higher priority than expand_times, but a lower priority "
             "than ExpandTimes")
109 110
        .AsDuplicable()
        .AsDispensable();
Y
yangyaming 已提交
111
    AddOutput("Out",
C
caoying03 已提交
112 113 114 115 116
              "(Tensor, default Tensor<float>). A tensor with rank in [1, 6]."
              "The rank of Output(Out) have the same with Input(X). "
              "After expanding, size of each dimension of Output(Out) is equal "
              "to size of the corresponding dimension of Input(X) multiplying "
              "the corresponding value given by Attr(expand_times).");
117
    AddAttr<std::vector<int>>("expand_times",
118 119
                              "Expand times number for each dimension.")
        .SetDefault({});
Y
yangyaming 已提交
120
    AddComment(R"DOC(
Y
yangyaming 已提交
121
Expand operator tiles the input by given times number. You should set times
122
number for each dimension by providing attribute 'expand_times'. The rank of X
C
caoying03 已提交
123 124
should be in [1, 6]. Please note that size of 'expand_times' must be the same
with X's rank. Following is a using case:
Y
yangyaming 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

Input(X) is a 3-D tensor with shape [2, 3, 1]:

        [
           [[1], [2], [3]],
           [[4], [5], [6]]
        ]

Attr(expand_times):  [1, 2, 2]

Output(Out) is a 3-D tensor with shape [2, 6, 2]:

        [
            [[1, 1], [2, 2], [3, 3], [1, 1], [2, 2], [3, 3]],
            [[4, 4], [5, 5], [6, 6], [4, 4], [5, 5], [6, 6]]
        ]

Y
yangyaming 已提交
142 143 144 145 146 147 148 149 150
)DOC");
  }
};

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

 protected:
Y
yangyaming 已提交
151
  void InferShape(framework::InferShapeContext* ctx) const override {
152 153 154
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "ExpandGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   framework::GradVarName("Out"), "ExpandGrad");
155

Y
yangyaming 已提交
156 157
    auto x_dims = ctx->GetInputDim("X");
    std::vector<int> expand_times =
158
        ctx->Attrs().Get<std::vector<int>>("expand_times");
159

Y
yangyaming 已提交
160
    auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
Y
yangyaming 已提交
161

M
minqiyang 已提交
162
    size_t start_pos = 0u;
M
minqiyang 已提交
163
    if (!ctx->IsRuntime() && x_dims[0] < 0) {
M
minqiyang 已提交
164
      PADDLE_ENFORCE_EQ(
M
minqiyang 已提交
165
          x_dims[0], out_dims[0],
166 167 168 169
          platform::errors::InvalidArgument(
              "The first dimension size (%d) of Input(Out@GRAD) should be "
              "equal to the crroresponding dimension size (%d) of Input(X)",
              out_dims[0], x_dims[0]));
M
minqiyang 已提交
170 171 172 173
      start_pos = 1u;
    }

    for (size_t i = start_pos; i < expand_times.size(); ++i) {
L
liym27 已提交
174 175 176
      if (expand_times[i] == -1) {
        continue;
      } else {
L
liym27 已提交
177 178 179
        if (ctx->IsRuntime()) {
          PADDLE_ENFORCE_EQ(
              x_dims[i] * expand_times[i], out_dims[i],
180 181 182 183 184
              platform::errors::InvalidArgument(
                  "The %uth dimension size (%d) of Input(Out@GRAD) should be "
                  "equal to the multiplication of the crroresponding dimension "
                  "sizes of Input(X) (%d) and expand_times (%d).",
                  i, out_dims[i], x_dims[i], expand_times[i]));
L
liym27 已提交
185
        }
L
liym27 已提交
186
      }
Y
yangyaming 已提交
187
    }
Y
yangyaming 已提交
188 189 190 191 192
    auto x_grad_name = framework::GradVarName("X");

    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
Y
yangyaming 已提交
193
  }
194 195 196 197

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
198 199 200
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
201 202 203 204 205 206 207 208 209 210 211
  }

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "expand_times_tensor") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
Y
yangyaming 已提交
212 213
};

H
hong 已提交
214 215
template <typename T>
class ExpandGradOpMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
216
 public:
H
hong 已提交
217
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
218 219

 protected:
220
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
221
    op->SetType("expand_grad");
H
hong 已提交
222 223 224 225 226 227
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetInput("expand_times_tensor", this->Input("expand_times_tensor"));
    op->SetInput("ExpandTimes", this->Input("ExpandTimes"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
228 229 230
  }
};

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
template <typename T>
class ExpandDoubleGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetInput("X", this->OutputGrad(framework::GradVarName("X")));
    op->SetOutput("Out", this->InputGrad(framework::GradVarName("Out")));
    if (this->HasInput("expand_times_tensor")) {
      op->SetInput("expand_times_tensor", this->Input("expand_times_tensor"));
    }
    if (this->HasInput("ExpandTimes")) {
      op->SetInput("ExpandTimes", this->Input("ExpandTimes"));
    }
    op->SetAttrMap(this->Attrs());
    op->SetType("expand");
  }
};

251
DECLARE_NO_NEED_BUFFER_VARS_INFERER(ExpandGradNoNeedBufVarsInferer, "X");
252

Y
yangyaming 已提交
253 254 255 256
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
257
REGISTER_OPERATOR(expand, ops::ExpandOp, ops::ExpandOpMaker,
H
hong 已提交
258 259
                  ops::ExpandGradOpMaker<paddle::framework::OpDesc>,
                  ops::ExpandGradOpMaker<paddle::imperative::OpBase>);
260
REGISTER_OPERATOR(expand_grad, ops::ExpandGradOp,
261 262
                  ops::ExpandDoubleGradOpMaker<paddle::framework::OpDesc>,
                  ops::ExpandDoubleGradOpMaker<paddle::imperative::OpBase>,
263
                  ops::ExpandGradNoNeedBufVarsInferer);
Y
yangyaming 已提交
264
REGISTER_OP_CPU_KERNEL(
265 266 267
    expand, ops::ExpandKernel<paddle::platform::CPUDeviceContext, float>,
    ops::ExpandKernel<paddle::platform::CPUDeviceContext, double>,
    ops::ExpandKernel<paddle::platform::CPUDeviceContext, int>,
W
wangchaochaohu 已提交
268
    ops::ExpandKernel<paddle::platform::CPUDeviceContext, int64_t>,
269
    ops::ExpandKernel<paddle::platform::CPUDeviceContext, bool>);
Q
QI JUN 已提交
270 271
REGISTER_OP_CPU_KERNEL(
    expand_grad,
272
    ops::ExpandGradKernel<paddle::platform::CPUDeviceContext, float>,
W
wangchaochaohu 已提交
273 274 275
    ops::ExpandGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::ExpandGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::ExpandGradKernel<paddle::platform::CPUDeviceContext, int64_t>);