Caffe2 - C++ API
A deep learning, cross platform ML framework
lpnorm_op.cc
1 #include "caffe2/operators/lpnorm_op.h"
2 
3 #include "caffe2/core/operator.h"
4 #include "caffe2/core/types.h"
5 #include "caffe2/utils/eigen_utils.h"
6 
7 namespace caffe2 {
8 
9 template <>
10 bool LpNormOp<float, CPUContext>::RunOnDevice() {
11  const auto& X = Input(0);
12 
13  auto* norm = Output(0, {1}, at::dtype<float>());
14  const float* X_data = X.data<float>();
15  const float size = average_ ? (float)X.numel() : 1.0f;
16  CAFFE_ENFORCE_GT(size, 0);
17  if (p_ == 1) {
18  *(norm->template mutable_data<float>()) =
19  (ConstEigenVectorMap<float>(X_data, X.numel()).array()).abs().sum() /
20  size;
21  // L1(x) = sum(|x|), L1_average(x) = sum(\x\) / x.size()
22  } else if (p_ == 2) {
23  *(norm->template mutable_data<float>()) =
24  (ConstEigenVectorMap<float>(X_data, X.numel()).array()).square().sum() /
25  size;
26  // L2(x) = (sum(|x|^2)), L2_average(x) = sum(|x|^2) / x.size()
27  }
28  return true;
29 }
30 
31 template <>
32 bool LpNormGradientOp<float, CPUContext>::RunOnDevice() {
33  const auto& X = Input(0);
34  const auto& dnorm = Input(1);
35 
36  CAFFE_ENFORCE_EQ(dnorm.dim(), 1);
37  CAFFE_ENFORCE_EQ(dnorm.dim32(0), 1);
38  auto* dX = Output(0, X.sizes(), at::dtype<float>());
39  const float size = average_ ? (float)X.numel() : 1.0f;
40  if (p_ == 1) {
41  EigenVectorMap<float>(dX->template mutable_data<float>(), X.numel())
42  .array() = ConstEigenVectorMap<float>(X.data<float>(), X.numel())
43  .array()
44  .unaryExpr([](float x) {
45  const float kEps = 1e-12f;
46  if (x < -kEps) {
47  return -1.0f;
48  } else if (x > kEps) {
49  return 1.0f;
50  } else {
51  return 0.0f;
52  }
53  }) *
54  ((dnorm.data<float>())[0] / size);
55  } else if (p_ == 2) {
56  EigenVectorMap<float>(dX->template mutable_data<float>(), X.numel())
57  .array() =
58  ConstEigenVectorMap<float>(X.data<float>(), X.numel()).array() * 2.0f *
59  ((dnorm.data<float>())[0] / size);
60  }
61 
62  return true;
63 }
64 
65 namespace {
66 // LpNorm
67 REGISTER_CPU_OPERATOR(LpNorm, LpNormOp<float, CPUContext>);
68 REGISTER_CPU_OPERATOR(LpNormGradient, LpNormGradientOp<float, CPUContext>);
69 
70 OPERATOR_SCHEMA(LpNorm)
71  .NumInputs(1)
72  .NumOutputs(1)
73  .SetDoc(R"DOC(
74 This op computes the $L_p$ norm of the one dimensional input tensor $X$, and outputs a one dimensional output tensor $Y$. Here, the $L_p$ norm is calculated as
75 
76 $$L_p(\mathbf{x}) = \sum_i x_i^p$$
77 
78 This op supports $p$ values of 1 or 2. If the average argument is set, the norm is calculated as Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x).
79 
80 Github Links:
81 
82 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.h
83 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.cc
84 
85 
86 <details>
87 
88 <summary> <b>Example</b> </summary>
89 
90 **Code**
91 
92 ```
93 workspace.ResetWorkspace()
94 
95 op = core.CreateOperator(
96  "LpNorm",
97  ["X"],
98  ["Y"],
99  p=2
100 )
101 X = np.array([5., 2.])
102 print("X:\n",X)
103 
104 // Feed X into workspace
105 workspace.FeedBlob("X", X.astype(np.float32))
106 
107 workspace.RunOperatorOnce(op)
108 print("Y:\n", workspace.FetchBlob("Y"))
109 
110 ```
111 
112 **Result**
113 
114 ```
115 
116 X:
117  [5. 2.]
118 Y:
119  [29.]
120 
121 ```
122 
123 </details>
124 
125 )DOC")
126  .Input(0, "X", "1D Input tensor of data to be operated on.")
127  .Output(0, "Z", "1D output tensor")
128  .Arg(
129  "p",
130  "*(type: int; default: 2, possible values: {1,2})* Order of the norm in p-norm.")
131  .Arg(
132  "average",
133  "*(type: bool; default: False)* Whether we calculate norm or averaged_norm.The Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x)")
134  .TensorInferenceFunction([](const OperatorDef& /* unused */,
135  const vector<TensorShape>& in) {
136  std::vector<int64_t> output_dims(1);
137  output_dims[0] = 1; // 1
138  return vector<TensorShape>{
139  CreateTensorShape(vector<int64_t>{output_dims}, in[0].data_type())};
140  });
141 
142 OPERATOR_SCHEMA(LpNormGradient)
143  .NumInputs(2)
144  .NumOutputs(1)
145  .SetDoc(R"DOC(
146 Given one input float tensor X, derivative dout, and produces one output
147 float tensor dX. dX is the derivative of the Lp norm of tensor X, computed as
148 dx = d(sum over |x^p|)/dx, in which p is either 1 or 2(currently only
149 supports l1 and l2 norm) determined by the argument p.
150 )DOC")
151  .Input(0, "X", "1D input tensor")
152  .Input(1, "dout", "1D input tensor")
153  .Output(0, "dx", "1D output tensor")
154  .Arg("p", "Order of the norm in p-norm")
155  .Arg(
156  "average",
157  "whehther we calculate norm or averaged_norm."
158  "The Lp_averaged_norm(x) is defined as"
159  "Lp_averaged_normgradient(x) = LpNormGradient(x) / size(x)");
160 
161 class GetLpNormGradient : public GradientMakerBase {
162  using GradientMakerBase::GradientMakerBase;
163  vector<OperatorDef> GetGradientDefs() override {
164  return SingleGradientDef(
165  "LpNormGradient",
166  "",
167  vector<string>{I(0), GO(0)},
168  vector<string>{GI(0)});
169  }
170 };
171 
172 REGISTER_GRADIENT(LpNorm, GetLpNormGradient);
173 } // namespace
174 
175 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13