split_kernel.h 2.2 KB
Newer Older
C
chentianyu03 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/phi/core/dense_tensor.h"
C
chentianyu03 已提交
18

19
#include "paddle/phi/common/int_array.h"
20 21 22
#include "paddle/phi/common/scalar.h"
#include "paddle/phi/infermeta/unary.h"
#include "paddle/phi/kernels/empty_kernel.h"
C
chentianyu03 已提交
23

24
namespace phi {
C
chentianyu03 已提交
25 26 27 28

template <typename T, typename Context>
void SplitKernel(const Context& dev_ctx,
                 const DenseTensor& x,
29
                 const IntArray& num_or_sections,
C
chentianyu03 已提交
30 31 32 33 34 35
                 const Scalar& axis,
                 std::vector<DenseTensor*> out);

template <typename T, typename Context>
std::vector<DenseTensor> Split(const Context& dev_ctx,
                               const DenseTensor& x,
36
                               const IntArray& num_or_sections,
C
chentianyu03 已提交
37 38 39 40 41 42 43 44 45
                               const Scalar& axis) {
  size_t out_number;
  if (num_or_sections.GetData().size() == 1) {
    out_number = num_or_sections.GetData()[0];
  } else {
    out_number = num_or_sections.GetData().size();
  }

  std::vector<MetaTensor> out_meta;
46
  std::vector<MetaTensor*> out_meta_ptr;
C
chentianyu03 已提交
47
  out_meta.reserve(out_number);
48
  out_meta_ptr.reserve(out_number);
C
chentianyu03 已提交
49 50 51 52
  std::vector<DenseTensor> result;
  result.reserve(out_number);

  for (size_t i = 0; i < out_number; ++i) {
53
    result.emplace_back(DenseTensor());
54 55
    out_meta.emplace_back(&result.back());
    out_meta_ptr.push_back(&out_meta.back());
C
chentianyu03 已提交
56
  }
57
  SplitInferMeta(x, num_or_sections, axis, out_meta_ptr);
C
chentianyu03 已提交
58 59 60 61 62 63 64 65 66 67 68 69

  std::vector<DenseTensor*> outs;
  outs.reserve(out_meta.size());
  for (size_t i = 0; i < out_meta.size(); ++i) {
    outs.push_back(&result[i]);
  }

  SplitKernel<T, Context>(dev_ctx, x, num_or_sections, axis, outs);

  return result;
}

70
}  // namespace phi