tile_op.cc 7.0 KB
Newer Older
L
lilong12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2016 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 <memory>
#include <string>
#include <vector>

19 20 21 22 23
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/unary.h"

L
lilong12 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
namespace paddle {
namespace operators {

using framework::Tensor;

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

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
  }

  framework::OpKernelType GetKernelTypeForVar(
42 43
      const std::string& var_name,
      const Tensor& tensor,
L
lilong12 已提交
44 45 46 47
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "repeat_times_tensor" || var_name == "RepeatTimes") {
      return expected_kernel_type;
    }
48 49
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
L
lilong12 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  }
};

class TileOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensor, default Tensor<float>). X is the input to be titled.");
    AddInput(
        "RepeatTimes",
        "(Tensor<int>, optional). If provided, it is the number of repeat times"
        " along specific axis. It has a higher priority than "
        "repeat_times_tensor and the repeat_times attribute.")
        .AsDispensable();
    AddInput("repeat_times_tensor",
             "(Tensor Tensor<int>), repeat times for X."
             "It has a higher priority than repeat_times, but a lower priority "
             "than RepeatTimes")
        .AsDuplicable()
        .AsDispensable();
    AddOutput("Out",
              "(Tensor, default Tensor<float>). A tensor with rank in [1, 6]."
              "After tiling, 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(repeat_times).");
    AddAttr<std::vector<int>>("repeat_times",
                              "The number of repeat times for each dimension.")
77 78
        .SetDefault({})
        .SupportTensor();
L
lilong12 已提交
79 80 81 82 83 84 85 86 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
    AddComment(R"DOC(
Tile operator repeats the input by given times number. You should set times
number for each dimension by providing attribute 'repeat_times'. The rank of X
should be in [1, 6]. Please note that size of 'repeat_times' must be the same
with X's rank. Following is a using case:

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

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

Attr(repeat_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]]
        ]

)DOC");
  }
};

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "TileGrad");
112 113 114 115
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
                   "TileGrad");
L
lilong12 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

    auto x_dims = ctx->GetInputDim("X");
    auto x_grad_name = framework::GradVarName("X");

    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
  }

  framework::OpKernelType GetKernelTypeForVar(
134 135
      const std::string& var_name,
      const Tensor& tensor,
L
lilong12 已提交
136 137 138 139
      const framework::OpKernelType& expected_kernel_type) const override {
    if (var_name == "repeat_times_tensor" || var_name == "RepeatTimes") {
      return expected_kernel_type;
    }
140 141
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
L
lilong12 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  }
};

template <typename T>
class TileGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

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

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
template <typename T>
class TileDoubleGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

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

L
lilong12 已提交
182 183 184 185 186 187
DECLARE_NO_NEED_BUFFER_VARS_INFERER(TileGradNoNeedBufVarsInferer, "X");

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
188

189 190
DECLARE_INFER_SHAPE_FUNCTOR(tile,
                            TileInferMetaFunctor,
191 192
                            PD_INFER_META(phi::TileInferMeta));

193 194 195
REGISTER_OPERATOR(tile,
                  ops::TileOp,
                  ops::TileOpMaker,
L
lilong12 已提交
196
                  ops::TileGradOpMaker<paddle::framework::OpDesc>,
197 198
                  ops::TileGradOpMaker<paddle::imperative::OpBase>,
                  TileInferMetaFunctor);
199 200
REGISTER_OPERATOR(tile_grad,
                  ops::TileGradOp,
201 202
                  ops::TileDoubleGradOpMaker<paddle::framework::OpDesc>,
                  ops::TileDoubleGradOpMaker<paddle::imperative::OpBase>,
L
lilong12 已提交
203
                  ops::TileGradNoNeedBufVarsInferer);