reduce.h 2.4 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 18 19
// CUDA and HIP use same api
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)

20
#include "paddle/phi/kernels/funcs/reduce_function.h"
21

22
namespace phi {
23 24 25 26

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

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

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

#endif