reduce.h 2.3 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 33 34
            const DenseTensor& x,
            bool reduce_all,
            const std::vector<int64_t>& dims,
            bool keep_dim,
            DataType out_dtype,
            DenseTensor* out) {
  std::vector<int> reduce_dims =
35
      phi::funcs::details::GetReduceDim(dims, x.dims().size(), reduce_all);
36 37 38 39 40 41

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

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

#endif