Caffe2 - C++ API
A deep learning, cross platform ML framework
rowmul_op.h
1 #ifndef CAFFE2_OPERATORS_ROW_MUL_H_
2 #define CAFFE2_OPERATORS_ROW_MUL_H_
3 
4 #include "caffe2/core/context.h"
5 #include "caffe2/core/logging.h"
6 #include "caffe2/core/operator.h"
7 #include "caffe2/utils/math.h"
8 
9 namespace caffe2 {
10 
11 // A hacky version of Mul with broadcast
12 // RowMul([mat, w], [output])
13 template <typename T, class Context>
14 class RowMulOp : public Operator<Context> {
15  public:
16  USE_OPERATOR_CONTEXT_FUNCTIONS;
17  USE_SIMPLE_CTOR_DTOR(RowMulOp);
18 
19  bool RunOnDevice() override {
20  auto& mat = Input(0);
21  auto& w = Input(1);
22 
23  auto* output = Output(0, mat.sizes(), at::dtype<T>());
24  T* output_data = output->template mutable_data<T>();
25  const T* mat_data = mat.template data<T>();
26  const T* w_data = w.template data<T>();
27 
28  // Dimension checking
29  CAFFE_ENFORCE_EQ(
30  w.numel(),
31  mat.dim32(0),
32  "Length of w should be equal to the first dim of mat");
33 
34  auto block_size = mat.size_from_dim(1);
35  for (int i = 0; i < w.numel(); i++) {
36  size_t offset = i * block_size;
37  for (int j = 0; j < block_size; j++) {
38  output_data[offset + j] = mat_data[offset + j] * w_data[i];
39  }
40  }
41 
42  return true;
43  }
44 };
45 
46 // A hacky version
47 template <typename T, class Context>
48 class ReduceTailSumOp : public Operator<Context> {
49  public:
50  USE_OPERATOR_CONTEXT_FUNCTIONS;
51  USE_SIMPLE_CTOR_DTOR(ReduceTailSumOp);
52 
53  bool RunOnDevice() override {
54  auto& mat = Input(0);
55 
56  int N = mat.dim32(0);
57  int block_size = mat.size_from_dim(1);
58 
59  auto* output = Output(0, {N}, at::dtype<T>());
60  T* output_data = output->template mutable_data<T>();
61  const T* mat_data = mat.template data<T>();
62 
63  for (int i = 0; i < N; i++) {
64  output_data[i] = 0;
65  size_t offset = i * block_size;
66  for (int j = 0; j < block_size; j++) {
67  output_data[i] += mat_data[offset + j];
68  }
69  }
70  return true;
71  }
72 };
73 
74 } // namespace caffe2
75 
76 #endif // CAFFE2_OPERATORS_ROW_MUL_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