1 #include "caffe2/operators/clip_op.h" 2 #include "caffe2/utils/eigen_utils.h" 7 bool ClipOp<float, CPUContext>::RunOnDevice() {
10 auto* Y = Output(0, X.sizes(), at::dtype<float>());
11 EigenVectorMap<float>(Y->template mutable_data<float>(), Y->numel()) =
12 ConstEigenVectorMap<float>(X.data<
float>(), X.numel())
19 bool ClipGradientOp<float, CPUContext>::RunOnDevice() {
23 CAFFE_ENFORCE_GE(Y.numel(), 0);
24 CAFFE_ENFORCE_EQ(dY.numel(), Y.numel());
25 auto* dX = Output(0, Y.sizes(), at::dtype<float>());
26 const float* Ydata = Y.data<
float>();
27 const float* dYdata = dY.data<
float>();
28 float* dXdata = dX->template mutable_data<float>();
29 for (
int i = 0; i < Y.numel(); ++i) {
30 dXdata[i] = dYdata[i] * (Ydata[i] > min_ && Ydata[i] < max_);
35 REGISTER_CPU_OPERATOR(
Clip, ClipOp<float, CPUContext>);
36 REGISTER_CPU_GRADIENT_OPERATOR(ClipGradient, ClipGradientOp<float, CPUContext>);
41 .AllowInplace({{0, 0}})
42 .IdenticalTypeAndShape()
44 This operator limits the given input within an interval. The interval is 45 specified by the `min` and `max` arguments. They default to 46 *numeric_limits::lowest()* and *numeric_limits::max()* respectively. The 47 clipping operation can be done in an in-place fashion by using the same output 48 blob as the input blob. 52 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/clip_op.cc 56 <summary> <b>Example</b> </summary> 61 workspace.ResetWorkspace() 63 op = core.CreateOperator( 72 workspace.FeedBlob("X", (np.random.randint(100, size=(5,5))).astype(np.float32)) 73 print("X:", workspace.FetchBlob("X")) 74 workspace.RunOperatorOnce(op) 75 print("Y:", workspace.FetchBlob("Y")) 82 X: [[45. 16. 59. 99. 48.] 86 [36. 38. 30. 84. 40.]] 87 Y: [[45. 20. 59. 60. 48.] 91 [36. 38. 30. 60. 40.]] 99 "*(type: float)* Minimum value, under which element is " 100 "replaced by min (default=*numeric_limits::lowest()*).")
103 "*(type: float)* Maximum value, under which element is " 104 "replaced by max (default=*numeric_limits::max()*).")
108 "*(Tensor`<float>`)* Input tensor within range " 109 "[*numeric_limits::lowest()*, *numeric_limits::max()*].")
113 "*(Tensor`<float>`)* Output tensor clipped within range [`min`, `max`].")
114 .InheritOnnxSchema();
116 GRADIENT_OPERATOR_SCHEMA(ClipGradient)
119 .AllowInplace({{1, 0}});
121 class GetClipGradient :
public GradientMakerBase {
122 using GradientMakerBase::GradientMakerBase;
123 vector<OperatorDef> GetGradientDefs()
override {
124 return SingleGradientDef(
126 vector<string>{O(0), GO(0)},
127 vector<string>{GI(0)});
130 REGISTER_GRADIENT(
Clip, GetClipGradient);
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...