Caffe2 - C++ API
A deep learning, cross platform ML framework
clip_op.cc
1 #include "caffe2/operators/clip_op.h"
2 
3 namespace caffe2 {
4 
5 template <>
6 bool ClipOp<float, CPUContext>::RunOnDevice() {
7  auto& X = Input(0);
8  auto* Y = Output(0);
9  Y->ResizeLike(X);
10  EigenVectorMap<float>(Y->mutable_data<float>(), Y->size()) =
11  ConstEigenVectorMap<float>(X.data<float>(), X.size())
12  .cwiseMax(min_)
13  .cwiseMin(max_);
14  return true;
15 }
16 
17 template <>
18 bool ClipGradientOp<float, CPUContext>::RunOnDevice() {
19  auto& Y = Input(0);
20  auto& dY = Input(1);
21  auto* dX = Output(0);
22  CAFFE_ENFORCE_GT(Y.size(), 0);
23  CAFFE_ENFORCE_EQ(dY.size(), Y.size());
24  dX->ResizeLike(Y);
25  const float* Ydata = Y.data<float>();
26  const float* dYdata = dY.data<float>();
27  float* dXdata = dX->mutable_data<float>();
28  for (int i = 0; i < Y.size(); ++i) {
29  dXdata[i] = dYdata[i] * (Ydata[i] > min_ && Ydata[i] < max_);
30  }
31  return true;
32 }
33 
34 REGISTER_CPU_OPERATOR(Clip, ClipOp<float, CPUContext>);
35 REGISTER_CPU_OPERATOR(ClipGradient, ClipGradientOp<float, CPUContext>);
36 
37 OPERATOR_SCHEMA(Clip)
38  .NumInputs(1)
39  .NumOutputs(1)
40  .AllowInplace({{0, 0}})
41  .IdenticalTypeAndShape()
42  .SetDoc(R"DOC(
43 Clip operator limits the given input within an interval. The interval is
44 specified with arguments 'min' and 'max'. They default to
45 numeric_limits::lowest() and numeric_limits::max() respectively. The clipping
46 operation can be done in in-place fashion too, where the input and output blobs
47 are the same.
48 )DOC")
49  .Arg("min", "Minimum value, under which element is replaced by min")
50  .Arg("max", "Maximum value, above which element is replaced by max")
51  .Input(
52  0,
53  "input",
54  "Input tensor (Tensor<float>) containing elements to be"
55  "clipped")
56  .Input(
57  1,
58  "output",
59  "Output tensor (Tensor<float>) containing clipped"
60  "input elements")
61  .InheritOnnxSchema("Clip");
62 
63 OPERATOR_SCHEMA(ClipGradient).NumInputs(2).NumOutputs(1).AllowInplace({{1, 0}});
64 
65 class GetClipGradient : public GradientMakerBase {
66  using GradientMakerBase::GradientMakerBase;
67  vector<OperatorDef> GetGradientDefs() override {
68  return SingleGradientDef(
69  "ClipGradient", "",
70  vector<string>{O(0), GO(0)},
71  vector<string>{GI(0)});
72  }
73 };
74 REGISTER_GRADIENT(Clip, GetClipGradient);
75 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...