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 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];
  }

N
niuliling123 已提交
42
  KPStream stream = dev_ctx.stream();
43

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

#endif