Caffe2 - C++ API
A deep learning, cross platform ML framework
normalize_op.cc
1 #include "caffe2/operators/normalize_op.h"
2 
3 #include "caffe2/core/tensor.h"
4 
5 namespace caffe2 {
6 
7 template <typename T, class Context>
8 void NormalizeGradientOp<T, Context>::DoNormalize(
9  const T* xData,
10  const T* gOutData,
11  T* gInData,
12  const int m,
13  const int n,
14  const int sf) {
15  using InnerStride = Eigen::InnerStride<Eigen::Dynamic>;
16  using StridedVec =
17  Eigen::Map<Eigen::Matrix<T, 1, Eigen::Dynamic>, 0, InnerStride>;
18  using ConstStridedVec =
19  Eigen::Map<const Eigen::Matrix<T, 1, Eigen::Dynamic>, 0, InnerStride>;
20 
21  for (int i = 0; i < n; ++i) {
22  auto base = (i / sf) * sf * m + (i % sf);
23  ConstStridedVec xVec(xData + base, 1, m, InnerStride(sf));
24  ConstStridedVec gOutVec(gOutData + base, 1, m, InnerStride(sf));
25 
26  auto row_sum = xVec.dot(gOutVec);
27  auto row_norm = xVec.template lpNorm<2>();
28  row_norm = std::max(row_norm, kEps_);
29  auto row_norm_3 = pow(row_norm, 3);
30  StridedVec gInVec(gInData + base, 1, m, InnerStride(sf));
31  gInVec = (gOutVec / row_norm) - ((xVec / row_norm_3) * row_sum);
32  }
33 };
34 
35 REGISTER_CPU_OPERATOR(Normalize, NormalizeOp<float, CPUContext>);
36 OPERATOR_SCHEMA(Normalize)
37  .NumInputs(1)
38  .NumOutputs(1)
39  .Arg("axis", "axis to normalize")
40  .SetDoc(R"DOC(
41 Given a matrix, apply L2-normalization along the specified dimension.
42 )DOC")
43  .IdenticalTypeAndShape();
44 
45 REGISTER_CPU_GRADIENT_OPERATOR(
46  NormalizeGradient,
47  NormalizeGradientOp<float, CPUContext>);
48 GRADIENT_OPERATOR_SCHEMA(NormalizeGradient)
49  .NumInputs(2)
50  .NumOutputs(1)
51  .Arg("axis", "axis to normalize");
52 
53 class GetNormalizeGradient final : public GradientMakerBase {
54  using GradientMakerBase::GradientMakerBase;
55  vector<OperatorDef> GetGradientDefs() override {
56  CAFFE_ENFORCE_EQ(def_.input_size(), 1);
57  return SingleGradientDef(
58  "NormalizeGradient",
59  "",
60  vector<string>{I(0), GO(0)},
61  vector<string>{GI(0)});
62  }
63 };
64 REGISTER_GRADIENT(Normalize, GetNormalizeGradient);
65 
66 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13
static vector< OperatorDef > SingleGradientDef(const Args &...args)
a helper function to allow one to create one single operator def, which is usually the case for many ...