split_op.cc 6.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yancey 已提交
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/split_op.h"
16

17
#include <string>
Y
Yancey 已提交
18

19 20 21
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/infermeta/unary.h"

Y
Yancey 已提交
22 23 24 25 26 27 28 29
namespace paddle {
namespace operators {
using framework::Tensor;

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

30
  void InferShape(framework::InferShapeContext *ctx) const override {
31 32
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"),
                      true,
33 34
                      platform::errors::InvalidArgument(
                          "Input(X) of SplitOp should not be null."));
35 36
    PADDLE_ENFORCE_GE(ctx->Outputs("Out").size(),
                      1UL,
37 38 39 40 41 42 43 44 45 46 47 48
                      platform::errors::InvalidArgument(
                          "Outputs(Out) of SplitOp should not be empty."));
    auto in_dims = ctx->GetInputDim("X");
    auto outs_names = ctx->Outputs("Out");
    size_t axis = static_cast<size_t>(ctx->Attrs().Get<int>("axis"));
    size_t num = static_cast<size_t>(ctx->Attrs().Get<int>("num"));
    std::vector<int> sections = static_cast<std::vector<int>>(
        ctx->Attrs().Get<std::vector<int>>("sections"));
    const size_t outs_number = outs_names.size();

    if (sections.size() > 0) {
      PADDLE_ENFORCE_EQ(
49 50
          sections.size(),
          outs_number,
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
          platform::errors::InvalidArgument("tensor split sections size "
                                            "should be equal to output size."));
    }

    if (ctx->HasInput("AxisTensor")) {
      auto out_dims = phi::make_ddim(std::vector<int>(in_dims.size(), -1));
      std::vector<framework::DDim> outs_dims(outs_number, out_dims);
      ctx->SetOutputsDim("Out", outs_dims);
      for (size_t i = 0; i < outs_number; ++i) {
        ctx->ShareLoD("X", "Out", 0, i);
      }
      return;
    }

    bool each_section_is_known =
        (sections.size() > 0 && !ctx->HasInputs("SectionsTensorList"));

68 69 70 71 72 73 74
    auto outs_dims = UpdateOutsDims(ctx->IsRuntime(),
                                    each_section_is_known,
                                    in_dims,
                                    num,
                                    sections,
                                    axis,
                                    outs_number);
75 76 77 78 79 80 81 82 83
    ctx->SetOutputsDim("Out", outs_dims);
    if (axis != 0) {
      // Only pass LoD when not spliting along the first dim.
      for (size_t i = 0; i < outs_number; ++i) {
        ctx->ShareLoD("X", "Out", 0, i);
      }
    }
  }

84 85 86
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
87 88 89 90 91
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
92 93 94
      // OneDNN uses blocking format, which cannot be always supported with
      // reorders, because if blocked dimension is not divisible by 8 or
      // 16(depending on which blocking format is used) submemory cannot be
J
jakpiase 已提交
95
      // created, so in that scenario a fallback is needed
96 97
      const auto x_md = ctx.Input<Tensor>("X")->mem_desc();
      if (x_md.data.format_desc.blocking.inner_nblks == 0)
98 99
        return framework::OpKernelType(input_data_type,
                                       ctx.GetPlace(),
J
jakpiase 已提交
100 101
                                       framework::DataLayout::kMKLDNN,
                                       framework::LibraryType::kMKLDNN);
102 103 104
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
105 106 107
  }

  framework::OpKernelType GetKernelTypeForVar(
108 109
      const std::string &var_name,
      const Tensor &tensor,
110 111 112 113
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "AxisTensor" || var_name == "SectionsTensorList") {
      return expected_kernel_type;
    }
114 115
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
116
  }
Y
Yancey 已提交
117 118 119 120
};

class SplitOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
121
  void Make() override {
122
    AddInput("X", "(Tensor) Input tensor of the split operator.");
123
    AddInput("AxisTensor",
T
tianshuo78520a 已提交
124
             "(Tensor) The axis which the input will be split on. "
125 126 127 128 129 130 131 132 133 134
             "It has higher priority than Attr(axis). "
             "The shape of AxisTensor must be [1]")
        .AsDispensable();
    AddInput("SectionsTensorList",
             "(vector<Tensor<int>>, optional). "
             "The length of each output along the specified axis. "
             "It has a higher priority than Attr(sections)."
             "The shape of the element in vector must be [1].")
        .AsDuplicable()
        .AsDispensable();
135 136
    AddOutput("Out", "(Tensor) Output tensors of the split operator.")
        .AsDuplicable();
Y
Yancey 已提交
137
    AddComment(R"DOC(
138 139 140 141 142 143 144 145 146 147 148 149 150
Split operator

This operator splits the input tensor into multiple sub-tensors.

Example:
  Input = [[1,2],
           [3,4],
           [5,6]]
  sections = [2,1]
  axis = 0
  Output[0] = [[1,2],
               [3,4]]
  Output[1] = [[5,6]]
Y
Yancey 已提交
151 152 153

    )DOC");
    AddAttr<std::vector<int>>("sections",
154 155 156
                              "(vector<int>) "
                              "the length of each output along the "
                              "specified axis.")
Y
Yancey 已提交
157 158
        .SetDefault(std::vector<int>{});
    AddAttr<int>("num",
159 160
                 "(int, default 0)"
                 "Number of sub-tensors. This must evenly divide "
Y
Yancey 已提交
161 162
                 "Input.dims()[axis]")
        .SetDefault(0);
163 164
    AddAttr<int>("axis",
                 "(int, default 0) "
T
tianshuo78520a 已提交
165
                 "The axis which the input will be split on.")
Y
Yancey 已提交
166
        .SetDefault(0);
167 168 169 170 171 172 173 174
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
        .SetDefault(false);
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
        .InEnum({"float32", "bfloat16"});
Y
Yancey 已提交
175 176 177 178 179 180 181
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
182

183 184 185
REGISTER_OPERATOR(split,
                  ops::SplitOp,
                  ops::SplitOpMaker,
H
hong 已提交
186
                  ops::SplitGradMaker<paddle::framework::OpDesc>,
187
                  ops::SplitGradMaker<paddle::imperative::OpBase>);