1 #include "caffe2/operators/slice_op.h" 2 #include "caffe2/utils/math.h" 6 REGISTER_CPU_OPERATOR(Slice, SliceOp<CPUContext>);
7 REGISTER_CPU_GRADIENT_OPERATOR(SliceGradient, SliceGradientOp<CPUContext>);
12 .DisallowInputFillers()
14 Produces a slice of the input tensor. 16 - Currently, only slicing in a single dimension is supported. 18 - Start and end indices are either passed as two 1D input tensors or using the `starts` and `ends` arguments. 20 - If a negative value is passed for any of the start or end indices, it represents the number of elements before the end of that dimension. End indices are non-inclusive unless negative (end index -1 means up to and including the last element). 23 - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/slice_op.cc 27 <summary> <b>Example</b> </summary> 33 workspace.ResetWorkspace() 35 op = core.CreateOperator( 43 workspace.FeedBlob("X", np.array([[1,2,3,4],[5,6,7,8]])) 44 print("X:", workspace.FetchBlob("X")) 45 workspace.RunOperatorOnce(op) 46 print("Y:", workspace.FetchBlob("Y")) 66 .Input(0, "X",
"(*Tensor*): tensor to extract slices from")
70 "(*Tensor`<int>`*): 1D tensor of start-indices for each dimension of data")
74 "(*Tensor`<int>`*): 1D tensor of end-indices for each dimension of data")
75 .Arg(
"starts",
"(*Tuple(int)*): list of starting indices")
76 .Arg(
"ends",
"(*Tuple(int)*): list of ending indices")
77 .TensorInferenceFunction([](
const OperatorDef& def,
78 const vector<TensorShape>& in) {
82 return vector<TensorShape>();
84 auto const& data = in[0];
86 ArgumentHelper helper(def);
87 auto starts = helper.GetRepeatedArgument<
int>(
"starts", vector<int>());
88 auto ends = helper.GetRepeatedArgument<
int>(
"ends", vector<int>());
89 vector<int> dst_sizes(data.dims_size());
91 for (
int i = 0; i < data.dims_size(); ++i) {
92 if (i >= starts.size()) {
95 if (data.dims_size() > 0) {
96 auto start = starts[i];
99 start = data.dims(i) + 1 + start;
102 end = data.dims(i) + 1 + end;
104 dst_sizes[i] = end - start;
109 return vector<TensorShape>{
110 CreateTensorShape(dst_sizes, data.data_type())};
112 .Output(0,
"Y",
"(*Tensor*): sliced output tensor")
113 .InheritOnnxSchema();
115 GRADIENT_OPERATOR_SCHEMA(SliceGradient);
118 struct GetSliceGradient :
public GradientMakerBase {
119 using GradientMakerBase::GradientMakerBase;
120 vector<OperatorDef> GetGradientDefs()
override {
121 if (def_.input_size() > 1) {
122 return vector<OperatorDef>{CreateOperatorDef(
125 std::vector<string>{I(0), I(1), I(2), GO(0)},
126 std::vector<string>{GI(0)})};
128 return vector<OperatorDef>{CreateOperatorDef(
131 std::vector<string>{I(0), GO(0)},
132 std::vector<string>{GI(0)})};
137 REGISTER_GRADIENT(Slice, GetSliceGradient);
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...