Caffe2 - C++ API
A deep learning, cross platform ML framework
find_duplicate_elements_op.h
1 #ifndef CAFFE2_OPERATORS_FIND_DUPLICATE_ELEMENTS_OP_H
2 #define CAFFE2_OPERATORS_FIND_DUPLICATE_ELEMENTS_OP_H
3 
4 #include <unordered_map>
5 #include <vector>
6 
7 #include "caffe2/core/context.h"
8 #include "caffe2/core/operator.h"
9 #include "caffe2/core/tensor.h"
10 
11 namespace caffe2 {
12 
13 template <class Context>
14 class FindDuplicateElementsOp final : public Operator<Context> {
15  public:
16  USE_OPERATOR_CONTEXT_FUNCTIONS;
17  USE_SIMPLE_CTOR_DTOR(FindDuplicateElementsOp);
18  USE_DISPATCH_HELPER;
19 
20  bool RunOnDevice() override {
22  call(this, Input(0));
23  }
24 
25  template <typename T>
26  bool DoRunWithType() {
27  const auto& data = Input(0);
28  CAFFE_ENFORCE(data.dim() == 1, "data should be 1-D.");
29 
30  const auto* data_ptr = data.template data<T>();
31  std::unordered_map<T, int64_t> dict;
32  std::vector<int64_t> dupIndices;
33  // i is the index of unique elements, j is the index of all elements
34  for (int64_t i = 0, j = 0; j < data.sizes()[0]; ++i, ++j) {
35  bool retVal = dict.insert({data_ptr[j], i}).second;
36  if (!retVal) {
37  --i;
38  dupIndices.push_back(j);
39  }
40  }
41 
42  const auto dupSize = dupIndices.size();
43 
44  auto* output = Output(0, {static_cast<int64_t>(dupSize)}, at::dtype<int64_t>());
45  auto* out_ptr = output->template mutable_data<int64_t>();
46  for (size_t i = 0; i < dupSize; ++i) {
47  out_ptr[i] = dupIndices[i];
48  }
49 
50  return true;
51  }
52 };
53 
54 } // namespace caffe2
55 
56 #endif // CAFFE2_OPERATORS_FIND_DUPLICATE_ELEMENTS_OP_H
const Tensor & Input(int idx, DeviceType type=Context::GetDeviceType())
Retrieve a non-owning reference to the input at position &#39;idx&#39; for this operator. ...
Definition: operator.h:702
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13