Caffe2 - C++ API
A deep learning, cross platform ML framework
sin_op.cc
1 #include "caffe2/operators/sin_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 SinGradientFunctor<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) = dY_arr * X_arr.cos();
23  return true;
24 }
25 
26 REGISTER_CPU_OPERATOR(
27  Sin,
28  UnaryElementwiseOp<TensorTypes<float>, CPUContext, SinFunctor<CPUContext>>);
29 REGISTER_CPU_OPERATOR(
30  SinGradient,
31  BinaryElementwiseOp<
32  TensorTypes<float>,
33  CPUContext,
34  SinGradientFunctor<CPUContext>>);
35 
36 OPERATOR_SCHEMA(Sin)
37  .NumInputs(1)
38  .NumOutputs(1)
39  .IdenticalTypeAndShape()
40  .SetDoc(R"DOC(
41 Calculates the sine of the given input tensor, element-wise.
42 
43 Github Links:
44 
45 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sin_op.cc
46 
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  "Sin",
60  ["X"],
61  ["Y"]
62 )
63 
64 workspace.FeedBlob("X", np.random.rand(5).astype(np.float32))
65 print("X:", workspace.FetchBlob("X"))
66 workspace.RunOperatorOnce(op)
67 print("Y:", workspace.FetchBlob("Y"))
68 
69 ```
70 
71 **Result**
72 
73 ```
74 
75 X: [0.8466114 0.1803606 0.5601509 0.04959291 0.64770824]
76 Y: [0.74903965 0.17938434 0.5313141 0.04957259 0.60336035]
77 
78 ```
79 
80 </details>
81 
82 )DOC")
83 .Input(0, "X", "*(type: Tensor`<float>`)* Input tensor.")
84 .Output(
85  0,
86  "Y",
87  "*(type: Tensor`<float>`)* Output tensor calculated as the sine of the input tensor, element-wise.");
88 
89 OPERATOR_SCHEMA(SinGradient).NumInputs(2).NumOutputs(1).IdenticalTypeAndShape();
90 
91 namespace {
92 
93 class GetSinGradient : public GradientMakerBase {
94  using GradientMakerBase::GradientMakerBase;
95  std::vector<OperatorDef> GetGradientDefs() override {
96  return SingleGradientDef(
97  "SinGradient",
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(Sin, GetSinGradient);
107 
108 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13