concat_op.cc 9.6 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>
P
phlrain 已提交
18
#include <memory>
S
Siddharth Goyal 已提交
19
#include <string>
20 21
#include <vector>

22 23
#include "paddle/pten/kernels/funcs/concat_funcs.h"

P
phlrain 已提交
24 25 26 27
#ifdef PADDLE_WITH_MKLDNN
#include <paddle/fluid/platform/mkldnn_helper.h>
#endif

28 29
namespace paddle {
namespace operators {
30
using Tensor = framework::Tensor;
31 32 33 34 35

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

36
  void InferShape(framework::InferShapeContext *ctx) const override {
37 38
    OP_INOUT_CHECK(ctx->HasInputs("X"), "Input", "X", "Concat");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Concat");
39

40
    auto inputs_dims = ctx->GetInputsDim("X");
41

42
    const size_t inputs_num = inputs_dims.size();
43 44 45 46 47
    PADDLE_ENFORCE_GT(
        inputs_num, static_cast<size_t>(0),
        platform::errors::InvalidArgument(
            "The number of input tensors in concat op should > 0. But "
            "received inputs' length is 0."));
48
    if (inputs_num == 1) {
49 50
      VLOG(3) << "Warning: concat op have only one input, may waste memory";
    }
51

52 53 54 55 56 57 58 59 60
    if (ctx->HasInput("AxisTensor")) {
      auto out_dims =
          framework::make_ddim(std::vector<int>(inputs_dims[0].size(), -1));
      ctx->SetOutputDim("Out", out_dims);
      ctx->ShareLoD("X", /*->*/ "Out");
    } else {
      size_t axis =
          ComputeAxis(static_cast<int64_t>(ctx->Attrs().Get<int>("axis")),
                      static_cast<int64_t>(inputs_dims[0].size()));
61 62
      framework::DDim out_dims = pten::funcs::ComputeAndCheckShape(
          ctx->IsRuntime(), inputs_dims, axis);
63 64
      if (out_dims[axis] < 0) {
        out_dims[axis] = -1;
65
      }
66 67
      ctx->SetOutputDim("Out", out_dims);
      ctx->ShareLoD("X", /*->*/ "Out");
68 69
    }
  }
P
phlrain 已提交
70 71 72 73

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
74
    auto inputs = ctx.MultiInput<Tensor>("X");
75 76
    auto input_data_type = framework::proto::VarType::Type(0);
    bool flag = 0;
77 78 79
    for (auto *input : inputs) {
      if (input->IsInitialized() && input->numel() > 0) {
        input_data_type = input->type();
80 81 82 83 84
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
1
123malin 已提交
85 86
      PADDLE_THROW(platform::errors::InvalidArgument(
          "All Inputs of Concat OP are Empty!"));
87
    }
P
phlrain 已提交
88
#ifdef PADDLE_WITH_MKLDNN
89
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
P
phlrain 已提交
90 91 92 93 94 95 96
      return framework::OpKernelType(input_data_type, ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
97 98 99 100 101 102 103 104 105 106

  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "AxisTensor") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
107 108 109 110 111 112 113 114 115

  framework::KernelSignature GetExpectedPtenKernelArgs(
      const framework::ExecutionContext &ctx) const override {
    if (ctx.HasInput("AxisTensor")) {
      return framework::KernelSignature("concat", {"X"}, {"AxisTensor"},
                                        {"Out"});
    }
    return framework::KernelSignature("concat", {"X"}, {"axis"}, {"Out"});
  }
116 117 118 119
};

class ConcatOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
120
  void Make() override {
121 122
    AddInput("X", "Input tensors of concat operator.").AsDuplicable();
    AddOutput("Out", "Output tensor of concat operator.");
P
phlrain 已提交
123 124 125
    AddAttr<bool>(
        "use_mkldnn",
        "(bool, default false) Indicates if MKL-DNN kernel will be used")
Z
zmx 已提交
126 127
        .SetDefault(false)
        .AsExtra();
128
    AddAttr<int>("axis",
129 130 131 132
                 "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.")
133
        .SetDefault(0);
134 135 136 137 138 139
    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();
140 141 142 143
    AddAttr<bool>(
        "use_quantizer",
        "(bool, default false) "
        "This parameter is no longer used. Use 'mkldnn_data_type' instead.")
Z
zmx 已提交
144 145
        .SetDefault(false)
        .AsExtra();
146 147 148 149
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
Z
zmx 已提交
150 151
        .InEnum({"float32", "int8", "bfloat16"})
        .AsExtra();
152 153 154 155 156 157 158 159 160 161 162 163 164
    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");
165 166 167
  }
};

168 169
class ConcatOpGrad : public framework::OperatorWithKernel {
 public:
P
phlrain 已提交
170
  using framework::OperatorWithKernel::OperatorWithKernel;
171

172
  void InferShape(framework::InferShapeContext *ctx) const override {
C
chengduo 已提交
173 174 175
    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 已提交
176 177

    ctx->ShareAllLoD(in_x, out_x_g_n);
178
  }
P
phlrain 已提交
179 180 181 182

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));

