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  FindOp(const OperatorDef& operator_def, Workspace* ws)
16  : Operator<Context>(operator_def, ws),
17  missing_value_(
18  OperatorBase::GetSingleArgument<int>("missing_value", -1)) {}
19  USE_OPERATOR_CONTEXT_FUNCTIONS;
20  USE_DISPATCH_HELPER;
21 
22  bool RunOnDevice() {
23  return DispatchHelper<TensorTypes<int, long>>::call(this, Input(0));
24  }
25 
26  protected:
27  template <typename T>
28  bool DoRunWithType() {
29  auto& idx = Input(0);
30  auto& needles = Input(1);
31  auto* res_indices = Output(0);
32  res_indices->ResizeLike(needles);
33 
34  const T* idx_data = idx.template data<T>();
35  const T* needles_data = needles.template data<T>();
36  T* res_data = res_indices->template mutable_data<T>();
37  auto idx_size = idx.size();
38 
39  // Use an arbitrary cut-off for when to use brute-force
40  // search. For larger needle sizes we first put the
41  // index into a map
42  if (needles.size() < 16) {
43  // Brute force O(nm)
44  for (int i = 0; i < needles.size(); i++) {
45  T x = needles_data[i];
46  T res = static_cast<T>(missing_value_);
47  for (int j = idx_size - 1; j >= 0; j--) {
48  if (idx_data[j] == x) {
49  res = j;
50  break;
51  }
52  }
53  res_data[i] = res;
54  }
55  } else {
56  // O(n + m)
57  std::unordered_map<T, int> idx_map;
58  for (int j = 0; j < idx_size; j++) {
59  idx_map[idx_data[j]] = j;
60  }
61  for (int i = 0; i < needles.size(); i++) {
62  T x = needles_data[i];
63  auto it = idx_map.find(x);
64  res_data[i] = (it == idx_map.end() ? missing_value_ : it->second);
65  }
66  }
67 
68  return true;
69  }
70 
71  protected:
72  int missing_value_;
73 };
74 
75 } // namespace caffe2
76 
77 #endif // CAFFE2_OPERATORS_FIND_OP_H_
Workspace is a class that holds all the related objects created during runtime: (1) all blobs...
Definition: workspace.h:47
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...