Caffe2 - C++ API
A deep learning, cross platform ML framework
tanh_op.cc
1 #include <cmath>
2 
3 #include "caffe2/operators/elementwise_op.h"
4 #include "caffe2/utils/math.h"
5 
6 namespace caffe2 {
7 
8 struct TanhCPUFunctor {
9  template <typename T>
10  inline void
11  operator()(const int n, const T* x, T* y, CPUContext* /*device_context*/) {
12 #ifdef CAFFE2_USE_ACCELERATE
13  vvtanhf(y, x, &n);
14 #else
15  ConstEigenVectorArrayMap<T> x_arr(x, n);
16  EigenVectorMap<T>(y, n) = 1 - 2 * ((x_arr * 2).exp() + 1).inverse();
17 #endif
18  }
19 };
20 
22  template <typename T>
23  inline void Run(
24  const int n,
25  const T* y,
26  const T* dy,
27  T* dx,
28  CPUContext* /*device_context*/) {
29  ConstEigenVectorArrayMap<T> dy_arr(dy, n);
30  ConstEigenVectorArrayMap<T> y_arr(y, n);
31  EigenVectorMap<T>(dx, n) = dy_arr * (1 - y_arr * y_arr);
32  }
33 };
34 
35 REGISTER_CPU_OPERATOR(
37 REGISTER_CPU_OPERATOR(
38  TanhGradient,
41  CPUContext,
43 
44 OPERATOR_SCHEMA(Tanh)
45  .NumInputs(1)
46  .NumOutputs(1)
47  .AllowInplace({{0, 0}})
48  .IdenticalTypeAndShape()
49  .SetDoc(R"DOC(
50 Calculates the hyperbolic tangent of the given input tensor element-wise. This
51 operation can be done in an in-place fashion too, by providing the same input
52 and output blobs.
53 )DOC")
54  .Input(0, "input", "1-D input tensor")
55  .Output(0, "output", "The hyperbolic tangent values of the input tensor "
56  "computed element-wise")
57  .InheritOnnxSchema("Tanh");
58 
59 OPERATOR_SCHEMA(TanhGradient).NumInputs(2).NumOutputs(1).AllowInplace({{1, 0}});
60 
62  using GradientMakerBase::GradientMakerBase;
63  vector<OperatorDef> GetGradientDefs() override {
64  return SingleGradientDef(
65  "TanhGradient", "",
66  std::vector<string>{O(0), GO(0)},
67  std::vector<string>{GI(0)});
68  }
69 };
70 REGISTER_GRADIENT(Tanh, GetTanhGradient);
71 } // namespace caffe2
The CPU Context, representing the bare minimum of what a Context class in Caffe2 should implement...
Definition: context.h:66
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Performs a binary operation (e.g.