Caffe2 - C++ API
A deep learning, cross platform ML framework
mod_op.cc
1 #include "caffe2/operators/mod_op.h"
2 
3 #include "caffe2/core/operator.h"
4 #include "caffe2/core/tensor.h"
5 
6 namespace caffe2 {
7 
8 template <>
9 template <typename T>
10 bool ModOp<CPUContext>::DoRunWithType() {
11  auto& data = Input(DATA);
12  auto N = data.numel();
13  const auto* data_ptr = data.template data<T>();
14 
15  auto* output = Output(0, Input(DATA).sizes(), at::dtype<T>());
16  auto* output_ptr = output->template mutable_data<T>();
17 
18  for (auto i = 0; i < N; i++) {
19  output_ptr[i] = data_ptr[i] % divisor_;
20  if (output_ptr[i] && sign_follow_divisor_ &&
21  ((output_ptr[i] > 0) != (divisor_ > 0))) {
22  output_ptr[i] += divisor_;
23  }
24  }
25  return true;
26 }
27 
28 namespace {
29 
30 REGISTER_CPU_OPERATOR(Mod, ModOp<CPUContext>);
31 OPERATOR_SCHEMA(Mod)
32  .NumInputs(1)
33  .NumOutputs(1)
34  .Arg("divisor", "*(type: int; default: 0)* Divisor of the modulo operation (must be >= 1).")
35  .Arg(
36  "sign_follow_divisor",
37  "*(type: bool; default: False)* If true, sign of output matches divisor, else if false, sign follows dividend.")
38  .IdenticalTypeAndShape()
39  .AllowInplace({{0, 0}})
40  .SetDoc(R"DOC(
41 Element-wise modulo operation. Each element in the output is the modulo result
42 of the corresponding element in the input data. The divisor of the modulo is
43 provided by the `divisor` argument.
44 
45 Github Link:
46 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/mod_op.cc
47 
48 <details>
49 
50 <summary> <b>Example</b> </summary>
51 
52 **Code**
53 
54 ```
55 
56 workspace.ResetWorkspace()
57 
58 op = core.CreateOperator(
59  "Mod",
60  ["X"],
61  ["Y"],
62  divisor=10
63 )
64 
65 workspace.FeedBlob("X", (np.random.randint(100, size=(5,5))))
66 print("X before running op:", workspace.FetchBlob("X"))
67 workspace.RunOperatorOnce(op)
68 print("X after running op:", workspace.FetchBlob("Y"))
69 
70 ```
71 
72 **Result**
73 
74 ```
75 
76 X before running op:
77 [[56 22 43 13 60]
78  [ 4 55 58 10 45]
79  [64 66 4 3 66]
80  [10 36 47 52 78]
81  [91 4 36 47 95]]
82 X after running op:
83 [[6 2 3 3 0]
84  [4 5 8 0 5]
85  [4 6 4 3 6]
86  [0 6 7 2 8]
87  [1 4 6 7 5]]
88 
89  ```
90 
91  </details>
92 
93 )DOC")
94  .Input(0, "X", "*(type: Tensor`<int>`)* Input tensor with int32 or int64 data.")
95  .Output(0, "Y", "*(type: Tensor`<int>`)* Output tensor of data with modulo operation applied.");
96 
97 SHOULD_NOT_DO_GRADIENT(ModOp);
98 } // namespace
99 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13