flatten_op.cc 17.4 KB
Newer Older
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
B
Bai Yifan 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

15
#include "paddle/fluid/operators/flatten_op.h"
16

17 18 19
#include <memory>
#include <string>
#include <unordered_map>
B
Bai Yifan 已提交
20
#include <vector>
21

22
#include "paddle/fluid/framework/infershape_utils.h"
B
Bai Yifan 已提交
23
#include "paddle/fluid/framework/op_registry.h"
24
#include "paddle/phi/core/infermeta_utils.h"
25
#include "paddle/phi/infermeta/backward.h"
26
#include "paddle/phi/infermeta/unary.h"
B
Bai Yifan 已提交
27 28 29 30

namespace paddle {
namespace operators {

31
class FlattenOp : public framework::OperatorWithKernel {
B
Bai Yifan 已提交
32
 public:
33 34 35
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
36 37
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Flatten");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Flatten");
B
Bai Yifan 已提交
38 39
    const auto &axis = ctx->Attrs().Get<int>("axis");
    const auto &in_dims = ctx->GetInputDim("X");
40 41
    PADDLE_ENFORCE_GE(axis,
                      0,
42 43
                      platform::errors::InvalidArgument(
                          "The axis should be greater than or equal to 0."));
44 45 46 47 48 49 50
    if (in_dims.size() > 0) {
      PADDLE_ENFORCE_LE(
          axis,
          in_dims.size(),
          platform::errors::InvalidArgument(
              "The axis should be less than or equal to input tensor's rank."));
    }
B
Bai Yifan 已提交
51 52

    const auto &out_dims = GetOutputShape(axis, in_dims);
53
    ctx->SetOutputDim("Out", phi::make_ddim(out_dims));
B
Bai Yifan 已提交
54 55 56 57 58 59 60 61 62
    if (in_dims[0] == out_dims[0]) {
      // Only pass LoD when the first dimension of output and Input(X)
      // are the same.
      ctx->ShareLoD("X", "Out");
    }
  }

  static std::vector<int32_t> GetOutputShape(const int axis,
                                             const framework::DDim &in_dims) {
63 64 65 66
    if (in_dims.size() == 0) {
      return {1};
    }

B
Bai Yifan 已提交
67 68 69
    int64_t outer = 1, inner = 1;
    for (int i = 0; i < in_dims.size(); ++i) {
      if (i < axis) {
D
danleifeng 已提交
70 71 72 73 74
        if (in_dims[i] == -1 || outer == -1) {
          outer = -1;
        } else {
          outer *= in_dims[i];
        }
B
Bai Yifan 已提交
75
      } else {
D
danleifeng 已提交
76 77 78 79 80
        if (in_dims[i] == -1 || inner == -1) {
          inner = -1;
        } else {
          inner *= in_dims[i];
        }
B
Bai Yifan 已提交
81 82 83 84 85 86 87 88
      }
    }
    std::vector<int32_t> out_shape(2);
    out_shape[0] = outer;
    out_shape[1] = inner;
    return out_shape;
  }

89
 protected:
90
  phi::KernelKey GetExpectedKernelType(
91
      const framework::ExecutionContext &ctx) const override {
92 93
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
94
    return phi::KernelKey(input_data_type, ctx.GetPlace());
B
Bai Yifan 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  }
};

class FlattenOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) A tensor of rank >= axis.");
    AddOutput("Out",
              "A 2D tensor is reshaped input tensor. The input dimensions"
              "up to axis are flattened to the outer dimension of the output"
              "and the remaining input dimensions are flattened into the inner"
              "dimension of the output.");
    AddAttr<int>("axis",
                 "(int)"
                 "Indicate up to which input dimensions (exclusive) should be"
                 "flattened to the outer dimension of the output. The value"
                 "for axis must be in the range [0, R], where R is the rank of"
                 "the input tensor. When axis = 0, the shape of the output"
                 "tensor is (1, (d_0 X d_1 ... d_n), where the shape of the"
                 "input tensor is (d_0, d_1, ... d_n).")
        .SetDefault(1);
116 117
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
118 119
        .SetDefault(false)
        .AsExtra();
120 121 122 123
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
124 125
        .InEnum({"float32", "bfloat16"})
        .AsExtra();
