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