Caffe2 - C++ API
A deep learning, cross platform ML framework
index_hash_ops.h
1 
17 #ifndef CAFFE2_OPERATORS_INDEX_HASH_OPS_H_
18 #define CAFFE2_OPERATORS_INDEX_HASH_OPS_H_
19 
20 #include "caffe2/core/logging.h"
21 #include "caffe2/core/operator.h"
22 
23 namespace caffe2 {
24 
25 template <class Context>
26 class IndexHashOp : public Operator<Context> {
27  public:
28  USE_OPERATOR_CONTEXT_FUNCTIONS;
29  IndexHashOp(const OperatorDef& operator_def, Workspace* ws)
30  : Operator<Context>(operator_def, ws),
31  seed_(OperatorBase::GetSingleArgument<int64_t>("seed", 0)),
32  modulo_(OperatorBase::GetSingleArgument<int64_t>("modulo", 0)) {
33  CAFFE_ENFORCE_GT(modulo_, 0, "MODULO should be > 0");
34  }
35 
36  bool RunOnDevice() override {
38  this, Input(INDICES));
39  }
40 
41  template <typename T>
42  bool DoRunWithType() {
43  auto& indices = Input(INDICES);
44  auto* hashed_indices = Output(HASHED_INDICES);
45  hashed_indices->ResizeLike(indices);
46 
47  CAFFE_ENFORCE_GE(
48  static_cast<int64_t>(std::numeric_limits<T>::max()),
49  modulo_,
50  "MODULO shouldn't be larger than the numeric limit of the indices");
51 
52  auto N = indices.size();
53  auto* indices_data = indices.template data<T>();
54  auto* hashed_indices_data = hashed_indices->template mutable_data<T>();
55 
56  for (auto i = 0; i < N; i++) {
57  hashed_indices_data[i] = hash(indices_data[i]);
58  }
59 
60  return true;
61  }
62 
63  protected:
64  template <typename T>
65  T hash(T id) {
66  int8_t* bytes = (int8_t*)&id;
67  T hashed = seed_ * 0xDEADBEEF;
68  for (int i = 0; i < sizeof(T) / sizeof(int8_t); i++) {
69  hashed = hashed * 65537 + bytes[i];
70  }
71  hashed = static_cast<T>((modulo_ + hashed % modulo_) % modulo_);
72  return hashed;
73  }
74 
75  private:
76  INPUT_TAGS(INDICES);
77  OUTPUT_TAGS(HASHED_INDICES);
78 
79  int64_t seed_;
80  int64_t modulo_;
81 };
82 
83 } // namespace caffe2
84 
85 #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:63
Copyright (c) 2016-present, Facebook, Inc.