unique_op.h 16.2 KB
Newer Older
Z
zhoukunsheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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. */

#pragma once
Z
Zhang Ting 已提交
16
#include <algorithm>
Z
zhoukunsheng 已提交
17
#include <cmath>
Z
Zhang Ting 已提交
18 19
#include <numeric>
#include <set>
Z
zhoukunsheng 已提交
20 21 22
#include <unordered_map>
#include <utility>
#include <vector>
23

Z
zhoukunsheng 已提交
24
#include "paddle/fluid/framework/op_registry.h"
Z
Zhang Ting 已提交
25
#include "paddle/fluid/operators/math/concat_and_split.h"
26
#include "paddle/phi/kernels/funcs/math_function.h"
Z
zhoukunsheng 已提交
27 28 29 30 31 32

namespace paddle {
namespace operators {

template <typename InT>
struct UniqueOpFunctor {
33 34 35 36 37 38 39 40 41
  phi::DenseTensor* out_;
  phi::DenseTensor* index_;
  const phi::DenseTensor* in_;
  phi::DenseTensor* count_;

  UniqueOpFunctor(phi::DenseTensor* out,
                  phi::DenseTensor* index,
                  const phi::DenseTensor* in,
                  phi::DenseTensor* count = nullptr)
42
      : out_(out), index_(index), in_(in), count_(count) {}
Z
zhoukunsheng 已提交
43 44 45 46 47 48 49 50 51 52 53 54

