slice_op.cc 13.0 KB
Newer Older
W
whs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/slice_op.h"
#include <algorithm>
17
#include <memory>
18
#include <string>
W
whs 已提交
19 20 21 22 23 24 25 26 27 28 29
#include <vector>

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

class SliceOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

30 31 32 33 34 35
  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true,
                      "Input (Input) of slice op should not be null.");

    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      "Output (Out) of slice op should not be null.");
W
whs 已提交
36 37

    auto in_dims = ctx->GetInputDim("Input");
38 39
    PADDLE_ENFORCE_LT(in_dims.size(), 7,
                      "The rank of input should be less than 7.");
W
whs 已提交
40
    framework::DDim out_dims(in_dims);
41

W
whs 已提交
42 43 44
    auto axes = ctx->Attrs().Get<std::vector<int>>("axes");
    auto starts = ctx->Attrs().Get<std::vector<int>>("starts");
    auto ends = ctx->Attrs().Get<std::vector<int>>("ends");
45
    auto infer_flags = ctx->Attrs().Get<std::vector<int>>("infer_flags");
H
Hongyu Liu 已提交
46
    auto decrease_axis = ctx->Attrs().Get<std::vector<int>>("decrease_axis");
W
whs 已提交
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    auto starts_size = starts.size();
    auto ends_size = ends.size();
    if (infer_flags.empty()) {
      // Initialize infer_flags with 1.
      // To be compatible with other op tests in which infer_flags is not set.
      infer_flags = std::vector<int>(axes.size(), 1);
    }

    if (ctx->HasInputs("StartsTensorList")) {
      auto StartsTensorList = ctx->Inputs("StartsTensorList");
      PADDLE_ENFORCE_GT(StartsTensorList.size(), 0,
                        "StartsTensorList size can't be zero");
      starts_size = StartsTensorList.size();
    }
    if (ctx->HasInputs("EndsTensorList")) {
      auto EndsTensorList = ctx->Inputs("EndsTensorList");
      PADDLE_ENFORCE_GT(EndsTensorList.size(), 0,
                        "EndsTensorList size can't be zero");
      ends_size = EndsTensorList.size();
    }

    if (ctx->HasInput("StartsTensor") == false) {
      PADDLE_ENFORCE_EQ(
          starts_size, axes.size(),
          "The size of starts must be equal to the size of axes.");
    }
    if (ctx->HasInput("EndsTensor") == false) {
      PADDLE_ENFORCE_EQ(ends_size, axes.size(),
                        "The size of ends must be equal to the size of axes.");
    }

W
whs 已提交
79 80
    int dim_value, start, end;
    for (size_t i = 0; i < axes.size(); ++i) {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
      PADDLE_ENFORCE_LT(static_cast<int>(axes[i]), in_dims.size(),
                        "The index of dimension in axes must be less "
                        "than the size of input shape.");
      if (infer_flags[i] == -1) {
        out_dims[axes[i]] = -1;
      } else {
        // infer out_dim shape
        dim_value = out_dims[axes[i]];
        if (dim_value > 0) {
          start = starts[i] < 0 ? (starts[i] + dim_value) : starts[i];
          end = ends[i] < 0 ? (ends[i] + dim_value) : ends[i];
          start = std::max(start, 0);
          end = std::max(end, 0);
          end = std::min(end, dim_value);
          PADDLE_ENFORCE_GT(end, start, "end should greater than start");
          out_dims[axes[i]] = end - start;
        }
H
Hongyu Liu 已提交
98
      }
W
whs 已提交
99
    }
H
Hongyu Liu 已提交
100 101 102 103
    // generate new shape
    if (decrease_axis.size() > 0) {
      std::vector<int> new_out_shape;
      for (size_t i = 0; i < decrease_axis.size(); ++i) {
104
        if (ctx->IsRuntime() && infer_flags[i] != -1) {
H
Hongyu Liu 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
          PADDLE_ENFORCE_EQ(out_dims[decrease_axis[i]], 1,
                            "decrease dim should be 1");
        }
        out_dims[decrease_axis[i]] = 0;
      }

      for (int i = 0; i < out_dims.size(); ++i) {
        if (out_dims[i] != 0) {
          new_out_shape.push_back(out_dims[i]);
        }
      }
      if (new_out_shape.size() == 0) {
        new_out_shape.push_back(1);
      }

      out_dims = framework::make_ddim(new_out_shape);
    }
