strided_slice_op.cc 16.4 KB
Newer Older
W
wangchaochaohu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2019 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/strided_slice_op.h"
#include <algorithm>
#include <memory>
18
#include <string>
W
wangchaochaohu 已提交
19
#include <vector>
20
#include "paddle/fluid/operators/slice_op.h"
W
wangchaochaohu 已提交
21 22 23 24 25 26 27 28 29 30

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

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

31
  void InferShape(framework::InferShapeContext *ctx) const override {
32 33
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "StridedSlice");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "StridedSlice");
34 35 36 37 38 39 40
    auto input_var_type = ctx->GetInputsVarType("Input")[0];
    if (input_var_type == framework::proto::VarType::LOD_TENSOR_ARRAY) {
      if (ctx->IsRuntime()) {
        // shape is determined by Runtime.
        return;
      }
    }
W
wangchaochaohu 已提交
41
    auto in_dims = ctx->GetInputDim("Input");
42 43 44 45 46 47
    PADDLE_ENFORCE_LT(
        in_dims.size(), 7,
        platform::errors::InvalidArgument(
            "The dimension of StridedSlice operator's input should be less "
            "than 7, but received dimension is %d.",
            in_dims.size()));
48 49 50 51 52 53 54 55 56

    auto starts_int = ctx->Attrs().Get<std::vector<int>>("starts");
    auto ends_int = ctx->Attrs().Get<std::vector<int>>("ends");
    auto strides_int = ctx->Attrs().Get<std::vector<int>>("strides");

    std::vector<int64_t> starts(starts_int.begin(), starts_int.end());
    std::vector<int64_t> ends(ends_int.begin(), ends_int.end());
    std::vector<int64_t> strides(strides_int.begin(), strides_int.end());

W
wangchaochaohu 已提交
57
    auto axes = ctx->Attrs().Get<std::vector<int>>("axes");
58
    auto infer_flags = ctx->Attrs().Get<std::vector<int>>("infer_flags");
59
    auto decrease_axis = ctx->Attrs().Get<std::vector<int>>("decrease_axis");
W
wangchaochaohu 已提交
60

61 62 63
    auto starts_size = starts.size();
    auto ends_size = ends.size();
    auto strides_size = strides.size();
W
wangchaochaohu 已提交
64

65 66
    if (ctx->HasInputs("StartsTensorList")) {
      auto StartsTensorList = ctx->Inputs("StartsTensorList");
67 68 69 70
      PADDLE_ENFORCE_GT(
          StartsTensorList.size(), 0,
          platform::errors::InvalidArgument(
              "StridedSlice operator's StartsTensorList is empty."));
71 72 73 74
      starts_size = StartsTensorList.size();
    }
    if (ctx->HasInputs("EndsTensorList")) {
      auto EndsTensorList = ctx->Inputs("EndsTensorList");
75 76 77 78
      PADDLE_ENFORCE_GT(
          EndsTensorList.size(), 0,
          platform::errors::InvalidArgument(
              "StridedSlice operator's EndsTensorList is empty."));
79 80 81 82
      ends_size = EndsTensorList.size();
    }
    if (ctx->HasInputs("StridesTensorList")) {
      auto StridesTensorList = ctx->Inputs("StridesTensorList");
83 84 85 86
      PADDLE_ENFORCE_GT(
          StridesTensorList.size(), 0,
          platform::errors::InvalidArgument(
              "StridedSlice operator's StridesTensorList is empty."));
87 88 89 90 91 92 93 94
      strides_size = StridesTensorList.size();
    }

    auto tensor_input = false;
    if (ctx->HasInput("EndsTensor") || ctx->HasInput("StartsTensor") ||
        ctx->HasInput("StridesTensor")) {
      tensor_input = true;
    }
W
wangchaochaohu 已提交
95
    if (!ctx->HasInput("EndsTensor")) {
96 97 98 99 100 101 102
      PADDLE_ENFORCE_EQ(
          ends_size, axes.size(),
          platform::errors::InvalidArgument(
              "The size of ends attribute in StridedSlice operator is not "
              "equal to the size of axes attribute. The ends attribute's size "
              "is %d, axes attribute's size is %d.",
              ends_size, axes.size()));
103
    }
W
wangchaochaohu 已提交
104
    if (!ctx->HasInput("StartsTensor")) {
105 106
      PADDLE_ENFORCE_EQ(
          starts_size, axes.size(),
107 108 109 110 111
          platform::errors::InvalidArgument(
              "The size of starts attribute in StridedSlice operator is not "
              "equal to the size of axes attribute. The starts attribute's "
              "size is %d, axes attribute's size is %d.",
              starts_size, axes.size()));
112
    }
W
wangchaochaohu 已提交
113
    if (!ctx->HasInput("StridesTensor")) {
114 115
      PADDLE_ENFORCE_EQ(
          strides_size, axes.size(),
116 117 118 119 120
          platform::errors::InvalidArgument(
              "The size of strides attribute in StridedSlice operator is not "
              "equal to the size of axes attribute. The strides attribute's "
              "size is %d, axes attribute's size is %d.",
              strides_size, axes.size()));
121
    }