B
Bai Yifan 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    AddComment(R"DOC(
Flatten Operator

Flattens the input tensor into a 2D matrix.

Examples:
Case 1:
  Given
    X.shape = (3, 100, 100, 4)
  and
    axis = 2
  We get:
    Out.shape = (3 * 100, 4 * 100)

Case 2:
  Given
    X.shape = (3, 100, 100, 4)
  and
    axis = 0
  We get:
    Out.shape = (1, 3 * 100 * 100 * 4)
)DOC");
  }
};

151
class FlattenGradOp : public framework::OperatorWithKernel {
B
Bai Yifan 已提交
152
 public:
153 154 155
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *context) const override {
B
Bai Yifan 已提交
156 157 158 159 160
    context->SetOutputDim(framework::GradVarName("X"),
                          context->GetInputDim("X"));
    context->ShareLoD("X", framework::GradVarName("X"));
  }

161
 protected:
162
  phi::KernelKey GetExpectedKernelType(
163
      const framework::ExecutionContext &ctx) const override {
164 165
    auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
166
    return phi::KernelKey(input_data_type, ctx.GetPlace());
167 168 169 170 171 172 173 174
  }
};

template <typename T>
class FlattenGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

175
  void Apply(GradOpPtr<T> grad_op) const override {
176 177 178 179 180
    grad_op->SetType("flatten_grad");
    grad_op->SetInput("X", this->Input("X"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
B
Bai Yifan 已提交
181 182 183
  }
};

184 185 186 187 188
// FIXME(zcd): flatten2 adds an intermediate output(XShape) based on flatten,
// the XShape is used to carry the shape and lod of X which will be used in
// flatten_grad, in this way, the framework can reuse the memory of X
// immediately the flatten2_op is finished.
// Considering compatibility issues, we could not fix flatten2_op
189
class Flatten2Op : public framework::OperatorWithKernel {
190
 public:
191 192 193
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
194 195
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Flatten2");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Flatten2");
196
    const auto &axis = ctx->Attrs().Get<int>("axis");
197
    const auto &in_dims = ctx->GetInputDim("X");
198 199
    PADDLE_ENFORCE_GE(axis,
                      0,
200 201
                      platform::errors::InvalidArgument(
                          "The axis should be greater than or equal to 0."));
202
    PADDLE_ENFORCE_LE(
203 204
        axis,
        in_dims.size(),
205 206
        platform::errors::InvalidArgument(
            "The axis should be less than or equal to input tensor's rank"));
207 208

    const auto &out_dims = FlattenOp::GetOutputShape(axis, in_dims);
209
    ctx->SetOutputDim("Out", phi::make_ddim(out_dims));
210 211 212 213 214
    if (in_dims[0] == out_dims[0]) {
      // Only pass LoD when the first dimension of output and Input(X)
      // are the same.
      ctx->ShareLoD("X", "Out");
    }
215 216
    if (!ctx->HasOutput("XShape")) return;
    // OP_INOUT_CHECK(ctx->HasOutput("XShape"), "Output", "XShape", "Flatten2");
217 218 219 220 221
    std::vector<int64_t> xshape_dims(in_dims.size() + 1);
    xshape_dims[0] = 0;
    for (int i = 0; i < in_dims.size(); ++i) {
      xshape_dims[i + 1] = in_dims[i];
    }
222
    ctx->SetOutputDim("XShape", phi::make_ddim(xshape_dims));
223 224
    ctx->ShareLoD("X", "XShape");
  }
225

226
  phi::KernelKey GetExpectedKernelType(
227 228 229
      const framework::ExecutionContext &ctx) const override {
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
230
    return phi::KernelKey(input_data_type, ctx.GetPlace());
231
  }
232 233 234 235 236 237 238 239 240
};

class Flatten2OpMaker : public FlattenOpMaker {
 public:
  void Make() override {
    FlattenOpMaker::Make();
    AddOutput("XShape",
              "XShape is just used to store the shape and lod of X, which will "
              "be used in FlattenGradOp.")
241 242
        .AsIntermediate()
        .AsExtra();
243 244 245
  }
};