  template <typename IndexT>
  void apply() const {
    auto* in_data = in_->data<InT>();
    auto* index_data = index_->mutable_data<IndexT>(platform::CPUPlace());

    int64_t j = 0;

    // TODO(fangzeyang): Should optimize performance here.
    std::unordered_map<InT, int64_t> dict;
    std::vector<InT> uniq;

55
    PADDLE_ENFORCE_LT(
56 57
        in_->numel(),
        pow(2, 31),
58 59 60 61
        platform::errors::InvalidArgument(
            "The num of Input(X) elements should be less then INT_MAX, "
            "but received num is %d.",
            in_->numel()));
Z
zhoukunsheng 已提交
62 63 64 65

    for (auto i = 0; i < in_->numel(); i++) {
      auto it = dict.find(in_data[i]);
      if (it == dict.end()) {
66 67
        dict.emplace(std::make_pair(in_data[i], j));
        uniq.emplace_back(in_data[i]);
Z
zhoukunsheng 已提交
68 69 70 71 72 73 74
        index_data[i] = static_cast<IndexT>(j);
        j++;
      } else {
        index_data[i] = static_cast<IndexT>(it->second);
      }
    }

75 76
    if (count_ != nullptr) {
      // Resize the count tensor dims to allocate the memory
77
      count_->Resize(phi::make_ddim({static_cast<int64_t>(uniq.size())}));
78 79 80 81
      IndexT* count_data = count_->mutable_data<IndexT>(platform::CPUPlace());
      // init count_data to 0
      memset(count_data, 0, uniq.size() * sizeof(IndexT));

82
      const auto& index_type = framework::TransToProtoVarType(index_->dtype());
83 84
      bool index_type_match = index_type == framework::proto::VarType::INT32 ||
                              index_type == framework::proto::VarType::INT64;
85 86
      PADDLE_ENFORCE_EQ(index_type_match,
                        true,
87 88 89 90 91 92 93 94
                        platform::errors::InvalidArgument(
                            "Index holds the wrong type, it holds %s, "
                            "but desires to be %s or %s",
                            paddle::framework::DataTypeToString(index_type),
                            paddle::framework::DataTypeToString(
                                framework::proto::VarType::INT32),
                            paddle::framework::DataTypeToString(
                                framework::proto::VarType::INT64)));
95 96 97 98 99 100 101 102 103 104 105 106 107 108

      if (index_type == framework::proto::VarType::INT32) {
        for (auto i = 0; i < in_->numel(); ++i) {
          const IndexT& index = index_data[i];
          count_data[static_cast<int32_t>(index)] += static_cast<IndexT>(1);
        }
      } else {
        for (auto i = 0; i < in_->numel(); ++i) {
          const IndexT& index = index_data[i];
          count_data[static_cast<int64_t>(index)] += static_cast<IndexT>(1);
        }
      }
    }

109
    out_->Resize(phi::make_ddim({static_cast<int64_t>(uniq.size())}));
Z
zhoukunsheng 已提交
110 111 112 113 114
    auto out_data = out_->mutable_data<InT>(platform::CPUPlace());
    std::memcpy(out_data, uniq.data(), uniq.size() * sizeof(InT));
  }
};

115
static std::vector<phi::DenseTensor> Unbind(const phi::DenseTensor& in) {
Z
Zhang Ting 已提交
116
  int64_t size = in.dims()[0];
117
  std::vector<phi::DenseTensor> tensors(size);
Z
Zhang Ting 已提交
118 119 120 121 122 123 124
  for (int64_t i = 0; i < size; ++i) {
    tensors[i] = in.Slice(i, i + 1);
  }
  return tensors;
}

template <typename T>
125
static bool Equal(const phi::DenseTensor& a, const phi::DenseTensor& b) {
Z
Zhang Ting 已提交
126 127 128 129 130 131 132 133 134 135 136
  if (a.numel() != b.numel()) {
    return false;
  }
  for (int64_t i = 0; i < a.numel(); ++i) {
    if (a.data<T>()[i] != b.data<T>()[i]) {
      return false;
    }
  }
  return true;
}

Z
Zhang Ting 已提交
137
template <typename InT, typename IndexT>
Z
Zhang Ting 已提交
138
static void UniqueFlattendTensor(const framework::ExecutionContext& context,
139 140
                                 const phi::DenseTensor& in,
                                 phi::DenseTensor* out,
141 142 143
                                 bool return_index,
                                 bool return_inverse,
                                 bool return_counts) {
Z
Zhang Ting 已提交
144 145
  const InT* in_data = in.data<InT>();
  std::set<InT> unique(in_data, in_data + in.numel());
146
  out->Resize(phi::make_ddim({static_cast<int64_t>(unique.size())}));
Z
Zhang Ting 已提交
147
  auto out_data = out->mutable_data<InT>(context.GetPlace());
Z
Zhang Ting 已提交
148 149 150
  std::copy(unique.begin(), unique.end(), out_data);

  if (return_index) {
151
    auto* indices = context.Output<phi::DenseTensor>("Indices");
152
    indices->Resize(phi::make_ddim({out->numel()}));
Z
Zhang Ting 已提交
153 154
    auto indices_data = indices->mutable_data<IndexT>(context.GetPlace());
    std::unordered_map<InT, IndexT> indices_map;
Z
Zhang Ting 已提交
155 156 157 158 159 160 161 162 163 164 165
    indices_map.reserve(out->numel());
    for (int64_t i = 0; i < in.numel(); ++i) {
      if (indices_map.find(in_data[i]) != indices_map.end()) continue;
      indices_map[in_data[i]] = i;
    }
    for (int64_t i = 0; i < out->numel(); ++i) {
      indices_data[i] = indices_map[out_data[i]];
    }
  }

  if (return_inverse) {
166
    auto* inverse = context.Output<phi::DenseTensor>("Index");
167
    inverse->Resize(phi::make_ddim({in.numel()}));
Z
Zhang Ting 已提交
168 169
    auto inverse_data = inverse->mutable_data<IndexT>(context.GetPlace());
    std::unordered_map<InT, IndexT> inverse_map;
Z
Zhang Ting 已提交
170 171 172 173 174 175 176 177 178 179
    inverse_map.reserve(out->numel());
    for (int64_t i = 0; i < out->numel(); ++i) {
      inverse_map[out_data[i]] = i;
    }
    for (int64_t i = 0; i < in.numel(); ++i) {
      inverse_data[i] = inverse_map[in_data[i]];
    }
  }

  if (return_counts) {
180
    auto* count = context.Output<phi::DenseTensor>("Counts");
181
    count->Resize(phi::make_ddim({out->numel()}));
Z
Zhang Ting 已提交
182 183
    auto count_data = count->mutable_data<IndexT>(context.GetPlace());
    std::unordered_map<InT, IndexT> counts_map;
Z
Zhang Ting 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196
    counts_map.reserve(out->numel());
    for (int64_t i = 0; i < out->numel(); ++i) {
      counts_map[out_data[i]] = 0;
    }
    for (int64_t i = 0; i < in.numel(); i++) {
      counts_map[in_data[i]] += 1;
    }
    for (int64_t i = 0; i < out->numel(); i++) {
      count_data[i] = counts_map[out_data[i]];
    }
  }
}

Z
Zhang Ting 已提交
197
template <class ForwardIt, typename InT, typename IndexT>
Z
Zhang Ting 已提交
198
static ForwardIt UniqueDimImpl(const framework::ExecutionContext& context,
199 200
                               ForwardIt first,
                               ForwardIt last,
Z
Zhang Ting 已提交
201 202 203 204
                               const std::vector<IndexT>& sorted_indices_vec,
                               std::vector<IndexT>* inverse_vec,
                               std::vector<IndexT>* counts_vec,
                               std::vector<IndexT>* indices_vec) {
Z
Zhang Ting 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218
  if (first == last) {
    return last;
  }

  (*inverse_vec)[sorted_indices_vec[0]] = 0;
  (*counts_vec)[0] = 1;
  (*indices_vec)[0] = sorted_indices_vec[0];

  ForwardIt begin = first;
  ForwardIt result = first;

  while (++first != last) {
    int64_t idx_first = std::distance(begin, first);
    int64_t idx_result = std::distance(begin, result);
Z
Zhang Ting 已提交
219
    if (!Equal<InT>(*result, *first)) {
Z
Zhang Ting 已提交
220 221 222 223 224 225 226 227 228 229 230 231
      if (++result != first) {
        *result = std::move(*first);
      }
      idx_result += 1;
      (*indices_vec)[idx_result] = sorted_indices_vec[idx_first];
    }
    (*inverse_vec)[sorted_indices_vec[idx_first]] = idx_result;
    (*counts_vec)[idx_result] += 1;
  }
  return ++result;
}

Z
Zhang Ting 已提交
232
template <typename DeviceContext, typename InT, typename IndexT>
Z
Zhang Ting 已提交
233
static void UniqueDim(const framework::ExecutionContext& context,
234 235
                      const phi::DenseTensor& in,
                      phi::DenseTensor* out,
236 237 238 239
                      bool return_index,
                      bool return_inverse,
                      bool return_counts,
                      int axis) {
Z
Zhang Ting 已提交
240 241 242 243 244
  // transpose tensor: eg. axis=1, [dim0, dim1, dim2] -> [dim1, dim0, dim2]
  std::vector<int> permute(in.dims().size());
  std::iota(permute.begin(), permute.end(), 0);
  permute[axis] = 0;
  permute[0] = axis;
245
  std::vector<int64_t> in_trans_dims_vec(phi::vectorize(in.dims()));
Z
Zhang Ting 已提交
246 247
  in_trans_dims_vec[axis] = in.dims()[0];
  in_trans_dims_vec[0] = in.dims()[axis];
248
  phi::DenseTensor in_trans;
249
  framework::DDim in_trans_dims = phi::make_ddim(in_trans_dims_vec);
Z
Zhang Ting 已提交
250
  in_trans.Resize(in_trans_dims);
Z
Zhang Ting 已提交
251
  in_trans.mutable_data<InT>(context.GetPlace());
Z
Zhang Ting 已提交
252
  auto& dev_ctx = context.template device_context<DeviceContext>();
253
  phi::funcs::TransCompute<DeviceContext, InT>(
254
      in.dims().size(), dev_ctx, in, &in_trans, permute);
Z
Zhang Ting 已提交
255
  // reshape tensor: eg. [dim1, dim0, dim2] -> [dim1, dim0*dim2]
256
  framework::DDim in_trans_flat_dims = phi::flatten_to_2d(in_trans_dims, 1);
Z
Zhang Ting 已提交
257 258 259
  in_trans.Resize(in_trans_flat_dims);

  // sort indices
Z
Zhang Ting 已提交
260
  std::vector<IndexT> sorted_indices_vec(in_trans.dims()[0]);
Z
Zhang Ting 已提交
261 262
  std::iota(sorted_indices_vec.begin(), sorted_indices_vec.end(), 0);
  int64_t col = in_trans.dims()[1];
Z
Zhang Ting 已提交
263
  const InT* in_trans_data = in_trans.data<InT>();
264 265
  std::sort(sorted_indices_vec.begin(),
            sorted_indices_vec.end(),
Z
Zhang Ting 已提交
266 267
            [&](int64_t a, int64_t b) -> bool {
              for (int64_t i = 0; i < col; ++i) {
Z
Zhang Ting 已提交
268 269
                InT lhs = in_trans_data[i + a * col];
                InT rhs = in_trans_data[i + b * col];
Z
Zhang Ting 已提交
270 271 272 273 274 275 276 277 278 279
                if (lhs < rhs) {
                  return true;
                } else if (lhs > rhs) {
                  return false;
                }
              }
              return false;
            });

  // sort tensor according to indices
280
  phi::DenseTensor input_sorted;
Z
Zhang Ting 已提交
281
  input_sorted.Resize(in_trans_dims);
Z
Zhang Ting 已提交
282 283
  input_sorted.mutable_data<InT>(context.GetPlace());
  InT* input_sorted_data = input_sorted.data<InT>();
Z
Zhang Ting 已提交
284 285
  for (size_t i = 0; i < sorted_indices_vec.size(); ++i) {
    memcpy(input_sorted_data + i * col,
Z
Zhang Ting 已提交
286 287
           in_trans_data + static_cast<int64_t>(sorted_indices_vec[i]) * col,
           col * sizeof(InT));
Z
Zhang Ting 已提交
288 289
  }

290
  std::vector<phi::DenseTensor> input_unbind = Unbind(input_sorted);
Z
Zhang Ting 已提交
291 292 293
  std::vector<IndexT> inverse_vec(sorted_indices_vec.size(), 0);
  std::vector<IndexT> counts_vec(sorted_indices_vec.size(), 0);
  std::vector<IndexT> indices_vec(sorted_indices_vec.size(), 0);
294
  auto last = UniqueDimImpl<std::vector<phi::DenseTensor>::iterator, InT>(
295 296 297 298 299 300 301
      context,
      input_unbind.begin(),
      input_unbind.end(),
      sorted_indices_vec,
      &inverse_vec,
      &counts_vec,
      &indices_vec);
Z
Zhang Ting 已提交
302 303 304 305 306
  input_unbind.erase(last, input_unbind.end());
  counts_vec.erase(counts_vec.begin() + input_unbind.size(), counts_vec.end());
  indices_vec.erase(indices_vec.begin() + input_unbind.size(),
                    indices_vec.end());

Z
Zhang Ting 已提交
307
  math::ConcatFunctor<DeviceContext, InT> concat_functor;
308
  phi::DenseTensor out_trans;
Z
Zhang Ting 已提交
309 310
  std::vector<int64_t> out_trans_dims_vec = in_trans_dims_vec;
  out_trans_dims_vec[0] = input_unbind.size();
311
  out_trans.Resize(phi::make_ddim(out_trans_dims_vec));
Z
Zhang Ting 已提交
312
  out_trans.mutable_data<InT>(context.GetPlace());
Z
Zhang Ting 已提交
313
  std::swap(out_trans_dims_vec[0], out_trans_dims_vec[axis]);
314
  out->Resize(phi::make_ddim(out_trans_dims_vec));
Z
Zhang Ting 已提交
315
  out->mutable_data<InT>(context.GetPlace());
Z
Zhang Ting 已提交
316
  concat_functor(dev_ctx, input_unbind, 0, &out_trans);
317
  phi::funcs::TransCompute<DeviceContext, InT>(
318
      out_trans.dims().size(), dev_ctx, out_trans, out, permute);
Z
Zhang Ting 已提交
319 320

  if (return_inverse) {
321
    auto* inverse = context.Output<phi::DenseTensor>("Index");
Z
Zhang Ting 已提交
322 323 324 325
    framework::TensorFromVector(inverse_vec, context.device_context(), inverse);
  }

  if (return_counts) {
326
    auto* count = context.Output<phi::DenseTensor>("Counts");
Z
Zhang Ting 已提交
327 328 329 330
    framework::TensorFromVector(counts_vec, context.device_context(), count);
  }

  if (return_index) {
331
    auto* indices = context.Output<phi::DenseTensor>("Indices");
Z
Zhang Ting 已提交
332 333 334 335
    framework::TensorFromVector(indices_vec, context.device_context(), indices);
  }
}

Z
Zhang Ting 已提交
336 337 338
template <typename DeviceContext, typename InT>
struct UniqueFlattendTensorFunctor {
  const framework::ExecutionContext& ctx_;
339 340
  const phi::DenseTensor& in_;
  phi::DenseTensor* out_;
Z
Zhang Ting 已提交
341 342 343 344 345
  const bool return_index_;
  const bool return_inverse_;
  const bool return_counts_;

