concat_op.cc 7.7 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

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/concat_op.h"
1
123malin 已提交
16

17
#include <paddle/fluid/platform/complex.h>
18

P
phlrain 已提交
19
#include <memory>
S
Siddharth Goyal 已提交
20
#include <string>
21 22
#include <vector>

23
#include "paddle/fluid/framework/infershape_utils.h"
W
wangzhen38 已提交
24 25 26
#include "paddle/fluid/prim/api/composite_backward/composite_backward_api.h"
#include "paddle/fluid/prim/utils/static/composite_grad_desc_maker.h"
#include "paddle/fluid/prim/utils/static/desc_tensor.h"
27
#include "paddle/phi/infermeta/multiary.h"
28
#include "paddle/phi/kernels/funcs/concat_funcs.h"
29

30 31 32 33 34 35 36
namespace paddle {
namespace operators {

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

P
phlrain 已提交
37
 protected:
38
  phi::KernelKey GetExpectedKernelType(
P
phlrain 已提交
39
      const framework::ExecutionContext &ctx) const override {
40
    auto inputs = ctx.MultiInput<phi::DenseTensor>("X");
41 42
    auto input_data_type = framework::proto::VarType::Type(0);
    bool flag = 0;
43
    for (auto *input : inputs) {
44
      if (input->IsInitialized()) {
45
        input_data_type = framework::TransToProtoVarType(input->dtype());
46 47 48 49 50
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
1
123malin 已提交
51 52
      PADDLE_THROW(platform::errors::InvalidArgument(
          "All Inputs of Concat OP are Empty!"));
53
    }
54
    return phi::KernelKey(input_data_type, ctx.GetPlace());
P
phlrain 已提交
55
  }
56

57
  phi::KernelKey GetKernelTypeForVar(
58
      const std::string &var_name,
59
      const phi::DenseTensor &tensor,
60
      const phi::KernelKey &expected_kernel_type) const override {
61
    if (var_name == "AxisTensor") {
62 63 64
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
65
    }
66 67
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
68
  }
69 70 71 72
};

class ConcatOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
73
  void Make() override {
74 75 76
    AddInput("X", "Input tensors of concat operator.").AsDuplicable();
    AddOutput("Out", "Output tensor of concat operator.");
    AddAttr<int>("axis",
77 78 79 80
                 "The axis along which the input tensors will be concatenated."
                 "The axis could also be negative numbers. Negative axis is "
                 "interpreted as counting from the end of the rank."
                 "i.e., axis + rank(X) th dimension.")
81 82
        .SetDefault(0)
        .SupportTensor();
83 84 85 86 87 88
    AddInput("AxisTensor",
             "(Tensor) The axis along which the input tensors will be "
             "concatenated.  "
             "It has higher priority than Attr(axis). "
             "The shape of AxisTensor must be [1].")
        .AsDispensable();
89 90 91 92 93 94 95 96 97 98 99 100 101
    AddComment(R"DOC(
Concat Operator.

Concatenate the input tensors along dimension axis.
Examples:
  Input[0] = [[1,2],[3,4]]
  Input[1] = [[5,6]]
  axis = 0
  Output = [[1,2],
            [3,4],
            [5,6]]

)DOC");
102 103 104
  }
};

105 106
class ConcatOpGrad : public framework::OperatorWithKernel {
 public:
P
phlrain 已提交
107
  using framework::OperatorWithKernel::OperatorWithKernel;
108

109
  void InferShape(framework::InferShapeContext *ctx) const override {
C
chengduo 已提交
110 111 112
    auto in_x = "X";
    auto out_x_g_n = framework::GradVarName(in_x);
    ctx->SetOutputsDim(out_x_g_n, ctx->GetInputsDim(in_x));
H
hong 已提交
113 114

    ctx->ShareAllLoD(in_x, out_x_g_n);
115
  }
P
phlrain 已提交
116 117

