split_op.h 6.3 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 15 16

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. */

#pragma once

17
#include <chrono>  // NOLINT
18 19
#include <memory>
#include <string>
Y
Yancey 已提交
20
#include <vector>
Y
Yi Wang 已提交
21
#include "paddle/fluid/framework/op_registry.h"
C
chengduo 已提交
22
#include "paddle/fluid/operators/math/concat_and_split.h"
Y
Yi Wang 已提交
23
#include "paddle/fluid/operators/strided_memcpy.h"
24
#include "paddle/fluid/operators/utils.h"
Y
Yancey 已提交
25 26 27

namespace paddle {
namespace operators {
28 29 30 31 32 33 34 35
static inline std::vector<framework::DDim> UpdateOutsDims(
    const bool is_runtime, const bool each_section_is_known,
    const framework::DDim in_dims, const size_t num, std::vector<int> sections,
    const size_t axis, const int outs_number) {
  std::vector<framework::DDim> outs_dims(outs_number, in_dims);
  int64_t input_axis_dim = in_dims[axis];
  if (num > 0) {
    if (is_runtime || input_axis_dim > 0) {
T
Thunderbrook 已提交
36 37 38 39 40 41 42 43
      PADDLE_ENFORCE_EQ(
          input_axis_dim % num, 0,
          platform::errors::InvalidArgument(
              "The input's size along the split dimension "
              "must be evenly divisible by Attr(num_or_sections). "
              "But received Attr(num_or_sections) "
              "= %d, input(X)'s shape = [%s], Attr(dim) = %d.",
              num, in_dims, axis));
44
      size_t out_axis_dim = input_axis_dim / num;
Y
Yancey 已提交
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
      for (auto& out_dim : outs_dims) {
        out_dim[axis] = out_axis_dim;
      }
    } else {
      for (auto& out_dim : outs_dims) {
        out_dim[axis] = -1;
      }
    }
  } else if (sections.size() > 0) {
    if (is_runtime || input_axis_dim > 0) {
      const int unk_dim_val = -1;
      int unk_dim_idx = -1, num_of_unk = 0;
      int sum_of_section = 0;
      for (size_t i = 0; i < sections.size(); ++i) {
        if (sections[i] == unk_dim_val) {
          num_of_unk++;
          unk_dim_idx = i;
        } else {
          sum_of_section += sections[i];
        }
      }

      if (each_section_is_known) {
T
Thunderbrook 已提交
69 70 71 72 73 74 75
        PADDLE_ENFORCE_LE(
            num_of_unk, 1,
            platform::errors::InvalidArgument(
                "Only one dimension value of Attr(num_or_sections) "
                "in SplitOp can be -1. "
                "But received Attr(num_or_sections) = [%s].",
                framework::make_ddim(sections)));
76 77 78 79 80 81 82 83
      }

      if (unk_dim_idx != -1) {
        // for example, input shape = [4 ,5], axis = 1, sections = [2, 3, -1].
        // input_axis_dim = 5, sum_of_sections = 5.
        // the following check will fail.
        PADDLE_ENFORCE_LT(
            sum_of_section, input_axis_dim,
T
Thunderbrook 已提交
84 85 86 87 88 89 90
            platform::errors::InvalidArgument(
                "Sum of Attr(num_or_sections) other than unknown section "
                "must be less than the input's "
                "size "
                "along the split dimension. But received Attr(num_or_sections) "
                "= [%s], input(X)'s shape = [%s], Attr(dim) = %d.",
                framework::make_ddim(sections), in_dims, axis));
91 92 93 94 95 96
        if (each_section_is_known) {
          sections[unk_dim_idx] = input_axis_dim - sum_of_section;
        }
      } else {
        PADDLE_ENFORCE_EQ(
            sum_of_section, input_axis_dim,
T
Thunderbrook 已提交
97 98 99 100 101 102
            platform::errors::InvalidArgument(
                "Sum of Attr(num_or_sections) must be equal to the input's "
                "size "
                "along the split dimension. But received Attr(num_or_sections)"
                " = [%s], input(X)'s shape = [%s], Attr(dim) = %d.",
                framework::make_ddim(sections), in_dims, axis));
103 104
      }
    }
105
    for (int i = 0; i < outs_number; ++i) {
106 107 108 109 110
      outs_dims[i][axis] = sections[i];
    }
  }
  return outs_dims;
}
Q
QI JUN 已提交
111
template <typename DeviceContext, typename T>
112
class SplitOpKernel : public framework::OpKernel<T> {
Y
Yancey 已提交
113 114 115 116
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<framework::Tensor>("X");
    auto outs = ctx.MultiOutput<framework::Tensor>("Out");
117 118
    int num = ctx.Attr<int>("num");
    std::vector<int> sections = ctx.Attr<std::vector<int>>("sections");
C
chengduo 已提交
119
    int axis = ctx.Attr<int>("axis");
120 121 122 123 124 125 126

    auto in_dims = in->dims();
    auto outs_number = outs.size();

    bool need_resize_outs_dims = false;
    if (ctx.HasInput("AxisTensor")) {
      auto* axis_tensor = ctx.Input<framework::Tensor>("AxisTensor");
127
      axis = GetDataFromTensor(axis_tensor)[0];
128 129 130 131 132
      need_resize_outs_dims = true;
    }
    auto sections_tensor_list =
        ctx.MultiInput<framework::Tensor>("SectionsTensorList");
    if (sections_tensor_list.size() > 0) {
133
      sections = GetDataFromTensorList(sections_tensor_list);
134 135 136 137 138 139 140 141 142 143 144
      need_resize_outs_dims = true;
    }

    if (need_resize_outs_dims) {
      std::vector<framework::DDim> outs_dims =
          UpdateOutsDims(true, true, in_dims, num, sections, axis, outs_number);
      for (size_t j = 0; j < outs.size(); ++j) {
        outs[j]->Resize(outs_dims[j]);
      }
    }

C
chengduo 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157
    std::vector<const framework::Tensor*> shape_refer;
    for (size_t j = 0; j < outs.size(); ++j) {
      outs[j]->mutable_data<T>(ctx.GetPlace());
      shape_refer.emplace_back(outs[j]);
    }

    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    // Sometimes direct copies will be faster, this maybe need deeply analysis.
    if (axis == 0 && outs.size() < 10) {
      StridedMemcpyWithAxis0<T>(dev_ctx, *in, shape_refer, &outs);
    } else {
      math::SplitFunctor<DeviceContext, T> functor;
      functor(dev_ctx, *in, shape_refer, axis, &outs);
Y
Yancey 已提交
158 159 160 161
    }
  }
};

H
hong 已提交
162 163
template <typename T>
class SplitGradMaker : public framework::SingleGradOpMaker<T> {
T
typhoonzero 已提交
164
 public:
H
hong 已提交
165
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
T
typhoonzero 已提交
166 167

 protected:
168
  void Apply(GradOpPtr<T> op) const override {
T
typhoonzero 已提交
169
    op->SetType("concat");
H
hong 已提交
170
    op->SetInput("X", this->OutputGrad("Out"));
H
hong 已提交
171 172 173
    if (this->HasInput("AxisTensor")) {
      op->SetInput("AxisTensor", this->Input("AxisTensor"));
    }
H
hong 已提交
174 175
    op->SetOutput("Out", this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
T
typhoonzero 已提交
176 177 178
  }
};

Y
Yancey 已提交
179 180
}  // namespace operators
}  // namespace paddle