Caffe2 - C++ API
A deep learning, cross platform ML framework
cos_op.cc
1 #include "caffe2/operators/cos_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 CosGradientFunctor<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.sin();
23  return true;
24 }
25 
26 REGISTER_CPU_OPERATOR(
27  Cos,
28  UnaryElementwiseOp<TensorTypes<float>, CPUContext, CosFunctor<CPUContext>>);
29 REGISTER_CPU_OPERATOR(
30  CosGradient,
31  BinaryElementwiseOp<
32  TensorTypes<float>,
33  CPUContext,
34  CosGradientFunctor<CPUContext>>);
35 
36 OPERATOR_SCHEMA(Cos)
37  .NumInputs(1)
38  .NumOutputs(1)
39  .IdenticalTypeAndShape()
40  .SetDoc(R"DOC(
41 Calculates the cosine of the given input tensor, element-wise.
42 
43 Github Links:
44 
45 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cos_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  "Cos",
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.6816719 0.76771533 0.933932 0.01404487 0.11862425]
76 Y: [0.7765203 0.71949923 0.5946774 0.99990135 0.9929724 ]
77 
78 ```
79 
80 </details>
81 
82 
83 )DOC")
84  .Input(0, "X", "*(type: Tensor`<float>`)* Input tensor.")
85  .Output(
86  0,
87  "Y",
88  "*(type: Tensor`<float>`)* Output tensor calculated as the cosine of the input tensor, element-wise.");
89 
90 OPERATOR_SCHEMA(CosGradient).NumInputs(2).NumOutputs(1).IdenticalTypeAndShape();
91 
92 namespace {
93 
94 class GetCosGradient : public GradientMakerBase {
95  using GradientMakerBase::GradientMakerBase;
96  std::vector<OperatorDef> GetGradientDefs() override {
97  return SingleGradientDef(
98  "CosGradient",
99  "",
100  std::vector<std::string>{I(0), GO(0)},
101  std::vector<std::string>{GI(0)});
102  }
103 };
104 
105 } // namespace
106 
107 REGISTER_GRADIENT(Cos, GetCosGradient);
108 
109 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13