#ifdef PADDLE_WITH_MKLDNN
    // extra checking if attr "use_mkldnn" exist is needed because
    // test_reverse_op is calling concat_grad kernel without setting
    // "use_mkldnn" to any value
    if (ctx.HasAttr("use_mkldnn") &&
        this->CanMKLDNNBeUsed(ctx, input_data_type)) {
      return framework::OpKernelType(input_data_type, ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
P
phlrain 已提交
198
  }
199 200 201 202 203 204 205 206 207 208

  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "AxisTensor") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
P
phlrain 已提交
209 210
};

211
DECLARE_NO_NEED_BUFFER_VARS_INFERER(ConcatOpGradNoNeedBufferVarInferer, "X");
P
phlrain 已提交
212

H
hong 已提交
213 214
template <typename T>
class ConcatGradOpMaker : public framework::SingleGradOpMaker<T> {
P
phlrain 已提交
215
 public:
H
hong 已提交
216
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
P
phlrain 已提交
217 218

 protected:
219
  void Apply(GradOpPtr<T> op) const override {
P
phlrain 已提交
220
    op->SetType("concat_grad");
H
hong 已提交
221
    op->SetInput("X", this->Input("X"));
H
hong 已提交
222 223 224
    if (this->HasInput("AxisTensor")) {
      op->SetInput("AxisTensor", this->Input("AxisTensor"));
    }
H
hong 已提交
225 226 227
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
    op->SetAttrMap(this->Attrs());
P
phlrain 已提交
228
  }
229 230
};

C
ceci3 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244
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());
  }
};

245 246 247 248
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
249
REGISTER_OPERATOR(concat, ops::ConcatOp, ops::ConcatOpMaker,
H
hong 已提交
250 251
                  ops::ConcatGradOpMaker<paddle::framework::OpDesc>,
                  ops::ConcatGradOpMaker<paddle::imperative::OpBase>);
P
phlrain 已提交
252
REGISTER_OPERATOR(concat_grad, ops::ConcatOpGrad,
C
ceci3 已提交
253 254
                  ops::ConcatDoubleGradOpMaker<paddle::framework::OpDesc>,
                  ops::ConcatDoubleGradOpMaker<paddle::imperative::OpBase>,
255
                  ops::ConcatOpGradNoNeedBufferVarInferer);
256

C
chengduoZH 已提交
257 258
REGISTER_OP_CPU_KERNEL(
    concat_grad,
259 260
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, float>,
261
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, bool>,
262
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int64_t>,
263 264
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext,
                          paddle::platform::float16>,
L
liuyuhui 已提交
265
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int>,
266 267 268 269 270
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, uint8_t>,
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext,
                          paddle::platform::complex<float>>,
    ops::ConcatGradKernel<paddle::platform::CPUDeviceContext,
                          paddle::platform::complex<double>>);