split_op.h 6.2 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 36 37 38 39 40 41 42
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) {
      PADDLE_ENFORCE_EQ(input_axis_dim % num, 0,
                        "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);
      size_t out_axis_dim = input_axis_dim / num;
Y
Yancey 已提交
43

44 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
      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) {
        PADDLE_ENFORCE_LE(num_of_unk, 1,
                          "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));
      }

      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,
            "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);
        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,
            "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);
      }
    }
    for (size_t i = 0; i < outs_number; ++i) {
      outs_dims[i][axis] = sections[i];
    }
  }
  return outs_dims;
}
Q
QI JUN 已提交
103
template <typename DeviceContext, typename T>
104
class SplitOpKernel : public framework::OpKernel<T> {
Y
Yancey 已提交
105 106 107 108
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<framework::Tensor>("X");
    auto outs = ctx.MultiOutput<framework::Tensor>("Out");
109 110
    int num = ctx.Attr<int>("num");
    std::vector<int> sections = ctx.Attr<std::vector<int>>("sections");
C
chengduo 已提交
111
    int axis = ctx.Attr<int>("axis");
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    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");
      axis = GetDataFromTensor(axis_tensor)[0];
      need_resize_outs_dims = true;
    }
    auto sections_tensor_list =
        ctx.MultiInput<framework::Tensor>("SectionsTensorList");
    if (sections_tensor_list.size() > 0) {
      sections = GetDataFromTensorList(sections_tensor_list);
      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]);
      }
    }

Y
Yancey1989 已提交
137 138
    auto place = ctx.GetPlace();

C
chengduo 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151
    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 已提交
152 153 154 155
    }
  }
};

T
typhoonzero 已提交
156 157 158 159 160 161 162 163 164
class SplitGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto op = new framework::OpDesc();
    op->SetType("concat");
    op->SetInput("X", OutputGrad("Out"));
165
    op->SetInput("AxisTensor", Input("AxisTensor"));
T
typhoonzero 已提交
166 167 168 169 170 171
    op->SetOutput("Out", InputGrad("X"));
    op->SetAttrMap(Attrs());
    return std::unique_ptr<framework::OpDesc>(op);
  }
};

Y
Yancey 已提交
172 173
}  // namespace operators
}  // namespace paddle