unique_op.cc 5.7 KB
Newer Older
Z
zhoukunsheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Copyright (c) 2019 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. */

#include "paddle/fluid/operators/unique_op.h"

namespace paddle {
namespace operators {

class UniqueOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
25 26
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "unique");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "unique");
Z
zhoukunsheng 已提交
27
    auto in_dims = ctx->GetInputDim("X");
Z
Zhang Ting 已提交
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
    if (!ctx->Attrs().Get<bool>("is_sorted")) {
      OP_INOUT_CHECK(ctx->HasOutput("Index"), "Output", "Index", "unique");
      PADDLE_ENFORCE_EQ(in_dims.size(), 1,
                        platform::errors::InvalidArgument(
                            "The Input(X) should be 1-D Tensor, "
                            "But now the dims of Input(X) is %d.",
                            in_dims.size()));

      ctx->SetOutputDim("Out", {-1});
      ctx->SetOutputDim("Index", in_dims);
      return;
    }

    bool return_index = ctx->Attrs().Get<bool>("return_index");
    bool return_inverse = ctx->Attrs().Get<bool>("return_inverse");
    bool return_counts = ctx->Attrs().Get<bool>("return_counts");
    auto axis_vec = ctx->Attrs().Get<std::vector<int>>("axis");

    if (return_index) {
      OP_INOUT_CHECK(ctx->HasOutput("Indices"), "Output", "Indices", "unique");
    }
    if (return_inverse) {
      OP_INOUT_CHECK(ctx->HasOutput("Index"), "Output", "Index", "unique");
    }
    if (return_counts) {
      OP_INOUT_CHECK(ctx->HasOutput("Counts"), "Output", "Counts", "unique");
    }
Z
zhoukunsheng 已提交
55

Z
Zhang Ting 已提交
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
    if (axis_vec.empty()) {
      ctx->SetOutputDim("Out", {-1});
      if (return_inverse) {
        ctx->SetOutputDim("Index", {framework::product(in_dims)});
      }
    } else {
      int axis = axis_vec[0];
      if (axis < 0) {
        axis += in_dims.size();
      }
      PADDLE_ENFORCE_LT(
          axis, in_dims.size(),
          platform::errors::InvalidArgument("The axis(%d) should be less than "
                                            "the dimension size(%d) of x.",
                                            axis, in_dims.size()));
      auto out_dims = in_dims;
      out_dims[axis] = -1;
      ctx->SetOutputDim("Out", out_dims);
      if (return_inverse) {
        ctx->SetOutputDim("Index", {in_dims[axis]});
      }
    }
    if (return_index) {
      ctx->SetOutputDim("Indices", {-1});
    }
    if (return_counts) {
      ctx->SetOutputDim("Counts", {-1});
    }
Z
zhoukunsheng 已提交
84
  }
85 86 87 88 89 90 91 92

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        platform::CPUPlace());
  }
Z
zhoukunsheng 已提交
93 94 95 96 97
};

class UniqueOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
Z
Zhang Ting 已提交
98 99 100
    AddInput("X",
             "Input tensor. It should be a 1-D tensor when Attr(is_sorted)"
             " is fasle or a N-D tensor when Attr(is_sorted) is true.");
Z
zhoukunsheng 已提交
101 102 103
    AddAttr<int>("dtype", "data type for output index");
    AddOutput("Out", "A unique subsequence for input tensor.");
    AddOutput("Index",
Z
Zhang Ting 已提交
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
              "Equivalent to inverse in numpy.unique, "
              "the indices for where elements in the original input ended up "
              "in the returned unique tensor.");
    AddOutput(
        "Indices",
        "The indices of the input tensor that result in the unique tensor.")
        .AsDispensable();
    AddOutput("Counts", "The counts for each unique element.").AsDispensable();
    AddAttr<bool>("return_index",
                  "If True, also return the indices of the input"
                  " tensor that result in the unique Tensor.")
        .SetDefault(false);
    AddAttr<bool>(
        "return_inverse",
        "If True, also return the indices for where elements"
        " in the original input ended up in the returned unique tensor.")
        .SetDefault(false);
    AddAttr<bool>("return_counts",
                  "If True, also return the counts for each unique element.")
        .SetDefault(false);
    AddAttr<std::vector<int>>(
        "axis",
        "The axis to apply unique. If None, the input will be flattened.")
        .SetDefault({});
    AddAttr<bool>("is_sorted",
                  "If True, the unique elements of X are in ascending order."
                  "Otherwise, the unique elements are not sorted.")
        .SetDefault(false);
Z
zhoukunsheng 已提交
132
    AddComment(R"DOC(
Z
Zhang Ting 已提交
133 134 135 136 137 138
    1. Return a unique subsequence for 1-D input tensor, and an index tensor
    pointing to this unique subsequence when Attr(is_sorted) is false. This 
    means paddle.unique is called.
    
    2. Returns the unique elements of X in ascending order when Attr(is_sorted)
    is true. This means fluid.layers.unique is called.
Z
zhoukunsheng 已提交
139 140 141 142 143 144 145 146
)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(unique, ops::UniqueOp, ops::UniqueOpMaker);
Z
Zhang Ting 已提交
147 148 149 150 151
REGISTER_OP_CPU_KERNEL(
    unique, ops::UniqueKernel<paddle::platform::CPUDeviceContext, float>,
    ops::UniqueKernel<paddle::platform::CPUDeviceContext, double>,
    ops::UniqueKernel<paddle::platform::CPUDeviceContext, int32_t>,
    ops::UniqueKernel<paddle::platform::CPUDeviceContext, int64_t>);