Caffe2 - C++ API
A deep learning, cross platform ML framework
find_op.h
1 #ifndef CAFFE2_OPERATORS_FIND_OP_H_
2 #define CAFFE2_OPERATORS_FIND_OP_H_
3 
4 #include "caffe2/core/context.h"
5 #include "caffe2/core/logging.h"
6 #include "caffe2/core/operator.h"
7 
8 #include <unordered_map>
9 
10 namespace caffe2 {
11 
12 template <class Context>
13 class FindOp final : public Operator<Context> {
14  public:
15  template <class... Args>
16  explicit FindOp(Args&&... args)
17  : Operator<Context>(std::forward<Args>(args)...),
18  missing_value_(
19  this->template GetSingleArgument<int>("missing_value", -1)) {}
20  USE_OPERATOR_CONTEXT_FUNCTIONS;
21  USE_DISPATCH_HELPER;
22 
23  bool RunOnDevice() {
24  return DispatchHelper<TensorTypes<int, long>>::call(this, Input(0));
25  }
26 
27  protected:
28  template <typename T>
29  bool DoRunWithType() {
30  auto& idx = Input(0);
31  auto& needles = Input(1);
32 
33  auto* res_indices = Output(0, needles.sizes(), at::dtype<T>());
34 
35  const T* idx_data = idx.template data<T>();
36  const T* needles_data = needles.template data<T>();
37  T* res_data = res_indices->template mutable_data<T>();
38  auto idx_size = idx.numel();
39 
40  // Use an arbitrary cut-off for when to use brute-force
41  // search. For larger needle sizes we first put the
42  // index into a map
43  if (needles.numel() < 16) {
44  // Brute force O(nm)
45  for (int i = 0; i < needles.numel(); i++) {
46  T x = needles_data[i];
47  T res = static_cast<T>(missing_value_);
48  for (int j = idx_size - 1; j >= 0; j--) {
49  if (idx_data[j] == x) {
50  res = j;
51  break;
52  }
53  }
54  res_data[i] = res;
55  }
56  } else {
57  // O(n + m)
58  std::unordered_map<T, int> idx_map;
59  for (int j = 0; j < idx_size; j++) {
60  idx_map[idx_data[j]] = j;
61  }
62  for (int i = 0; i < needles.numel(); i++) {
63  T x = needles_data[i];
64  auto it = idx_map.find(x);
65  res_data[i] = (it == idx_map.end() ? missing_value_ : it->second);
66  }
67  }
68 
69  return true;
70  }
71 
72  protected:
73  int missing_value_;
74 };
75 
76 } // namespace caffe2
77 
78 #endif // CAFFE2_OPERATORS_FIND_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