 protected:
118
  phi::KernelKey GetExpectedKernelType(
P
phlrain 已提交
119
      const framework::ExecutionContext &ctx) const override {
120 121
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
122
    return phi::KernelKey(input_data_type, ctx.GetPlace());
P
phlrain 已提交
123
  }
124

125
  phi::KernelKey GetKernelTypeForVar(
126
      const std::string &var_name,
127
      const phi::DenseTensor &tensor,
128
      const phi::KernelKey &expected_kernel_type) const override {
129
    if (var_name == "AxisTensor") {
130 131 132
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
133
    }
134 135
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
136
  }
P
phlrain 已提交
137 138
};

139
DECLARE_NO_NEED_BUFFER_VARS_INFERER(ConcatOpGradNoNeedBufferVarInferer, "X");
P
phlrain 已提交
140

H
hong 已提交
141 142
template <typename T>
class ConcatGradOpMaker : public framework::SingleGradOpMaker<T> {
P
phlrain 已提交
143
 public:
H
hong 已提交
144
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
P
phlrain 已提交
145 146

 protected:
147
  void Apply(GradOpPtr<T> op) const override {
P
phlrain 已提交
148
    op->SetType("concat_grad");
H
hong 已提交
149
    op->SetInput("X", this->Input("X"));
H
hong 已提交
150 151 152
    if (this->HasInput("AxisTensor")) {
      op->SetInput("AxisTensor", this->Input("AxisTensor"));
    }
H
hong 已提交
153 154 155
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
    op->SetAttrMap(this->Attrs());
P
phlrain 已提交
156
  }
157 158
};

W
wangzhen38 已提交
159 160 161 162 163
class ConcatCompositeGradOpMaker : public prim::CompositeGradOpMakerBase {
  using prim::CompositeGradOpMakerBase::CompositeGradOpMakerBase;

 public:
  void Apply() override {
164 165
    std::vector<paddle::Tensor> input = this->GetMultiForwardInput("X");
    paddle::optional<paddle::Tensor> tensor_axis =
W
wangzhen38 已提交
166
        this->GetOptionalSingleForwardInput("AxisTensor");
167
    paddle::Tensor out_grad = this->GetSingleOutputGrad("Out");
W
wangzhen38 已提交
168
    std::vector<paddle::Tensor> input_grad = this->GetMultiInputGrad("X");
W
wangzhen38 已提交
169

W
wangzhen38 已提交
170 171 172
    std::vector<paddle::Tensor *> input_grad_ptr;
    for (auto i = 0; i < static_cast<int>(input_grad.size()); ++i) {
      input_grad_ptr.push_back(&input_grad[i]);
W
wangzhen38 已提交
173 174
    }
    int axis = static_cast<int>(this->Attr<int>("axis"));
175
    std::vector<paddle::Tensor *> dx_ptr = this->GetOutputPtr(input_grad_ptr);
W
wangzhen38 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189
    std::vector<std::string> dx_name = this->GetOutputName(input_grad);

    VLOG(6) << "Runing concat_grad composite func";
    if (tensor_axis.is_initialized()) {
      PADDLE_THROW(platform::errors::Unimplemented(
          "We don't support dynamic index from tensor for concat composite "
          "grad for now. "));
    } else {
      prim::concat_grad<prim::DescTensor>(input, out_grad, axis, dx_ptr);
    }
    this->RecoverOutputName(input_grad, dx_name);
  }
};

C
ceci3 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203
template <typename T>
class ConcatDoubleGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

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

204 205 206 207
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
208

209 210
DECLARE_INFER_SHAPE_FUNCTOR(concat,
                            ConcatInferShapeFunctor,
211
                            PD_INFER_META(phi::ConcatInferMeta));
212

213 214 215
REGISTER_OPERATOR(concat,
                  ops::ConcatOp,
                  ops::ConcatOpMaker,
H
hong 已提交
216
                  ops::ConcatGradOpMaker<paddle::framework::OpDesc>,
217
                  ops::ConcatGradOpMaker<paddle::imperative::OpBase>,
W
wangzhen38 已提交
218
                  ops::ConcatCompositeGradOpMaker,
219
                  ConcatInferShapeFunctor);
220 221
REGISTER_OPERATOR(concat_grad,
                  ops::ConcatOpGrad,
C
ceci3 已提交
222 223
                  ops::ConcatDoubleGradOpMaker<paddle::framework::OpDesc>,
                  ops::ConcatDoubleGradOpMaker<paddle::imperative::OpBase>,
224
                  ops::ConcatOpGradNoNeedBufferVarInferer);