W
whs 已提交
122
    ctx->SetOutputDim("Out", out_dims);
J
jerrywgz 已提交
123 124 125
    if (axes[0] != 0) {
      ctx->ShareLoD("Input", /*->*/ "Out");
    }
W
whs 已提交
126 127 128 129
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
130
      const framework::ExecutionContext &ctx) const override {
131 132 133
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
        ctx.device_context());
134 135 136 137 138 139 140 141 142 143 144 145
  }
  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "StartsTensor" || var_name == "EndsTensor") {
      return expected_kernel_type;
    }
    if (var_name == "StartsTensorList" || var_name == "EndsTensorList") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
W
whs 已提交
146 147 148 149 150 151
  }
};

class SliceOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    AddInput("Input", "(Tensor) Tensor of data to extract slices from.");
    AddInput("StartsTensor",
             "(Tensor<int32>, optional) If provided, slice will use this."
             "It has the highest priority of StartsTensor, StartsTensorList "
             "and attr(starts).")
        .AsDispensable();
    AddInput("EndsTensor",
             "(Tensor<int32>, optional) If provided, slice will use this."
             "It has the highest priority of EndsTensor, EndsTensorList and "
             "attr(ends).")
        .AsDispensable();
    AddInput(
        "StartsTensorList",
        "(vector<Tensor<int32>>, optional) If provided, slice will use this."
        "The shape of the tensor in vector MUST BE [1]."
        "It has higher priority compare with attr(starts).")
        .AsDuplicable()
        .AsDispensable();
    AddInput(
        "EndsTensorList",
        "(vector<Tensor<int32>>, optional) If provided, slice will use this."
        "The shape of the tensor in vector MUST BE [1]."
        "It has higher priority compare with attr(ends).")
        .AsDuplicable()
        .AsDispensable();
W
whs 已提交
177 178 179 180 181 182 183
    AddOutput("Out", "Sliced data tensor.");
    AddAttr<std::vector<int>>(
        "axes",
        "(list<int>) Axes that `starts` and `ends` apply to. It's optional."
        "If not present, will be treated as [0, 1, ..., len(`starts`) - 1].");
    AddAttr<std::vector<int>>(
        "starts",
184 185 186 187 188
        "(list<int>) Starting indices of corresponding axis in `axes`")
        .SetDefault({});
    AddAttr<std::vector<int>>(
        "ends", "(list<int>) Ending indices of corresponding axis in `axes`.")
        .SetDefault({});
W
whs 已提交
189
    AddAttr<std::vector<int>>(
190 191
        "infer_flags", "(list<int>) Flags of inferring dims in attributes.")
        .SetDefault({});
H
Hongyu Liu 已提交
192 193
    AddAttr<std::vector<int>>("decrease_axis", "(list<int>) decrease_axis")
        .SetDefault({});
W
whs 已提交
194 195 196 197 198
    AddComment(R"DOC(
Slice Operator.

Produces a slice of the input tensor along multiple axes. Similar to numpy:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
199
Slice uses `axes`, `starts` and `ends` attributes to specify the start and
W
whs 已提交
200
end dimension for each axis in the list of axes, it uses this information
201 202
to slice the input data tensor. If a negative value is passed for any of
the start or end indices, it represents number of elements before the end
W
whs 已提交
203
of that dimension. If the value passed to start or end is larger than
204 205
the n (the number of elements in this dimension), it represents n.
For slicing to the end of a dimension with unknown size, it is recommended
206
to pass in INT_MAX. The size of axes must be equal to starts\' and ends\'.
207 208
Following examples will explain how slice works:

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
.. code-block:: text

    Case1:
        Given:
            data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]
            axes = [0, 1]
            starts = [1, 0]
            ends = [2, 3]
        Then:
            result = [ [5, 6, 7], ]

    Case2:
        Given:
            data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]
            starts = [0, 1]
            ends = [-1, 1000]
        Then:
            result = [ [2, 3, 4], ]
W
whs 已提交
227 228 229 230
)DOC");
  }
};

231 232 233 234
class SliceOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