  UniqueFlattendTensorFunctor(const framework::ExecutionContext& context,
346 347
                              const phi::DenseTensor& in,
                              phi::DenseTensor* out,
348 349 350
                              bool return_index,
                              bool return_inverse,
                              bool return_counts)
Z
Zhang Ting 已提交
351 352 353 354 355 356 357 358 359
      : ctx_(context),
        in_(in),
        out_(out),
        return_index_(return_index),
        return_inverse_(return_inverse),
        return_counts_(return_counts) {}

  template <typename IndexT>
  void apply() const {
360 361
    UniqueFlattendTensor<InT, IndexT>(
        ctx_, in_, out_, return_index_, return_inverse_, return_counts_);
Z
Zhang Ting 已提交
362 363 364 365 366 367
  }
};

template <typename DeviceContext, typename InT>
struct UniqueDimFunctor {
  const framework::ExecutionContext& ctx_;
368 369
  const phi::DenseTensor& in_;
  phi::DenseTensor* out_;
Z
Zhang Ting 已提交
370 371 372 373 374 375
  const int axis_;
  const bool return_index_;
  const bool return_inverse_;
  const bool return_counts_;

  UniqueDimFunctor(const framework::ExecutionContext& context,
376 377
                   const phi::DenseTensor& in,
                   phi::DenseTensor* out,
378 379 380
                   const int axis,
                   bool return_index,
                   bool return_inverse,
Z
Zhang Ting 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
                   bool return_counts)
      : ctx_(context),
        in_(in),
        out_(out),
        axis_(axis),
        return_index_(return_index),
        return_inverse_(return_inverse),
        return_counts_(return_counts) {}

