reduce.h 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2021 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
// CUDA and HIP use same api
18 19
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) || \
    defined(PADDLE_WITH_XPU_KP)
20

21
#include "paddle/phi/core/visit_type.h"
22
#include "paddle/phi/kernels/funcs/reduce_function.h"
23

24
namespace phi {
25 26 27 28

template <typename T,
          template <typename> class ReduceOp,
          template <typename, typename> class TransformOp>
N
niuliling123 已提交
29
void Reduce(const KPDevice& dev_ctx,
30 31 32 33 34
            const DenseTensor& x,
            bool reduce_all,
            const std::vector<int64_t>& dims,
            bool keep_dim,
            DataType out_dtype,
35 36
            DenseTensor* out,
            bool is_mean = false) {
37
  std::vector<int> reduce_dims =
38
      phi::funcs::details::GetReduceDim(dims, x.dims().size(), reduce_all);
39 40 41 42 43 44

  int reduce_num = 1;
  for (auto i : reduce_dims) {
    reduce_num *= (x.dims())[i];
  }

45 46
  if (out_dtype != phi::DataType::UNDEFINED && out_dtype != x.dtype()) {
    auto tmp_tensor = phi::Cast<T>(dev_ctx, x, out_dtype);
47
    PD_VISIT_BOOL_AND_FLOATING_AND_COMPLEX_AND_3_TYPES(
48 49 50
        phi::DataType::INT32,
        phi::DataType::INT64,
        phi::DataType::FLOAT16,
51
        out_dtype,
52
        "ReduceKernel",
53 54
        ([&] {
          using MPType = typename kps::details::MPTypeTrait<data_t>::Type;
55 56 57 58
          phi::funcs::ReduceKernel<data_t,
                                   data_t,
                                   ReduceOp,
                                   TransformOp<data_t, MPType>>(
W
Wilber 已提交
59
              dev_ctx,
60
              tmp_tensor,
W
Wilber 已提交
61
              out,
62
              TransformOp<data_t, MPType>(reduce_num),
63 64
              reduce_dims,
              is_mean);
65 66 67
        }));
  } else {
    using MPType = typename kps::details::MPTypeTrait<T>::Type;
68
    phi::funcs::ReduceKernel<T, T, ReduceOp, TransformOp<T, MPType>>(
69 70 71 72 73 74
        dev_ctx,
        x,
        out,
        TransformOp<T, MPType>(reduce_num),
        reduce_dims,
        is_mean);
75 76
  }
}
77
}  // namespace phi
78 79

#endif