split_op.cc 8.1 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
namespace paddle {
namespace operators {
C
Charles-hit 已提交
24
using framework::LoDTensor;
Y
Yancey 已提交
25
using framework::Tensor;
C
Charles-hit 已提交
26
using framework::Variable;
Y
Yancey 已提交
27 28 29 30 31

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

32
  void InferShape(framework::InferShapeContext *ctx) const override {
33 34
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"),
                      true,
35 36
                      platform::errors::InvalidArgument(
                          "Input(X) of SplitOp should not be null."));
37 38
    PADDLE_ENFORCE_GE(ctx->Outputs("Out").size(),
                      1UL,
39 40
                      platform::errors::InvalidArgument(
                          "Outputs(Out) of SplitOp should not be empty."));
C
Charles-hit 已提交
41 42
    int axis = static_cast<int>(ctx->Attrs().Get<int>("axis"));
    int num = static_cast<int>(ctx->Attrs().Get<int>("num"));
43 44
    std::vector<int> sections = static_cast<std::vector<int>>(
        ctx->Attrs().Get<std::vector<int>>("sections"));
C
Charles-hit 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    // Construct MetaTensor for InferMeta Func
    using CompatMetaTensor = framework::CompatMetaTensor;
    CompatMetaTensor x(ctx->GetInputVarPtrs("X")[0], ctx->IsRuntime());
    std::vector<CompatMetaTensor> out;
    size_t out_size = ctx->GetOutputVarPtrs("Out").size();
    out.reserve(out_size);
    for (size_t i = 0; i < out_size; i++) {
      out.emplace_back(
          CompatMetaTensor(ctx->GetOutputVarPtrs("Out")[i], ctx->IsRuntime()));
    }
    std::vector<phi::MetaTensor *> out_ptr(out_size);
    for (size_t i = 0; i < out_size; i++) {
      out_ptr[i] = &out[i];
    }
    phi::Scalar axis_final;
    phi::IntArray sections_final;
    // Construct axis_final
    if (ctx->IsRuntime() && ctx->HasInput("AxisTensor")) {
      Variable *var =
          PADDLE_GET_CONST(Variable *, ctx->GetInputVarPtrs("AxisTensor")[0]);
      axis_final = std::move(experimental::MakePhiScalarFromVar(*var));
    } else if (!ctx->IsRuntime() && ctx->HasInput("AxisTensor")) {
      axis_final = std::move(phi::Scalar(-1));
      axis_final.SetFromTensor(true);
    } else {
      axis_final = std::move(phi::Scalar(axis));
71 72
    }

C
Charles-hit 已提交
73 74 75 76 77 78 79 80 81 82 83 84
    // Construct sections_final
    if (ctx->IsRuntime() && ctx->HasInputs("SectionsTensorList")) {
      int sections_tensor_list_size =
          ctx->GetInputVarPtrs("SectionsTensorList").size();
      const paddle::small_vector<framework::InferShapeVarPtr,
                                 phi::kInputSmallVectorSize>
          &sections_varptr_list = ctx->GetInputVarPtrs("SectionsTensorList");
      std::vector<LoDTensor> sections_from_tensor;
      sections_from_tensor.reserve(sections_tensor_list_size);
      for (const auto &section_varptr : sections_varptr_list) {
        Variable *var = PADDLE_GET_CONST(Variable *, section_varptr);
        sections_from_tensor.emplace_back(var->Get<LoDTensor>());
85
      }
C
Charles-hit 已提交
86 87 88 89 90 91 92
      sections_final = std::move(phi::IntArray(sections_from_tensor));
    } else if (!ctx->IsRuntime() && ctx->HasInputs("SectionsTensorList")) {
      sections_final = std::move(phi::IntArray(std::vector<int>(
          ctx->GetInputVarPtrs("SectionsTensorList").size(), -1)));
      sections_final.SetFromTensor(true);
    } else {
      sections_final = std::move(phi::IntArray(sections));
93
    }
C
Charles-hit 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106
    if (sections.size() > 0) {
      if (ctx->IsRuntime()) {
        phi::SplitInferMeta(
            x, sections_final, axis_final, out_ptr, {true, false});
      } else {
        phi::SplitInferMeta(
            x, sections_final, axis_final, out_ptr, {false, false});
      }
    } else {
      if (ctx->IsRuntime()) {
        phi::SplitWithNumInferMeta(x, num, axis_final, out_ptr, {true, false});
      } else {
        phi::SplitWithNumInferMeta(x, num, axis_final, out_ptr, {false, false});
107 108 109 110
      }
    }
  }

111 112 113
 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
114 115 116 117 118
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

#ifdef PADDLE_WITH_MKLDNN
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
119 120 121
      // 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 已提交
122
      // created, so in that scenario a fallback is needed
123 124
      const auto x_md = ctx.Input<Tensor>("X")->mem_desc();
      if (x_md.data.format_desc.blocking.inner_nblks == 0)
125 126
        return framework::OpKernelType(input_data_type,
                                       ctx.GetPlace(),
J
jakpiase 已提交
127 128
                                       framework::DataLayout::kMKLDNN,
                                       framework::LibraryType::kMKLDNN);
129 130 131
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
132 133 134
  }

  framework::OpKernelType GetKernelTypeForVar(
135 136
      const std::string &var_name,
      const Tensor &tensor,
137 138 139 140
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "AxisTensor" || var_name == "SectionsTensorList") {
      return expected_kernel_type;
    }
141 142
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
143
  }
Y
Yancey 已提交
144 145 146 147
};

class SplitOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
148
  void Make() override {
149
    AddInput("X", "(Tensor) Input tensor of the split operator.");
150
    AddInput("AxisTensor",
T
tianshuo78520a 已提交
151
             "(Tensor) The axis which the input will be split on. "
152 153 154 155 156 157 158 159 160 161
             "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();
162 163
    AddOutput("Out", "(Tensor) Output tensors of the split operator.")
        .AsDuplicable();
Y
Yancey 已提交
164
    AddComment(R"DOC(
165 166 167 168 169 170 171 172 173 174 175 176 177
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 已提交
178 179 180

    )DOC");
    AddAttr<std::vector<int>>("sections",
181 182 183
                              "(vector<int>) "
                              "the length of each output along the "
                              "specified axis.")
Y
Yancey 已提交
184 185
        .SetDefault(std::vector<int>{});
    AddAttr<int>("num",
186 187
                 "(int, default 0)"
                 "Number of sub-tensors. This must evenly divide "
Y
Yancey 已提交
188 189
                 "Input.dims()[axis]")
        .SetDefault(0);
190 191
    AddAttr<int>("axis",
                 "(int, default 0) "
T
tianshuo78520a 已提交
192
                 "The axis which the input will be split on.")
Y
Yancey 已提交
193
        .SetDefault(0);
194 195 196 197 198 199 200 201
    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 已提交
202 203 204 205 206 207 208
  }
};

}  // namespace operators
}  // namespace paddle

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

210 211 212
REGISTER_OPERATOR(split,
                  ops::SplitOp,
                  ops::SplitOpMaker,
H
hong 已提交
213
                  ops::SplitGradMaker<paddle::framework::OpDesc>,
214
                  ops::SplitGradMaker<paddle::imperative::OpBase>);