mode_op.h 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
/* 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
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/transpose_op.h"

namespace paddle {
namespace operators {

template <typename T, typename Type>
static void getMode(Type input_height, Type input_width, int input_dim,
                    const framework::Tensor* input, T* t_out, Type* t_indices) {
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
  for (Type i = 0; i < input_height; ++i) {
    std::vector<std::pair<T, Type>> col_vec;
    col_vec.reserve(input_width);
    if (input_dim == 1) {
      auto e_input = framework::EigenVector<T>::Flatten(*input);
      for (Type j = 0; j < input_width; ++j) {
        col_vec.emplace_back(std::pair<T, Type>(e_input(j), j));
      }
    } else {
      auto e_input = framework::EigenMatrix<T>::Reshape(*input, input_dim - 1);
      for (Type j = 0; j < input_width; ++j) {
        col_vec.emplace_back(std::pair<T, Type>(e_input(i, j), j));
      }
    }
    std::sort(col_vec.begin(), col_vec.end(),
              [](const std::pair<T, Type>& l, const std::pair<T, Type>& r) {
                return (!std::isnan(static_cast<double>(l.first)) &&
                        std::isnan(static_cast<double>(r.first))) ||
                       (l.first < r.first);
              });
    T mode = 0;
    int64_t indice = 0;
    int64_t cur_freq = 0;
    int64_t max_freq = 0;
    for (int64_t i = 0; i < input_width; ++i) {
      ++cur_freq;
      if (i == input_width - 1 || (col_vec[i + 1].first != col_vec[i].first)) {
        if (cur_freq > max_freq) {
          max_freq = cur_freq;
          mode = col_vec[i].first;
          indice = col_vec[i].second;
        }
        cur_freq = 0;
      }
    }
    t_out[i] = mode;
    t_indices[i] = indice;
  }
}

template <typename T, typename Type>
static void ModeAssign(const Type& input_height, const Type& input_width,
                       const int& input_dim, const framework::Tensor* input,
                       const framework::Tensor* indices, T* output_data) {
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
  for (Type i = 0; i < input_height; ++i) {
    if (input_dim == 1) {
      auto e_input = framework::EigenVector<T>::Flatten(*input);
      auto e_indices = framework::EigenVector<Type>::Flatten(*indices);
      output_data[i * input_width + e_indices(0)] = e_input(0);
    } else {
      auto e_input = framework::EigenMatrix<T>::Reshape(*input, input_dim - 1);
      auto e_indices =
          framework::EigenMatrix<Type>::Reshape(*indices, input_dim - 1);
      output_data[i * input_width + e_indices(i, 0)] = e_input(i, 0);
    }
  }
}

template <typename DeviceContext, typename T>
class ModeCPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* input = context.Input<framework::Tensor>("X");
    auto* output = context.Output<framework::Tensor>("Out");
    auto* indices = context.Output<framework::Tensor>("Indices");
    const auto& in_dims = input->dims();
    bool keepdim = static_cast<bool>(context.Attr<bool>("keepdim"));

    // axis < 0, cacluate the real axis
    int axis = static_cast<int>(context.Attr<int>("axis"));
    if (axis < 0) axis += in_dims.size();

    T* output_data = output->mutable_data<T>(context.GetPlace());
    int64_t* indices_data = indices->mutable_data<int64_t>(context.GetPlace());
    auto out_dims = output->dims();
    // if axis is not the last dim, transpose it to the last dim, do the
    // calculation,
    // then tranpose it back to orginal axis.
    if (axis == in_dims.size() - 1) {
      const int64_t& input_height = framework::product(
          framework::slice_ddim(in_dims, 0, in_dims.size() - 1));
      const int64_t& input_width = in_dims[in_dims.size() - 1];
      getMode<T, int64_t>(input_height, input_width, in_dims.size(), input,
                          output_data, indices_data);
    } else {
      std::vector<int> trans_axis;
      for (int i = 0; i < axis; i++) {
        trans_axis.emplace_back(i);
      }
      trans_axis.push_back(in_dims.size() - 1);
      for (int i = axis + 1; i < in_dims.size() - 1; i++) {
        trans_axis.emplace_back(i);
      }
      trans_axis.emplace_back(axis);

      if (!keepdim) {
        std::vector<int> tmp_out_shape;
        for (int i = 0; i < axis; i++) {
          tmp_out_shape.emplace_back(in_dims[i]);
        }
        tmp_out_shape.emplace_back(1);
        for (int i = axis + 1; i < in_dims.size(); i++) {
          tmp_out_shape.emplace_back(in_dims[i]);
        }
        framework::DDim tmp_out_dim = framework::make_ddim(tmp_out_shape);
        output->Resize(tmp_out_dim);
        indices->Resize(tmp_out_dim);
      }

      // get the trans input_dims, out_dims
      framework::DDim trans_shape(in_dims);
      framework::DDim trans_out_shape(in_dims);

      for (size_t i = 0; i < trans_axis.size(); i++) {
        trans_shape[i] = in_dims[trans_axis[i]];
        trans_out_shape[i] = in_dims[trans_axis[i]];
      }
      trans_out_shape[in_dims.size() - 1] = 1;

      framework::Tensor trans_input;
      trans_input.mutable_data<T>(trans_shape, context.GetPlace());
      int ndims = trans_axis.size();
      auto& dev_context =
          context.template device_context<platform::CPUDeviceContext>();

      // transpose the input value
      TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, *input,
                                                  &trans_input, trans_axis);

      const int64_t input_height = framework::product(
          framework::slice_ddim(trans_shape, 0, trans_shape.size() - 1));
      const int64_t input_width = trans_shape[trans_shape.size() - 1];
      framework::Tensor tmp_out;
      T* t_out = tmp_out.mutable_data<T>(trans_out_shape, context.GetPlace());
      framework::Tensor tmp_indices;
      auto* t_ind = tmp_indices.mutable_data<int64_t>(trans_out_shape,
                                                      context.GetPlace());

      getMode<T, int64_t>(input_height, input_width, in_dims.size(),
                          &trans_input, t_out, t_ind);
      // transpose back
      TransCompute<platform::CPUDeviceContext, int64_t>(
          ndims, dev_context, tmp_indices, indices, trans_axis);
      TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, tmp_out,
                                                  output, trans_axis);
      if (!keepdim) {
        output->Resize(out_dims);
        indices->Resize(out_dims);
      }
    }
  }
};

template <typename DeviceContext, typename T>
class ModeGradCPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* x = context.Input<framework::Tensor>("X");
    auto* out_grad =
        context.Input<framework::Tensor>(framework::GradVarName("Out"));
    auto* indices = context.Input<framework::Tensor>("Indices");
    auto* x_grad =
        context.Output<framework::Tensor>(framework::GradVarName("X"));
    int axis = static_cast<int>(context.Attr<int>("axis"));
    bool keepdim = static_cast<bool>(context.Attr<bool>("keepdim"));

    auto in_dims = x->dims();
    auto out_dims = indices->dims();

    // axis < 0, get the real axis
    axis = (axis < 0) ? (in_dims.size() + axis) : axis;

    if (!keepdim) {
      std::vector<int> tmp_out_shape;
      for (int i = 0; i < axis; i++) {
        tmp_out_shape.emplace_back(out_dims[i]);
      }
      tmp_out_shape.emplace_back(1);
      for (int i = axis + 1; i < in_dims.size(); i++) {
        tmp_out_shape.emplace_back(out_dims[i - 1]);
      }
      out_dims = framework::make_ddim(tmp_out_shape);
    }
    T* x_grad_data = x_grad->mutable_data<T>(context.GetPlace());
    if (axis == in_dims.size() - 1) {
      // allocate the memory for the input_grad
      // assign the out_grad to input_grad directly
      const int64_t input_height = framework::product(
          framework::slice_ddim(in_dims, 0, in_dims.size() - 1));
      const int64_t input_width = in_dims[in_dims.size() - 1];

      // init the output grad with 0, because some input elements has no grad
      memset(x_grad_data, 0, x_grad->numel() * sizeof(T));
      // Assign the output_grad to input_grad
      if (keepdim) {
        ModeAssign(input_height, input_width, in_dims.size(), out_grad, indices,
                   x_grad_data);
      } else {
        auto& dev_context =
            context.template device_context<platform::CPUDeviceContext>();
        framework::Tensor out_grad_tmp;
        framework::Tensor indices_tmp;
        out_grad_tmp.mutable_data<T>(out_grad->dims(), dev_context.GetPlace());
        indices_tmp.mutable_data<int64_t>(indices->dims(),
                                          dev_context.GetPlace());
        framework::TensorCopy(*out_grad, dev_context.GetPlace(), dev_context,
                              &out_grad_tmp);
        framework::TensorCopy(*indices, dev_context.GetPlace(), dev_context,
                              &indices_tmp);
        out_grad_tmp.Resize(out_dims);
        indices_tmp.Resize(out_dims);
        ModeAssign(input_height, input_width, in_dims.size(), &out_grad_tmp,
                   &indices_tmp, x_grad_data);
      }
    } else {
      // can not assign grad to input_grad, must do the transpose
      std::vector<int> trans_axis;
      for (int i = 0; i < axis; i++) {
        trans_axis.emplace_back(i);
      }
      trans_axis.emplace_back(out_dims.size() - 1);
      for (int i = axis + 1; i < out_dims.size() - 1; i++) {
        trans_axis.emplace_back(i);
      }
      trans_axis.emplace_back(axis);
      framework::DDim trans_shape(out_dims);
      framework::DDim trans_in_shape(in_dims);
      for (size_t i = 0; i < trans_axis.size(); i++) {
        trans_shape[i] = out_dims[trans_axis[i]];
        trans_in_shape[i] = in_dims[trans_axis[i]];
      }
      // transpose the out_grad, indices
      framework::Tensor trans_dO;
      trans_dO.mutable_data<T>(trans_shape, context.GetPlace());
      framework::Tensor trans_ind;
      trans_ind.mutable_data<int64_t>(trans_shape, context.GetPlace());
      int ndims = trans_axis.size();
      auto& dev_context =
          context.template device_context<platform::CPUDeviceContext>();

      if (keepdim) {
        // Do transpose
        TransCompute<platform::CPUDeviceContext, T>(
            ndims, dev_context, *out_grad, &trans_dO, trans_axis);
        TransCompute<platform::CPUDeviceContext, int64_t>(
            ndims, dev_context, *indices, &trans_ind, trans_axis);
      } else {
        framework::Tensor out_grad_tmp;
        framework::Tensor indices_tmp;
        out_grad_tmp.mutable_data<T>(out_grad->dims(), dev_context.GetPlace());
        indices_tmp.mutable_data<int64_t>(indices->dims(),
                                          dev_context.GetPlace());
        framework::TensorCopy(*out_grad, dev_context.GetPlace(), dev_context,
                              &out_grad_tmp);
        framework::TensorCopy(*indices, dev_context.GetPlace(), dev_context,
                              &indices_tmp);
        out_grad_tmp.Resize(out_dims);
        indices_tmp.Resize(out_dims);
        // Do transpose
        TransCompute<platform::CPUDeviceContext, T>(
            ndims, dev_context, out_grad_tmp, &trans_dO, trans_axis);
        TransCompute<platform::CPUDeviceContext, int64_t>(
            ndims, dev_context, indices_tmp, &trans_ind, trans_axis);
      }
      const int64_t input_height = framework::product(
          framework::slice_ddim(trans_in_shape, 0, trans_in_shape.size() - 1));
      const int64_t input_width = trans_in_shape[trans_in_shape.size() - 1];

      // Assign the out_grad to tranpose input_grad
      framework::Tensor tmp_out;
      T* t_out = tmp_out.mutable_data<T>(trans_in_shape, context.GetPlace());
      memset(t_out, 0, x_grad->numel() * sizeof(T));

      ModeAssign<T, int64_t>(input_height, input_width, in_dims.size(),
                             &trans_dO, &trans_ind, t_out);

      // Transpose back
      TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, tmp_out,
                                                  x_grad, trans_axis);
    }
  }
};

}  // namespace operators
}  // namespace paddle