W
wangchaochaohu 已提交
122 123
    // we need to analysis strided slice op is valid for
    // the parameter that we get from python front
124
    std::vector<int64_t> out_dims_vector(in_dims.size(), -1);
125 126
    if (!tensor_input) {
      StridedSliceOutDims(starts, ends, strides, axes, infer_flags, in_dims,
127 128
                          decrease_axis, out_dims_vector.data(), axes.size(),
                          true);
W
wangchaochaohu 已提交
129 130
    }
    framework::DDim out_dims(framework::make_ddim(out_dims_vector));
131 132
    // generate new shape
    if (decrease_axis.size() > 0) {
133
      std::vector<int64_t> new_out_shape;
134 135 136
      for (size_t i = 0; i < decrease_axis.size(); ++i) {
        if (ctx->IsRuntime() && infer_flags[i] != -1) {
          PADDLE_ENFORCE_EQ(out_dims[decrease_axis[i]], 1,
137 138 139 140
                            platform::errors::InvalidArgument(
                                "the size of decrease dimension should be 1, "
                                "but received %d.",
                                out_dims[decrease_axis[i]]));
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        }
        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
wangchaochaohu 已提交
156 157 158 159 160 161
    ctx->SetOutputDim("Out", out_dims);
    ctx->ShareLoD("Input", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
162
      const framework::ExecutionContext &ctx) const override {
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    auto *in_var = ctx.InputVar("Input");
    auto is_in_var_array = in_var->IsType<framework::LoDTensorArray>();
    if (is_in_var_array) {
      auto &tensor_array = in_var->Get<framework::LoDTensorArray>();
      for (auto &tensor : tensor_array) {
        if (!platform::is_cuda_pinned_place(tensor.place())) {
          PADDLE_ENFORCE_EQ(
              platform::is_same_place(tensor.place(),
                                      ctx.device_context().GetPlace()),
              true,
              platform::errors::InvalidArgument(
                  "Place of context is %s. Place of input tensor is %s. They "
                  "are should be same, but reveived different place.",
                  string::to_string(ctx.device_context().GetPlace()),
                  string::to_string(tensor.place())));
        }
      }
      return framework::OpKernelType(
          OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
          ctx.device_context());
    }
184 185 186 187 188
    // NOTE: cuda pinned tensor need to copy its data to target place
    auto in_tensor = ctx.Input<Tensor>("Input");
    if (platform::is_cuda_pinned_place(in_tensor->place())) {
      return framework::OpKernelType(in_tensor->type(), ctx.device_context());
    }
189 190
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
191
        in_tensor->place());
W
wangchaochaohu 已提交
192
  }
193 194 195 196 197 198 199 200 201 202 203 204 205 206
  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" ||
        var_name == "StridesTensor") {
      return expected_kernel_type;
    }
    if (var_name == "StartsTensorList" || var_name == "EndsTensorList" ||
        var_name == "StridesTensorList") {
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
W
wangchaochaohu 已提交
207 208
};

209 210 211 212 213 214 215 216
class StridedSliceOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext *ctx) const override {
    ctx->SetOutputType("Out", ctx->GetInputType("Input"));
    ctx->SetOutputDataType("Out", ctx->GetInputDataType("Input"));
  }
};

W
wangchaochaohu 已提交
217 218 219 220
class StridedSliceOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Input", "Tensor of data to extract slices from.");
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    AddOutput("Out", "Strided Sliced data tensor.");

    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(
        "StridesTensor",
        "(Tensor<int32>, optional) If provided, slice will use this."
        "It has the highest priority of StridesTensor, StridesTensorList 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();
    AddInput(
        "StridesTensorList",
        "(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(strides).")
        .AsDuplicable()
        .AsDispensable();
W
wangchaochaohu 已提交
260
    AddAttr<std::vector<int>>(
261
        "axes", "(list<int>) Axes that `starts` and `ends` apply to.");
W
wangchaochaohu 已提交
262
    AddAttr<std::vector<int>>(
263 264
        "starts", "(list<int>) Start indices for the strided slice start.")
        .SetDefault({});
W
wangchaochaohu 已提交
265
    AddAttr<std::vector<int>>("ends",
266 267
                              "(list<int>) End indices the tensor slice end")
        .SetDefault({});
W
wangchaochaohu 已提交
268
    AddAttr<std::vector<int>>(
269 270 271 272 273
        "strides", "(list<int> Stride step from the start to the end)")
        .SetDefault({});
    AddAttr<std::vector<int>>(
        "infer_flags", "(list<int>) Flags of inferring dims in attributes.")
        .SetDefault({});
274 275
    AddAttr<std::vector<int>>("decrease_axis", "(list<int>) decrease_axis")
        .SetDefault({});
W
wangchaochaohu 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    AddComment(R"DOC(
Strided Slice Operator.
Instead of calling this op directly most users will want to use the
NumPy-style slicing syntax.
For Example:
data = fluid.layers.fill_constant(shape=[3, 3], value=0, dtype='int64')
y = fluid.layers.strided_slice(data, [0, 1], [1,0], [2, 3], [1, 1])
)DOC");
  }
};

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