H
hong 已提交
246 247
template <typename T>
class Flatten2GradOpMaker : public framework::SingleGradOpMaker<T> {
248
 public:
H
hong 已提交
249
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
250

251
  void Apply(GradOpPtr<T> grad_op) const override {
252
    grad_op->SetType("flatten2_grad");
H
hong 已提交
253 254 255 256
    grad_op->SetInput("XShape", this->Output("XShape"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
257 258 259
  }
};

260
class Flatten2GradOp : public framework::OperatorWithKernel {
261
 public:
262 263 264
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *context) const override {
265 266 267 268 269
    OP_INOUT_CHECK(
        context->HasInput("XShape"), "Input", "XShape", "Flatten2Grad");
    OP_INOUT_CHECK(context->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
270
                   "Flatten2Grad");
271
    auto xshape_dims = context->GetInputDim("XShape");
272
    auto x_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size());
273 274 275 276
    context->SetOutputDim(framework::GradVarName("X"), x_dims);
    context->ShareLoD("XShape", framework::GradVarName("X"));
  }

277
 protected:
278
  phi::KernelKey GetExpectedKernelType(
279
      const framework::ExecutionContext &ctx) const override {
280 281
    auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
282
    return phi::KernelKey(input_data_type, ctx.GetPlace());
283 284 285
  }
};

286 287 288 289 290
class FlattenContiguousRangeOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "FlattenContiguousRange");
291 292
    OP_INOUT_CHECK(
        ctx->HasOutput("Out"), "Output", "Out", "FlattenContiguousRange");
293 294 295
    const auto &start_axis = ctx->Attrs().Get<int>("start_axis");
    const auto &stop_axis = ctx->Attrs().Get<int>("stop_axis");

296 297 298 299 300 301 302 303
    // Construct MetaTensor for InferMeta Func
    using CompatMetaTensor = framework::CompatMetaTensor;
    CompatMetaTensor x(ctx->GetInputVarPtrs("X")[0], ctx->IsRuntime());
    CompatMetaTensor out(ctx->GetOutputVarPtrs("Out")[0], ctx->IsRuntime());
    std::unique_ptr<CompatMetaTensor> xshape(nullptr);
    if (ctx->HasOutput("XShape")) {
      xshape = std::move(std::unique_ptr<CompatMetaTensor>(new CompatMetaTensor(
          ctx->GetOutputVarPtrs("XShape")[0], ctx->IsRuntime())));
304
    }
305 306
    phi::FlattenWithXShapeInferMeta(
        x, start_axis, stop_axis, &out, xshape.get());
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
  }
};

class FlattenContiguousRangeOpMaker : public FlattenOpMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) A tensor of rank >= axis.");
    AddOutput("Out",
              "A 2D tensor is reshaped input tensor. The input dimensions"
              "up to axis are flattened to the outer dimension of the output"
              "and the remaining input dimensions are flattened into the inner"
              "dimension of the output.");
    AddAttr<int>("start_axis",
                 "(int)"
                 "Indicate the input start dimension (exclusive) to flatten")
        .SetDefault(1);
    AddAttr<int>("stop_axis",
                 "(int)"
                 "Indicate the input stop dimension (exclusive) to flatten")
        .SetDefault(1);
    AddComment(R"DOC(
Flatten Operator

Flattens the input tensor into a new matrix according to start_axis and stop_axis.

Examples:
Case 1:
  Given
    X.shape = (3, 100, 100, 4)
  and
    start_axis = 2, stop_axis = -1
  We get:
    Out.shape = (3, 100, 400)

Case 2:
  Given
    X.shape = (3, 100, 100, 4)
  and
    start_axis = 0, stop_axis = -1
  We get:
    Out.shape = (3 * 100 * 100 * 4)
)DOC");
    AddOutput("XShape",
              "XShape is just used to store the shape and lod of X, which will "
              "be used in FlattenGradOp.")
352 353
        .AsIntermediate()
        .AsExtra();
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  }
};

template <typename T>
class FlattenContiguousRangeGradOpMaker
    : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("flatten_contiguous_range_grad");
    grad_op->SetInput("XShape", this->Output("XShape"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
  }
};

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

  void InferShape(framework::InferShapeContext *context) const override {
377 378 379 380 381 382 383
    OP_INOUT_CHECK(context->HasInput("XShape"),
                   "Input",
                   "XShape",
                   "FlattenContiguousRangeGrad");
    OP_INOUT_CHECK(context->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
384
                   "FlattenContiguousRangeGrad");
385 386 387 388 389 390 391 392
    // Construct MetaTensor for InferMeta Func
    using CompatMetaTensor = framework::CompatMetaTensor;
    CompatMetaTensor xshape(context->GetInputVarPtrs("XShape")[0],
                            context->IsRuntime());
    CompatMetaTensor dx(
        context->GetOutputVarPtrs(framework::GradVarName("X"))[0],
        context->IsRuntime());
    phi::KernelWithXShapeInferMeta(xshape, &dx);
393 394 395
  }

 protected:
396
  phi::KernelKey GetExpectedKernelType(
397
      const framework::ExecutionContext &ctx) const override {
398 399 400
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(
                              ctx, framework::GradVarName("Out")),
                          ctx.GetPlace());
401 402
  }
};
403 404
DECLARE_INPLACE_OP_INFERER(FlattenOpInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(FlattenGradInplaceInferer,
405 406
                           {framework::GradVarName("Out"),
                            framework::GradVarName("X")});
407
DECLARE_NO_NEED_BUFFER_VARS_INFERER(FlattenGradNoNeedBufferVarsInferer, "X");
D
dzhwinter 已提交
408

B
Bai Yifan 已提交
409 410 411 412
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
413 414 415
REGISTER_OPERATOR(flatten,
                  ops::FlattenOp,
                  ops::FlattenOpMaker,
416 417
                  ops::FlattenGradOpMaker<paddle::framework::OpDesc>,
                  ops::FlattenGradOpMaker<paddle::imperative::OpBase>,
418
                  ops::FlattenOpInplaceInferer);
419 420
REGISTER_OPERATOR(flatten_grad,
                  ops::FlattenGradOp,
421 422
                  ops::FlattenGradInplaceInferer,
                  ops::FlattenGradNoNeedBufferVarsInferer);
423

424 425 426
REGISTER_OPERATOR(flatten2,
                  ops::Flatten2Op,
                  ops::Flatten2OpMaker,
H
hong 已提交
427 428
                  ops::Flatten2GradOpMaker<paddle::framework::OpDesc>,
                  ops::Flatten2GradOpMaker<paddle::imperative::OpBase>,
429
                  ops::FlattenOpInplaceInferer);
430 431
REGISTER_OPERATOR(flatten2_grad,
                  ops::Flatten2GradOp,
432
                  ops::FlattenGradInplaceInferer);
433

434
REGISTER_OPERATOR(
435 436
    flatten_contiguous_range,
    ops::FlattenContiguousRangeOp,
437 438 439 440 441 442 443 444
    ops::FlattenContiguousRangeOpMaker,
    ops::FlattenContiguousRangeGradOpMaker<paddle::framework::OpDesc>,
    ops::FlattenContiguousRangeGradOpMaker<paddle::imperative::OpBase>,
    ops::FlattenOpInplaceInferer);
REGISTER_OPERATOR(flatten_contiguous_range_grad,
                  ops::FlattenContiguousRangeGradOp,
                  ops::FlattenGradInplaceInferer);

L
Leo Chen 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
REGISTER_OP_CPU_KERNEL(flatten,
                       ops::FlattenKernel<phi::CPUContext, float>,
                       ops::FlattenKernel<phi::CPUContext, double>,
                       ops::FlattenKernel<phi::CPUContext, uint8_t>,
                       ops::FlattenKernel<phi::CPUContext, int>,
                       ops::FlattenKernel<phi::CPUContext, int8_t>,
                       ops::FlattenKernel<phi::CPUContext, int64_t>);
REGISTER_OP_CPU_KERNEL(flatten_grad,
                       ops::FlattenGradKernel<phi::CPUContext, float>,
                       ops::FlattenGradKernel<phi::CPUContext, double>,
                       ops::FlattenGradKernel<phi::CPUContext, uint8_t>,
                       ops::FlattenGradKernel<phi::CPUContext, int>,
                       ops::FlattenGradKernel<phi::CPUContext, int8_t>,
                       ops::FlattenGradKernel<phi::CPUContext, int64_t>);
REGISTER_OP_CPU_KERNEL(flatten2,
                       ops::Flatten2Kernel<phi::CPUContext, float>,
                       ops::Flatten2Kernel<phi::CPUContext, double>,
                       ops::Flatten2Kernel<phi::CPUContext, uint8_t>,
                       ops::Flatten2Kernel<phi::CPUContext, int>,
                       ops::Flatten2Kernel<phi::CPUContext, int8_t>,
                       ops::Flatten2Kernel<phi::CPUContext, int64_t>);
REGISTER_OP_CPU_KERNEL(flatten2_grad,
                       ops::Flatten2GradKernel<phi::CPUContext, float>,
                       ops::Flatten2GradKernel<phi::CPUContext, double>,
                       ops::Flatten2GradKernel<phi::CPUContext, uint8_t>,
                       ops::Flatten2GradKernel<phi::CPUContext, int>,
                       ops::Flatten2GradKernel<phi::CPUContext, int8_t>,
                       ops::Flatten2GradKernel<phi::CPUContext, int64_t>);