  template <typename IndexT>
  void apply() const {
    UniqueDim<DeviceContext, InT, IndexT>(
        ctx_, in_, out_, return_index_, return_inverse_, return_counts_, axis_);
  }
};

Z
Zhang Ting 已提交
397
template <typename DeviceContext, typename T>
Z
zhoukunsheng 已提交
398 399 400
class UniqueKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
401 402
    auto* x = context.Input<phi::DenseTensor>("X");
    auto* out = context.Output<phi::DenseTensor>("Out");
Z
Zhang Ting 已提交
403 404 405 406
    auto data_type = static_cast<framework::proto::VarType::Type>(
        context.Attr<int>("dtype"));
    if (data_type == framework::proto::VarType::INT32) {
      PADDLE_ENFORCE_LE(
407 408
          x->numel(),
          INT_MAX,
Z
Zhang Ting 已提交
409 410 411 412 413 414
          platform::errors::InvalidArgument(
              "The number of elements in Input(X) should be less than or "
              "equal to INT_MAX, but received num is %d. Please set `dtype` to "
              "int64.",
              x->numel()));
    }
Z
Zhang Ting 已提交
415
    if (!context.Attr<bool>("is_sorted")) {
416
      auto* index = context.Output<phi::DenseTensor>("Index");
Z
Zhang Ting 已提交
417 418 419 420

      framework::VisitDataType(data_type, UniqueOpFunctor<T>(out, index, x));
      return;
    }
Z
zhoukunsheng 已提交
421

Z
Zhang Ting 已提交
422 423 424 425
    std::vector<int> axis_vec = context.Attr<std::vector<int>>("axis");
    bool return_index = context.Attr<bool>("return_index");
    bool return_inverse = context.Attr<bool>("return_inverse");
    bool return_counts = context.Attr<bool>("return_counts");
426 427 428 429
    if (x->numel() == 0) {
      out->mutable_data<T>(context.GetPlace());
      return;
    }
Z
Zhang Ting 已提交
430
    if (axis_vec.empty()) {
431
      framework::VisitDataTypeTiny(
Z
Zhang Ting 已提交
432 433 434
          data_type,
          UniqueFlattendTensorFunctor<DeviceContext, T>(
              context, *x, out, return_index, return_inverse, return_counts));
Z
Zhang Ting 已提交
435 436
    } else {
      int axis = axis_vec[0];
437
      framework::VisitDataTypeTiny(
438 439 440 441 442 443 444 445
          data_type,
          UniqueDimFunctor<DeviceContext, T>(context,
                                             *x,
                                             out,
                                             axis,
                                             return_index,
                                             return_inverse,
                                             return_counts));
Z
Zhang Ting 已提交
446
    }
Z
zhoukunsheng 已提交
447 448 449 450 451
  }
};

}  // namespace operators
}  // namespace paddle