Caffe2 - C++ API
A deep learning, cross platform ML framework
abs_op.cc
1 #include "caffe2/operators/abs_op.h"
2 #include "caffe2/utils/eigen_utils.h"
3 
4 #include <algorithm>
5 #include <functional>
6 
7 namespace caffe2 {
8 
9 template <>
10 template <typename T>
11 bool AbsGradientFunctor<CPUContext>::Forward(
12  const std::vector<int>& X_dims,
13  const std::vector<int>& /* dY_dims */,
14  const T* X,
15  const T* dY,
16  T* dX,
17  CPUContext* /* context */) const {
18  const int size = std::accumulate(
19  X_dims.cbegin(), X_dims.cend(), 1, std::multiplies<int>());
20  ConstEigenVectorArrayMap<T> dY_arr(dY, size);
21  ConstEigenVectorArrayMap<T> X_arr(X, size);
22  EigenVectorMap<T>(dX, size) =
23  (X_arr == T(0)).select(T(0), (X_arr > T(0)).select(dY_arr, -dY_arr));
24  return true;
25 }
26 
27 REGISTER_CPU_OPERATOR(
28  Abs,
29  UnaryElementwiseOp<TensorTypes<float>, CPUContext, AbsFunctor<CPUContext>>);
30 REGISTER_CPU_OPERATOR(
31  AbsGradient,
32  BinaryElementwiseOp<
33  TensorTypes<float>,
34  CPUContext,
35  AbsGradientFunctor<CPUContext>>);
36 
37 OPERATOR_SCHEMA(Abs)
38  .NumInputs(1)
39  .NumOutputs(1)
40  .IdenticalTypeAndShape()
41  .SetDoc(R"DOC(
42 Calculates the absolute value of the given input tensor, element-wise.
43 
44 Github Links:
45 
46 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/abs_op.cc
47 
48 <details>
49 
50 <summary> <b>Example</b> </summary>
51 
52 **Code**
53 
54 ```
55 workspace.ResetWorkspace()
56 
57 op = core.CreateOperator(
58  "Abs",
59  ["X"],
60  ["Y"]
61 )
62 
63 workspace.FeedBlob("X", np.random.randn(5).astype(np.float32))
64 print("X:", workspace.FetchBlob("X"))
65 workspace.RunOperatorOnce(op)
66 print("Y:", workspace.FetchBlob("Y"))
67 
68 ```
69 
70 **Result**
71 
72 ```
73 
74 X: [ 0.3005476 1.551666 -1.3591481 0.39191285 -0.21866608]
75 Y: [0.3005476 1.551666 1.3591481 0.39191285 0.21866608]
76 
77 ```
78 
79 </details>
80 
81 )DOC")
82  .Input(0, "X", "*(type: Tensor<float>)* Input tensor.")
83  .Output(
84  0,
85  "Y",
86  "*(type: Tensor`<float>`)* Absolute value of input element-wise.")
87  .InheritOnnxSchema();
88 
89 OPERATOR_SCHEMA(AbsGradient).NumInputs(2).NumOutputs(1).IdenticalTypeAndShape();
90 
91 namespace {
92 
93 class GetAbsGradient : public GradientMakerBase {
94  using GradientMakerBase::GradientMakerBase;
95  std::vector<OperatorDef> GetGradientDefs() override {
96  return SingleGradientDef(
97  "AbsGradient",
98  "",
99  std::vector<std::string>{I(0), GO(0)},
100  std::vector<std::string>{GI(0)});
101  }
102 };
103 
104 } // namespace
105 
106 REGISTER_GRADIENT(Abs, GetAbsGradient);
107 
108 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13