arg_min_max_op_base.h 5.7 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 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
Y
yuyang18 已提交
16
#include <string>
S
sneaxiy 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <type_traits>
#include <vector>
#include "paddle/fluid/framework/ddim.h"
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/string/printf.h"

namespace paddle {
namespace operators {

enum ArgMinMaxType { kArgMin, kArgMax };

template <typename DeviceContext, typename T, typename Tout, int64_t Rank,
          ArgMinMaxType argMinMaxValue>
struct ArgMinMaxFunctor {};

#define DECLARE_ARG_MIN_MAX_FUNCTOR(eigen_op_type, enum_argminmax_value)      \
  template <typename DeviceContext, typename T, typename Tout, int64_t Rank>  \
  struct ArgMinMaxFunctor<DeviceContext, T, Tout, Rank,                       \
                          enum_argminmax_value> {                             \
    void operator()(const DeviceContext& ctx, const framework::LoDTensor& in, \
Y
yuyang18 已提交
41
                    framework::LoDTensor* out, int64_t axis) {                \
S
sneaxiy 已提交
42
      auto in_eigen = framework::EigenTensor<T, Rank>::From(in);              \
Y
yuyang18 已提交
43
      auto out_eigen = framework::EigenTensor<Tout, Rank - 1>::From(*out);    \
S
sneaxiy 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
      out_eigen.device(*(ctx.eigen_device())) =                               \
          in_eigen.eigen_op_type(axis).template cast<Tout>();                 \
    }                                                                         \
  }

DECLARE_ARG_MIN_MAX_FUNCTOR(argmin, ArgMinMaxType::kArgMin);
DECLARE_ARG_MIN_MAX_FUNCTOR(argmax, ArgMinMaxType::kArgMax);

template <typename DeviceContext, typename T, typename Tout,
          ArgMinMaxType EnumArgMinMaxValue>
class ArgMinMaxKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& x = *(ctx.Input<framework::LoDTensor>("X"));
    auto& out = *(ctx.Output<framework::LoDTensor>("Out"));
    out.mutable_data<Tout>(ctx.GetPlace());
    auto axis = ctx.Attr<int64_t>("axis");
C
chengduo 已提交
61 62
    auto x_rank = x.dims().size();
    if (axis < 0) axis += x_rank;
S
sneaxiy 已提交
63 64 65 66 67
    auto& dev_ctx = ctx.template device_context<DeviceContext>();

#define CALL_ARG_MINMAX_FUNCTOR(rank)                                \
  ArgMinMaxFunctor<DeviceContext, T, Tout, rank, EnumArgMinMaxValue> \
      functor##rank;                                                 \
Y
yuyang18 已提交
68
  functor##rank(dev_ctx, x, &out, axis)
S
sneaxiy 已提交
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

    switch (x.dims().size()) {
      case 1:
        CALL_ARG_MINMAX_FUNCTOR(1);
        break;
      case 2:
        CALL_ARG_MINMAX_FUNCTOR(2);
        break;
      case 3:
        CALL_ARG_MINMAX_FUNCTOR(3);
        break;
      case 4:
        CALL_ARG_MINMAX_FUNCTOR(4);
        break;
      case 5:
        CALL_ARG_MINMAX_FUNCTOR(5);
        break;
      case 6:
        CALL_ARG_MINMAX_FUNCTOR(6);
        break;
      default:
        PADDLE_THROW(
            "%s operator doesn't supports tensors whose ranks are greater "
            "than 6.",
            (EnumArgMinMaxValue == kArgMin ? "argmin" : "argmax"));
        break;
Y
yuyang18 已提交
95
#undef CALL_ARG_MINMAX_FUNCTOR
S
sneaxiy 已提交
96 97 98 99
    }
  }
};

Y
yuyang18 已提交
100
template <typename DeviceContext, typename T>
S
sneaxiy 已提交
101
using ArgMinKernel =
Y
yuyang18 已提交
102
    ArgMinMaxKernel<DeviceContext, T, int64_t, ArgMinMaxType::kArgMin>;
S
sneaxiy 已提交
103

Y
yuyang18 已提交
104
template <typename DeviceContext, typename T>
S
sneaxiy 已提交
105
using ArgMaxKernel =
Y
yuyang18 已提交
106
    ArgMinMaxKernel<DeviceContext, T, int64_t, ArgMinMaxType::kArgMax>;
S
sneaxiy 已提交
107

Y
yuyang18 已提交
108
class ArgMinMaxOp : public framework::OperatorWithKernel {
S
sneaxiy 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
    PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null");
    const auto& x_dims = ctx->GetInputDim("X");
    int64_t axis = ctx->Attrs().Get<int64_t>("axis");
    PADDLE_ENFORCE(axis >= -x_dims.size() && axis < x_dims.size(),
                   "'axis' must be inside [-Rank(X), Rank(X))");

    auto x_rank = x_dims.size();
    if (axis < 0) axis += x_rank;

    std::vector<int64_t> vec;
    for (int64_t i = 0; i < axis; i++) vec.push_back(x_dims[i]);
    for (int64_t i = axis + 1; i < x_rank; i++) vec.push_back(x_dims[i]);
    ctx->SetOutputDim("Out", framework::make_ddim(vec));
  }
Y
yuyang18 已提交
128
};
S
sneaxiy 已提交
129 130 131 132 133 134 135 136 137 138 139

class BaseArgMinMaxOpMaker : public framework::OpProtoAndCheckerMaker {
 protected:
  virtual const char* OpName() const = 0;
  virtual const char* Name() const = 0;

 public:
  void Make() override {
    AddInput("X", "Input tensor.");
    AddOutput("Out", "Output tensor.");
    AddAttr<int64_t>("axis", "The axis in which to compute the arg indics.");
Y
yuyang18 已提交
140 141
    AddComment(string::Sprintf(R"DOC(
      %s Operator.
S
sneaxiy 已提交
142

Y
yuyang18 已提交
143 144
      Computes the indices of the %s elements of the input tensor's element
      along the provided axis.
S
sneaxiy 已提交
145
)DOC",
Y
yuyang18 已提交
146
                               OpName(), Name()));
S
sneaxiy 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  }
};

class ArgMinOpMaker : public BaseArgMinMaxOpMaker {
 protected:
  const char* OpName() const override { return "ArgMin"; }
  const char* Name() const override { return "min"; }
};

class ArgMaxOpMaker : public BaseArgMinMaxOpMaker {
 protected:
  const char* OpName() const override { return "ArgMax"; }
  const char* Name() const override { return "max"; }
};
}  // namespace operators
}  // namespace paddle