291
  void InferShape(framework::InferShapeContext *ctx) const override {
292 293 294 295 296
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input",
                   "StridedSliceGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   "Out@GRAD", "StridedSliceGrad");

297 298 299 300 301 302 303
    auto input_var_type = ctx->GetInputsVarType("Input")[0];
    if (input_var_type == framework::proto::VarType::LOD_TENSOR_ARRAY) {
      if (ctx->IsRuntime()) {
        // shape is determined by Runtime
        return;
      }
    }
W
wangchaochaohu 已提交
304 305 306 307 308 309 310 311
    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);
    }
  }

  framework::OpKernelType GetExpectedKernelType(
312
      const framework::ExecutionContext &ctx) const override {
313 314 315
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.GetPlace());
W
wangchaochaohu 已提交
316
  }
317 318 319
  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
320 321
    if (var_name == "StartsTensor" || var_name == "EndsTensor" ||
        var_name == "StridesTensor") {
322 323
      return expected_kernel_type;
    }
324 325
    if (var_name == "StartsTensorList" || var_name == "EndsTensorList" ||
        var_name == "StridesTensorList") {
326 327 328 329 330
      return expected_kernel_type;
    }
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   tensor.place(), tensor.layout());
  }
W
wangchaochaohu 已提交
331 332
};

H
hong 已提交
333 334
template <typename T>
class StridedSliceOpGradMaker : public framework::SingleGradOpMaker<T> {
W
wangchaochaohu 已提交
335
 public:
H
hong 已提交
336
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
W
wangchaochaohu 已提交
337 338

 protected:
339
  void Apply(GradOpPtr<T> bind) const override {
H
hong 已提交
340 341 342 343 344 345 346 347 348 349
    bind->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    bind->SetInput("Input", this->Input("Input"));
    bind->SetInput("StartsTensor", this->Input("StartsTensor"));
    bind->SetInput("EndsTensor", this->Input("EndsTensor"));
    bind->SetInput("StridesTensor", this->Input("StridesTensor"));
    bind->SetInput("StartsTensorList", this->Input("StartsTensorList"));
    bind->SetInput("EndsTensorList", this->Input("EndsTensorList"));
    bind->SetInput("StridesTensorList", this->Input("StridesTensorList"));
    bind->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input"));
    bind->SetAttrMap(this->Attrs());
W
wangchaochaohu 已提交
350 351 352
    bind->SetType("strided_slice_grad");
  }
};
353 354 355 356 357 358 359 360 361 362
class StridedSliceGradOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext *ctx) const override {
    ctx->SetOutputType(framework::GradVarName("Input"),
                       ctx->GetInputType(framework::GradVarName("Out")));
    ctx->SetOutputDataType(
        framework::GradVarName("Input"),
        ctx->GetInputDataType(framework::GradVarName("Out")));
  }
};
W
wangchaochaohu 已提交
363

364
DECLARE_NO_NEED_BUFFER_VARS_INFERER(StridedSliceOpGradNoNeedBufferVarsInferer,
Z
Zeng Jinle 已提交
365
                                    "Input");
W
wangchaochaohu 已提交
366 367 368 369 370 371

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(strided_slice, ops::StridedSliceOp, ops::StridedSliceOpMaker,
H
hong 已提交
372
                  ops::StridedSliceOpGradMaker<paddle::framework::OpDesc>,
373 374 375
                  ops::StridedSliceOpGradMaker<paddle::imperative::OpBase>,
                  ops::StridedSliceOpVarTypeInference);

W
wangchaochaohu 已提交
376
REGISTER_OPERATOR(strided_slice_grad, ops::StridedSliceOpGrad,
377 378
                  ops::StridedSliceOpGradNoNeedBufferVarsInferer,
                  ops::StridedSliceGradOpVarTypeInference);
W
wangchaochaohu 已提交
379 380 381

REGISTER_OP_CPU_KERNEL(
    strided_slice,
382
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, bool>,
W
wangchaochaohu 已提交
383 384 385
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, int>,
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, int64_t>,
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, float>,
386 387
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext, double>,
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext,
388
                            paddle::platform::complex<float>>,
389
    ops::StridedSliceKernel<paddle::platform::CPUDeviceContext,
390
                            paddle::platform::complex<double>>);
W
wangchaochaohu 已提交
391 392 393

REGISTER_OP_CPU_KERNEL(
    strided_slice_grad,
394
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, bool>,
W
wangchaochaohu 已提交
395 396 397
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, int>,
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, int64_t>,
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, float>,
398 399
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext, double>,
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext,
400
                                paddle::platform::complex<float>>,
401
    ops::StridedSliceGradKernel<paddle::platform::CPUDeviceContext,
402
                                paddle::platform::complex<double>>);