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