Caffe2 - C++ API
A deep learning, cross platform ML framework
index_hash_ops.h
1 #ifndef CAFFE2_OPERATORS_INDEX_HASH_OPS_H_
2 #define CAFFE2_OPERATORS_INDEX_HASH_OPS_H_
3 
4 #include "caffe2/core/asan.h"
5 #include "caffe2/core/logging.h"
6 #include "caffe2/core/operator.h"
7 
8 namespace caffe2 {
9 
10 template <class Context>
11 class IndexHashOp : public Operator<Context> {
12  public:
13  USE_OPERATOR_CONTEXT_FUNCTIONS;
14  IndexHashOp(const OperatorDef& operator_def, Workspace* ws)
15  : Operator<Context>(operator_def, ws),
16  seed_(OperatorBase::GetSingleArgument<int64_t>("seed", 0)),
17  modulo_(OperatorBase::GetSingleArgument<int64_t>("modulo", 0)) {
18  CAFFE_ENFORCE_GT(modulo_, 0, "MODULO should be > 0");
19  }
20 
21  bool RunOnDevice() override {
23  this, Input(INDICES));
24  }
25 
26  template <typename T>
27  bool DoRunWithType() {
28  auto& indices = Input(INDICES);
29  auto* hashed_indices = Output(HASHED_INDICES);
30  hashed_indices->ResizeLike(indices);
31 
32  CAFFE_ENFORCE_GE(
33  static_cast<int64_t>(std::numeric_limits<T>::max()),
34  modulo_,
35  "MODULO shouldn't be larger than the numeric limit of the indices");
36 
37  auto N = indices.size();
38  auto* indices_data = indices.template data<T>();
39  auto* hashed_indices_data = hashed_indices->template mutable_data<T>();
40 
41  for (auto i = 0; i < N; i++) {
42  hashed_indices_data[i] = hash(indices_data[i]);
43  }
44 
45  return true;
46  }
47 
48  protected:
49  template <typename T>
50  CAFFE2_NO_SANITIZE("signed-integer-overflow") T hash(T id) {
51  int8_t* bytes = (int8_t*)&id;
52  T hashed = seed_ * 0xDEADBEEF;
53  for (int i = 0; i < sizeof(T) / sizeof(int8_t); i++) {
54  hashed = hashed * 65537 + bytes[i];
55  }
56  // We want the result of the modulo to be positive. This works under the
57  // assumption that modulo_ > 0 which is enforced in the constructor.
58  auto modHashed = hashed % modulo_;
59  return modHashed >= 0 ? modHashed : modHashed + modulo_;
60  }
61 
62  private:
63  INPUT_TAGS(INDICES);
64  OUTPUT_TAGS(HASHED_INDICES);
65 
66  int64_t seed_;
67  int64_t modulo_;
68 };
69 
70 } // namespace caffe2
71 
72 #endif // CAFFE2_OPERATORS_INDEX_HASH_OPS_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 ...