235 236 237 238
  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(ctx->HasInput("Input"), true, "Input should not be null");
    PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName("Out")), true,
                      "Input(Out@GRAD) should not be null");
239 240 241 242 243 244
    auto x_dims = ctx->GetInputDim("Input");
    auto x_grad_name = framework::GradVarName("Input");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
  }
245
  framework::OpKernelType GetExpectedKernelType(
246
      const framework::ExecutionContext &ctx) const override {
247 248 249
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
250 251 252 253 254 255 256 257 258 259 260 261
  }
  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "StartsTensor" || var_name == "EndsTensor") {
      return expected_kernel_type;
    }
    if (var_name == "StartsTensorList" || var_name == "EndsTensorList") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
262
  }
263 264
};

H
hong 已提交
265 266
template <typename T>
class SliceOpGradMaker : public framework::SingleGradOpMaker<T> {
267
 public:
H
hong 已提交
268
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
269 270

 protected:
271
  void Apply(GradOpPtr<T> bind) const override {
H
hong 已提交
272
    bind->SetInput("Input", this->Input("Input"));
H
hong 已提交
273 274 275 276 277 278 279 280 281 282 283 284
    if (this->HasInput("StartsTensor")) {
      bind->SetInput("StartsTensor", this->Input("StartsTensor"));
    }
    if (this->HasInput("EndsTensor")) {
      bind->SetInput("EndsTensor", this->Input("EndsTensor"));
    }
    if (this->HasInput("StartsTensorList")) {
      bind->SetInput("StartsTensorList", this->Input("StartsTensorList"));
    }
    if (this->HasInput("EndsTensorList")) {
      bind->SetInput("EndsTensorList", this->Input("EndsTensorList"));
    }
H
hong 已提交
285 286 287
    bind->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    bind->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input"));
    bind->SetAttrMap(this->Attrs());
288 289 290 291
    bind->SetType("slice_grad");
  }
};

292 293 294 295 296 297
template <typename T>
class SliceDoubleOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
298
  void Apply(GradOpPtr<T> bind) const override {
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    if (this->HasInput("StartsTensor")) {
      bind->SetInput("StartsTensor", this->Input("StartsTensor"));
    }
    if (this->HasInput("EndsTensor")) {
      bind->SetInput("EndsTensor", this->Input("EndsTensor"));
    }
    if (this->HasInput("StartsTensorList")) {
      bind->SetInput("StartsTensorList", this->Input("StartsTensorList"));
    }
    if (this->HasInput("EndsTensorList")) {
      bind->SetInput("EndsTensorList", this->Input("EndsTensorList"));
    }
    bind->SetInput("Input", this->OutputGrad(framework::GradVarName("Input")));
    bind->SetOutput("Out", this->InputGrad(framework::GradVarName("Out")));
    bind->SetAttrMap(this->Attrs());
    bind->SetType("slice");
  }
};

Z
Zeng Jinle 已提交
318 319
DECLARE_NO_NEED_BUFFER_VARS_INFERER(SliceOpGradNoNeedBufferVarsInference,
                                    "Input");
320

W
whs 已提交
321 322 323 324 325
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(slice, ops::SliceOp, ops::SliceOpMaker,
H
hong 已提交
326 327
                  ops::SliceOpGradMaker<paddle::framework::OpDesc>,
                  ops::SliceOpGradMaker<paddle::imperative::OpBase>);
328
REGISTER_OPERATOR(slice_grad, ops::SliceOpGrad,
329 330
                  ops::SliceDoubleOpGradMaker<paddle::framework::OpDesc>,
                  ops::SliceDoubleOpGradMaker<paddle::imperative::OpBase>,
331
                  ops::SliceOpGradNoNeedBufferVarsInference);
W
whs 已提交
332 333 334 335 336 337

REGISTER_OP_CPU_KERNEL(
    slice, ops::SliceKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SliceKernel<paddle::platform::CPUDeviceContext, int64_t>,
    ops::SliceKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SliceKernel<paddle::platform::CPUDeviceContext, double>);
338 339 340 341 342 343

REGISTER_OP_CPU_KERNEL(
    slice_grad, ops::SliceGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::SliceGradKernel<paddle::platform::CPUDeviceContext, int64_t>,
    ops::SliceGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SliceGradKernel<paddle::platform::CPUDeviceContext, double>);