reduce.h 9.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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
16 17 18

#include <set>

19
#include "paddle/phi/backends/cpu/cpu_context.h"
20
#include "paddle/phi/core/visit_type.h"
21 22 23 24 25 26
#include "paddle/phi/kernels/cast_kernel.h"

#include "paddle/phi/api/lib/utils/storage.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/math_function.h"
27 28
// See Note [ Why still include the fluid headers? ]
#include "paddle/fluid/operators/eigen/eigen_function.h"
29
namespace phi {
30

31 32 33 34 35 36
template <typename DeviceContext,
          typename T,
          size_t D,
          size_t R_D,
          typename Functor>
void ReduceFunctor(const DeviceContext& context,
37 38
                   const phi::DenseTensor& input,
                   phi::DenseTensor* output,
39 40 41 42 43 44 45 46 47 48 49 50 51 52
                   const std::vector<int64_t>& dims,
                   bool keep_dim) {
  auto x = EigenTensor<T, D>::From(input);
  auto x_rank = static_cast<int>(x.dimensions().size());
  auto reduce_dim = Eigen::array<int, R_D>();
  std::vector<int64_t> dims_ref = dims;
  for (size_t i = 0; i < dims_ref.size(); ++i) {
    if (dims_ref[i] < 0) dims_ref[i] = x_rank + dims_ref[i];
    reduce_dim[i] = dims_ref[i];
  }
  // construct the squeezed output tensor
  DDim out_dims = output->dims();
  if (keep_dim && x_rank > 1) {
    const int kDelFlag = -2;
53
    auto dims_vector = phi::vectorize(out_dims);
54 55 56 57 58
    for (size_t i = 0; i < dims_ref.size(); ++i) {
      dims_vector[dims_ref[i]] = kDelFlag;
    }
    dims_vector.erase(remove(dims_vector.begin(), dims_vector.end(), kDelFlag),
                      dims_vector.end());
59
    out_dims = phi::make_ddim(dims_vector);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  }
  auto& place = *context.eigen_device();
  Functor functor;

  if (D == 1) {
    auto out = EigenScalar<T>::From(*output);
    functor(place, &x, &out, reduce_dim);
  } else {
    auto out = EigenTensor<T, (D - R_D)>::From(*output, out_dims);
    functor(place, &x, &out, reduce_dim);
  }
}

#define HANDLE_REDUCE_DIM(NDIM, RDIM)                        \
  if (ndim == NDIM && rdim == RDIM) {                        \
    ReduceFunctor<DeviceContext, OutT, NDIM, RDIM, Functor>( \
        dev_ctx, input, output, dims, keep_dim);             \
  }
//////////////// HandleLargeDim

inline void GetShuffledDim(const DDim& src_dims,
                           DDim* dst_dims,
                           const std::vector<int64_t>& reduced_dims,
83
                           std::vector<int>* perm_axis) {
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  // check if it's a reduced dim
  std::vector<bool> src_dims_check(src_dims.size(), false);
  size_t src_size = src_dims.size();
  size_t reduce_size = reduced_dims.size();
  std::vector<int64_t> regular_reduced_dims = reduced_dims;
  for (size_t i = 0; i < regular_reduced_dims.size(); i++) {
    if (regular_reduced_dims[i] < 0) {
      regular_reduced_dims[i] = src_size + regular_reduced_dims[i];
    }
  }

  for (size_t i = 0; i < reduce_size; ++i) {
    dst_dims->at(src_size - reduce_size + i) =
        src_dims[regular_reduced_dims[i]];
    (*perm_axis)[src_size - reduce_size + i] = regular_reduced_dims[i];
    src_dims_check[regular_reduced_dims[i]] = true;
  }

  size_t offset = 0;
  for (size_t i = 0; i < src_dims_check.size(); ++i) {
    bool is_reduced = src_dims_check[i];
    if (!is_reduced) {
      (*perm_axis)[offset] = i;
      dst_dims->at(offset++) = src_dims[i];
    }
  }
}

template <typename DeviceContext, typename OutT>
void GetShuffledInput(const DeviceContext& dev_ctx,
114 115
                      const phi::DenseTensor& input,
                      phi::DenseTensor* shuffled_input,
116 117
                      const std::vector<int64_t>& dims) {
  DDim shuffled_dims(input.dims());
118
  std::vector<int> perm_axis(input.dims().size());
119 120
  GetShuffledDim(input.dims(), &shuffled_dims, dims, &perm_axis);

121
  shuffled_input->ResizeAndAllocate(shuffled_dims);
122
  dev_ctx.template Alloc<OutT>(shuffled_input);
123

124
  phi::funcs::TransposeNormal<DeviceContext, OutT> trans;
125 126 127 128 129
  trans(dev_ctx, input, shuffled_input, perm_axis);
}

template <typename DeviceContext, typename OutT, typename Functor>
void HandleLargeDim(const DeviceContext& dev_ctx,
130 131
                    const phi::DenseTensor& input,
                    phi::DenseTensor* output,
132 133 134
                    const std::vector<int64_t>& dims,
                    bool keep_dim) {
  //  shuffle the reduced dim to the end
135 136
  phi::DenseTensor shuffled_input = phi::DenseTensor(
      phi::make_intrusive<paddle::experimental::SharedStorage>(input.place()),
137 138 139 140 141 142 143
      input.meta());

  GetShuffledInput<DeviceContext, OutT>(dev_ctx, input, &shuffled_input, dims);

  // transpose to 2D tensor whose shape is {unreduced, reduced}.
  const int64_t unreduced = output->numel();
  const int64_t reduced = shuffled_input.numel() / unreduced;
144
  shuffled_input.ResizeAndAllocate({unreduced, reduced});
145
  DDim output_dim = output->dims();
146
  output->ResizeAndAllocate({unreduced});
147 148
  ReduceFunctor<DeviceContext, OutT, 2, 1, Functor>(
      dev_ctx, shuffled_input, output, {1}, keep_dim);
149
  output->ResizeAndAllocate(output_dim);
150 151 152 153 154 155
}

////////////// ReduceKernel

template <typename DeviceContext, typename T, typename OutT, typename Functor>
void ReduceKernelImpl(const DeviceContext& dev_ctx,
156 157
                      const phi::DenseTensor& input,
                      phi::DenseTensor* output,
158 159 160
                      const std::vector<int64_t>& dims,
                      bool keep_dim,
                      bool reduce_all) {
161
  dev_ctx.template Alloc<OutT>(output);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

  if (reduce_all) {
    // Flatten and reduce 1-D tensor
    auto x = EigenVector<OutT>::Flatten(input);
    auto out = EigenScalar<OutT>::From(*output);
    auto& dev = *dev_ctx.eigen_device();
    auto reduce_dim = Eigen::array<int, 1>({{0}});

    Functor functor;
    functor(dev, &x, &out, reduce_dim);
  } else {
    int ndim = input.dims().size();
    int rdim = dims.size();
    if (ndim > 6) {
      HandleLargeDim<DeviceContext, OutT, Functor>(
          dev_ctx, input, output, dims, keep_dim);

    } else {
      HANDLE_REDUCE_DIM(6, 5);
      HANDLE_REDUCE_DIM(6, 4);
      HANDLE_REDUCE_DIM(6, 3);
      HANDLE_REDUCE_DIM(6, 2);
      HANDLE_REDUCE_DIM(6, 1);
      HANDLE_REDUCE_DIM(5, 4);
      HANDLE_REDUCE_DIM(5, 3);
      HANDLE_REDUCE_DIM(5, 2);
      HANDLE_REDUCE_DIM(5, 1);
      HANDLE_REDUCE_DIM(4, 3);
      HANDLE_REDUCE_DIM(4, 2);
      HANDLE_REDUCE_DIM(4, 1);
      HANDLE_REDUCE_DIM(3, 2);
      HANDLE_REDUCE_DIM(3, 1);
      HANDLE_REDUCE_DIM(2, 1);
      HANDLE_REDUCE_DIM(1, 1);
    }
  }
}

200 201 202 203 204 205 206 207 208
template <typename DeviceContext, typename T, typename Functor>
void Reduce(const DeviceContext& dev_ctx,
            const DenseTensor& x,
            bool reduce_all,
            const std::vector<int64_t>& dims,
            bool keep_dim,
            DataType out_dtype,
            DenseTensor* out) {
  // If the dims has full dim, set the reduce_all is True
209
  const int& input_dim_size = x.dims().size();
210 211
  std::set<int> dims_set(dims.begin(), dims.end());
  bool full_dim = true;
212 213 214
  for (int i = 0; i < input_dim_size; ++i) {
    if (dims_set.find(i) == dims_set.end() &&
        dims_set.find(i - input_dim_size) == dims_set.end()) {
215 216 217 218 219 220 221
      full_dim = false;
      break;
    }
  }
  reduce_all = (reduce_all || full_dim);

  // no need to cast dtype
222
  if (out_dtype == phi::DataType::UNDEFINED || out_dtype == x.dtype()) {
223 224
    // do reduce sum
    PD_VISIT_ALL_TYPES(
225
        x.dtype(), "ReduceKernelImpl", ([&] {
226
          phi::ReduceKernelImpl<DeviceContext, T, data_t, Functor>(
227 228 229
              dev_ctx, x, out, dims, keep_dim, reduce_all);
        }));
  } else {
230
    // cast x tensor to out_dtype
231
    auto tmp_tensor = phi::Cast<T, DeviceContext>(dev_ctx, x, out_dtype);
232 233 234 235

    // do reduce sum
    PD_VISIT_ALL_TYPES(
        out_dtype, "ReduceKernelImpl", ([&] {
236
          phi::ReduceKernelImpl<DeviceContext, T, data_t, Functor>(
237 238 239 240 241
              dev_ctx, tmp_tensor, out, dims, keep_dim, reduce_all);
        }));
  }
}

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
template <typename DeviceContext, typename OutT, typename Functor>
void BoolReduceKernel(const DeviceContext& dev_ctx,
                      const phi::DenseTensor& input,
                      const std::vector<int64_t>& dims,
                      bool keep_dim,
                      bool reduce_all,
                      phi::DenseTensor* output) {
  dev_ctx.template Alloc<OutT>(output);

  // The dims has full dim, set the reduce_all is True
  const auto& input_dim_size = input.dims().size();
  std::set<int> dims_set(dims.begin(), dims.end());
  bool full_dim = true;
  for (auto i = 0; i < input_dim_size; i++) {
    if (dims_set.find(i) == dims_set.end()) {
      full_dim = false;
      break;
    }
  }
  reduce_all = (reduce_all || full_dim);

  ReduceKernelImpl<DeviceContext, bool, OutT, Functor>(
      dev_ctx, input, output, dims, keep_dim, reduce_all);
}

267
}  // namespace phi