reshape_op.cc 29.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yibing Liu 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yibing Liu 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yibing Liu 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
Y
Yibing Liu 已提交
14

Y
Yi Wang 已提交
15
#include <string>
W
wanghuancoder 已提交
16

17
#include "paddle/fluid/framework/infershape_utils.h"
Y
yuyang18 已提交
18
#include "paddle/fluid/framework/op_registry.h"
19
#include "paddle/fluid/framework/phi_utils.h"
Y
Yi Wang 已提交
20

21 22 23
// only can include the headers in paddle/phi/api dirs
#include "paddle/phi/api/lib/utils/tensor_utils.h"
#include "paddle/phi/backends/cpu/cpu_context.h"
24
#include "paddle/phi/common/int_array.h"
25
#include "paddle/phi/core/infermeta_utils.h"
26
#include "paddle/phi/infermeta/backward.h"
27
#include "paddle/phi/infermeta/unary.h"
28 29
#include "paddle/phi/kernels/reshape_grad_kernel.h"
#include "paddle/phi/kernels/reshape_kernel.h"
30

W
wanghuancoder 已提交
31 32 33 34 35 36 37 38 39 40
namespace paddle {
namespace framework {
class InferShapeContext;
class OpDesc;
}  // namespace framework
namespace imperative {
class OpBase;
}  // namespace imperative
}  // namespace paddle

Y
Yibing Liu 已提交
41 42 43
namespace paddle {
namespace operators {

44
using Tensor = phi::DenseTensor;
45

Y
yuyang18 已提交
46 47
class ReshapeOp : public framework::OperatorWithKernel {
 public:
48 49
  ReshapeOp(const std::string &type,
            const framework::VariableNameMap &inputs,
Y
yuyang18 已提交
50 51 52 53 54
            const framework::VariableNameMap &outputs,
            const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
55 56
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"),
                      true,
57 58
                      platform::errors::InvalidArgument(
                          "Input(X) of ReshapeOp should not be null."));
59 60
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"),
                      true,
61 62
                      platform::errors::InvalidArgument(
                          "Output(Out) of ReshapeOp should not be null."));
Y
yuyang18 已提交
63

64 65
    if (ctx->HasInputs("ShapeTensor")) {
      // top prority shape
66
      auto ShapeTensor = ctx->Inputs("ShapeTensor");
67
      PADDLE_ENFORCE_GT(
68 69
          ShapeTensor.size(),
          0,
70 71 72 73 74
          platform::errors::InvalidArgument(
              "When `shape` in ReshapeOp is a list or tuple "
              "which contains Tensor, the shape's size can't be zero. "
              "But received shape's size is %d.",
              ShapeTensor.size()));
75 76 77 78 79 80
      auto infer_shape = ctx->Attrs().Get<std::vector<int>>("shape");
      const int64_t copy_dim_val = 0;
      auto in_dims = ctx->GetInputDim("X");
      for (size_t i = 0; i < infer_shape.size(); ++i) {
        if (infer_shape[i] == copy_dim_val) {
          PADDLE_ENFORCE_LT(
81 82
              static_cast<int>(i),
              in_dims.size(),
83 84 85 86
              platform::errors::InvalidArgument(
                  "The index of 0 in `shape` must be less than "
                  "the input tensor X's dimensions. But received shape[%d] "
                  "= 0, X's dimensions = %d, X's shape = [%s].",
87 88 89
                  i,
                  in_dims.size(),
                  in_dims));
90 91 92
          infer_shape[i] = in_dims[i];
        }
      }
93
      auto infer_out_dims = phi::make_ddim(infer_shape);
94 95 96
      ctx->SetOutputDim("Out", infer_out_dims);
      return;
    }
Y
yuyang18 已提交
97

98 99 100 101 102 103 104 105
    const std::vector<int> &shape = ctx->Attrs().Get<std::vector<int>>("shape");
    if (ctx->HasInput("Shape") && shape.empty()) {
      auto shape_dims = ctx->GetInputDim("Shape");
      int num_ele = 1;
      for (int i = 0; i < shape_dims.size(); ++i) {
        num_ele *= shape_dims[i];
      }
      auto vec_dims = std::vector<int>(num_ele, -1);
106
      auto out_dims = phi::make_ddim(vec_dims);
107 108
      ctx->SetOutputDim("Out", out_dims);
      ctx->ShareLoD("X", /*->*/ "Out");
109 110
      return;
    }
111 112

    if (ctx->HasInput("Shape") && !shape.empty() && ctx->IsRuntime()) {
Y
yuyang18 已提交
113 114 115 116 117
      // If true, set the shape of Output(Out) according to Input(Shape) in
      // ReshapeKernel with ExecutionContext. Also check LoD in ReshapeKernel.
      ctx->ShareLoD("X", /*->*/ "Out");
      return;
    }
118

119 120
    PADDLE_ENFORCE_EQ(!shape.empty(),
                      true,
121 122 123
                      platform::errors::InvalidArgument(
                          "The parameter 'shape' in ReshapeOp must be set. "
                          "But received 'shape' is empty."));
Y
yuyang18 已提交
124 125 126 127 128 129 130 131 132 133 134 135
    auto x_dims = ctx->GetInputDim("X");
    auto out_dims = ValidateShape(shape, x_dims);
    ctx->SetOutputDim("Out", out_dims);
    if (x_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 framework::DDim ValidateShape(const std::vector<int> shape,
                                       const framework::DDim &in_dims) {
136 137
    const int64_t in_size = phi::product(in_dims);
    auto in_dims_vec = phi::vectorize(in_dims);
138 139
    bool all_positive = std::all_of(in_dims_vec.cbegin(),
                                    in_dims_vec.cend(),
C
chengduo 已提交
140
                                    [](int64_t i) { return i > 0; });
Y
yuyang18 已提交
141 142 143 144 145 146 147 148 149 150
    // only one dimension can be set to -1, whose size will be automatically
    // infered.
    const int64_t unk_dim_val = -1;
    const int64_t copy_dim_val = 0;

    std::vector<int64_t> output_shape(shape.size(), 0);
    int64_t capacity = 1;
    int unk_dim_idx = -1;
    for (size_t i = 0; i < shape.size(); ++i) {
      if (shape[i] == unk_dim_val) {
151
        PADDLE_ENFORCE_EQ(
152 153
            unk_dim_idx,
            -1,
154 155 156
            platform::errors::InvalidArgument(
                "Only one dimension value of 'shape' in ReshapeOp can "
                "be -1. But received shape = [%s], shape[%d] is also -1.",
157 158
                phi::make_ddim(shape),
                i));
Y
yuyang18 已提交
159 160
        unk_dim_idx = i;
      } else if (shape[i] == copy_dim_val) {
161
        PADDLE_ENFORCE_LT(
162 163
            static_cast<int>(i),
            in_dims.size(),
164 165 166 167 168
            platform::errors::InvalidArgument(
                "The index of 0 in `shape` must be less than "
                "the input tensor X's dimensions. "
                "But received shape = [%s], shape[%d] = 0, X's shape = [%s], "
                "X's dimensions = %d.",
169 170 171 172
                phi::make_ddim(shape),
                i,
                in_dims,
                in_dims.size()));
Y
yuyang18 已提交
173
      } else {
174
        PADDLE_ENFORCE_GT(
175 176
            shape[i],
            0,
177 178
            platform::errors::InvalidArgument(
                "Each dimension value of 'shape' in ReshapeOp must not "
T
tianshuo78520a 已提交
179
                "be negative except one unknown dimension. "
180
                "But received  shape = [%s], shape[%d] = %d.",
181 182 183
                phi::make_ddim(shape),
                i,
                shape[i]));
Y
yuyang18 已提交
184 185
      }

186 187
      // NOTE all non-zero values will be converted to True (include negative
      // value)
Y
yuyang18 已提交
188 189 190 191 192 193
      capacity *= (shape[i] ? shape[i] : in_dims[i]);
      output_shape[i] =
          (shape[i] ? static_cast<int64_t>(shape[i]) : in_dims[i]);
    }

    if (unk_dim_idx != -1) {
C
chengduo 已提交
194
      if (all_positive) {
Y
yuyang18 已提交
195 196 197 198 199
        // in_size < 0 and is un-determinate in compile time, skip the check,
        // for example, in_dims = [-1, 8, 1, 1], shape = [-1, 3, 8],
        // capacity = -24, in_size = -8, output_shape[0] = 0
        // the following check will fail.
        output_shape[unk_dim_idx] = -in_size / capacity;
200
        PADDLE_ENFORCE_EQ(
201 202
            output_shape[unk_dim_idx] * capacity,
            -in_size,
203 204 205 206 207
            platform::errors::InvalidArgument(
                "The 'shape' attribute in ReshapeOp is invalid. "
                "The input tensor X'size must be divisible by known "
                "capacity of 'shape'. "
                "But received X's shape = [%s], X's size = %d, "
208
                "'shape' is [%s], known capacity of 'shape' is %d.",
209 210 211 212
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
Y
yuyang18 已提交
213 214 215 216
      } else {
        output_shape[unk_dim_idx] = -1;
      }
    } else {
Y
Yamei-Lee 已提交
217 218
      if (all_positive) {
        PADDLE_ENFORCE_EQ(
219 220
            capacity,
            in_size,
221 222 223 224 225 226
            platform::errors::InvalidArgument(
                "The 'shape' in ReshapeOp is invalid. "
                "The input tensor X'size must be equal to the capacity of "
                "'shape'. "
                "But received X's shape = [%s], X's size = %d, 'shape' is "
                "[%s], the capacity of 'shape' is %d.",
227 228 229 230
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
Y
Yamei-Lee 已提交
231
      }
Y
yuyang18 已提交
232
    }
233 234 235 236 237

    // support reshape with zero-input(input tensor with product(shape) == 0)
    // by now we require that if the input tensor is zero shape, the target
    // shape of output must be zero
    if (in_size == 0) {
J
JZ-LIANG 已提交
238
      PADDLE_ENFORCE_LE(
239 240
          capacity,
          in_size,
241 242 243 244 245
          platform::errors::InvalidArgument(
              "The 'shape' in ReshapeOp is invalid. "
              "The input tensor X's shape = [%s], X's capacity = %d."
              "But the target shape of Out is [%s],  the "
              "capacity of 'Out' is %d.",
246 247 248 249
              in_dims,
              in_size,
              phi::make_ddim(shape),
              capacity));
250 251
    }

252
    return phi::make_ddim(output_shape);
Y
yuyang18 已提交
253 254 255 256 257
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
258 259 260 261
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

    return framework::OpKernelType(input_data_type, ctx.GetPlace());
Y
yuyang18 已提交
262
  }
263 264

  framework::OpKernelType GetKernelTypeForVar(
265 266
      const std::string &var_name,
      const Tensor &tensor,
267 268 269 270
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "ShapeTensor") {
      return expected_kernel_type;
    }
271 272
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
273
  }
Y
yuyang18 已提交
274 275
};

Y
Yibing Liu 已提交
276 277
class ReshapeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
278
  void Make() override {
279 280
    AddInput("X", "(Tensor). The input tensor of reshape operator.");
    AddInput("Shape",
281 282 283
             "(Tensor<int32>, optional). Target shape of reshape operator. "
             "It has a higher priority than Attr(shape) but a lower priority "
             "than Input(ShapeTensor). The Attr(shape) still should be "
T
tianshuo78520a 已提交
284
             "set correctly to guarantee shape inference in compile time.")
285
        .AsDispensable();
286 287
    AddInput(
        "ShapeTensor",
288 289 290 291
        "(vector<Tensor<int32>>, optional). Target shape of reshape operator. "
        "It has the highest priority compare with Input(Shape) and "
        "Attr(shape)."
        "The shape of the element in vector must be [1].")
292 293
        .AsDuplicable()
        .AsDispensable();
294
    AddOutput("Out", "(Tensor). The output tensor of reshape operator.");
C
caoying03 已提交
295
    AddAttr<std::vector<int>>(
296 297 298 299
        "shape",
        "(std::vector<int>) Target shape of reshape operator."
        "It has the lowest priority compare with Input(Shape) and "
        " Input(ShapeTensor).")
300
        .SetDefault({});
301 302
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
Z
zmx 已提交
303 304
        .SetDefault(false)
        .AsExtra();
K
kexinzhao 已提交
305 306
    AddComment(R"DOC(
Reshape Operator.
Y
Yibing Liu 已提交
307

308 309
Reshape Input(X) into the shape specified by Attr(shape) or Input(Shape). The
data in Input(X) are unchanged.
Y
Yibing Liu 已提交
310

C
caoying03 已提交
311
Examples:
Y
Yibing Liu 已提交
312

C
caoying03 已提交
313 314 315 316
1. Given a 3-D tensor Input(X) with a shape [2, 4, 6], and the target shape
specified by Attr(shape) is [6, 8], the reshape operator will transform Input(X)
into a 2-D tensor with shape [6, 8] and leaving Input(X)'s data unchanged.

317
2. Given a 3-D tensor Input(X) with a shape [2, 4, 6], and the target shape
C
caoying03 已提交
318 319 320 321 322 323
specified by Attr(shape) is [2, 3, -1, 2], the reshape operator will transform
Input(X) into a 4-D tensor with shape [2, 3, 4, 2] and leaving Input(X)'s data
unchanged. In this case, one and only dimension of Attr(shape) can be set to -1,
the value of this dimension is inferred from the total element number of
Input(X) and remaining dimensions.

324
3. Given a 3-D tensor Input(X) with a shape [2, 4, 6], and the target shape
C
caoying03 已提交
325 326 327 328
specified by Attr(shape) is [-1, 0, 3, 2], the reshape operator will transform
Input(X) into a 4-D tensor with shape [2, 4, 3, 2] and leaving Input(X)'s data
unchanged. In this case, besides -1, 0 means the actual dimension value is going
to be copied from the corresponding dimension of Input(X).
Y
Yibing Liu 已提交
329

C
caoying03 已提交
330
Note:
Y
Yibing Liu 已提交
331

C
caoying03 已提交
332 333 334
1. One and only one dimension in Attr(shape) can be set -1. In this case,
the actual dimension value will be infered from the total element number of
Input(X) and remaining dimensions.
335 336

2. More than one dimensions in Attr(shape) can be set to 0, which means the real
C
caoying03 已提交
337
dimension value will be copied from Input(X) at runtime. Note that the index of
G
guosheng 已提交
338
0 can not exceed Rank(X). For example, Input(X) is a 3-D tensor with shape
C
caoying03 已提交
339
[2, 3, 4], Attr(shape) = [2, 3, 2, 0] is an invalid input.
340 341

3. Input(Shape) has a higher priority than Attr(shape) if it is provided, while
T
tianshuo78520a 已提交
342
Attr(shape) still should be set correctly to guarantee shape inference in
343
compile-time.
Y
Yibing Liu 已提交
344

Y
Yibing Liu 已提交
345 346 347 348 349 350 351 352 353 354 355 356
)DOC");
  }
};

class ReshapeGradOp : public framework::OperatorWithKernel {
 public:
  ReshapeGradOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

357
  void InferShape(framework::InferShapeContext *ctx) const override {
358
    PADDLE_ENFORCE_EQ(
359 360
        ctx->HasInput("X"),
        true,
361
        platform::errors::InvalidArgument("Input(X) shouldn't be null."));
362 363
    PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName("Out")),
                      true,
364 365
                      platform::errors::InvalidArgument(
                          "Input(Out@GRAD) shouldn't be null."));
Q
Qiao Longfei 已提交
366
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
Y
Yibing Liu 已提交
367
  }
368 369 370 371

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
372 373 374 375
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");

    return framework::OpKernelType(input_data_type, ctx.GetPlace());
376
  }
Y
Yibing Liu 已提交
377 378
};

Y
yuyang18 已提交
379 380 381
class ReshapeKernel {
 public:
  void operator()(const framework::ExecutionContext &ctx) const {
382 383
    auto *out = ctx.Output<phi::DenseTensor>("Out");
    auto *in = ctx.Input<phi::DenseTensor>("X");
Y
yuyang18 已提交
384

385
    auto list_new_shape_tensor =
386
        ctx.MultiInput<phi::DenseTensor>("ShapeTensor");
387 388
    auto *shape_tensor =
        ctx.HasInput("Shape") ? ctx.Input<phi::DenseTensor>("Shape") : nullptr;
389
    phi::IntArray pt_scalar_shape;
390 391
    if (list_new_shape_tensor.size() > 0) {
      // have shape tensor
392
      std::vector<phi::DenseTensor> pt_vec_shape;
393 394 395
      for (auto &tensor : list_new_shape_tensor) {
        if (platform::is_gpu_place(tensor->place()) ||
            platform::is_xpu_place(tensor->place())) {
396
          phi::DenseTensor temp;
397 398
          paddle::framework::TensorCopySync(
              *tensor, platform::CPUPlace(), &temp);
399
          pt_vec_shape.push_back(std::move(temp));
400
        } else {
401
          pt_vec_shape.push_back(*tensor);
402 403
        }
      }
404
      pt_scalar_shape = phi::IntArray(pt_vec_shape);
405
    } else if (shape_tensor) {
406
      phi::DenseTensor pt_shape;
407 408
      if (platform::is_gpu_place(shape_tensor->place()) ||
          platform::is_xpu_place(shape_tensor->place())) {
409
        phi::DenseTensor temp;
410 411
        paddle::framework::TensorCopySync(
            *shape_tensor, platform::CPUPlace(), &temp);
412
        pt_shape = std::move(temp);
413
      } else {
414
        pt_shape = *shape_tensor;
415
      }
416
      pt_scalar_shape = phi::IntArray(pt_shape);
417
    } else {
418
      auto &shape_attr = ctx.Attr<std::vector<int>>("shape");
419
      pt_scalar_shape = phi::IntArray(shape_attr);
420 421
    }
    if (platform::is_cpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
422
      auto &dev_ctx = ctx.device_context<phi::CPUContext>();
423 424 425 426
      phi::ReshapeKernel(static_cast<const phi::CPUContext &>(dev_ctx),
                         *in,
                         pt_scalar_shape,
                         out);
427
    }
428
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
429
    if (platform::is_gpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
430
      auto &dev_ctx = ctx.device_context<phi::GPUContext>();
431 432 433 434
      phi::ReshapeKernel(static_cast<const phi::GPUContext &>(dev_ctx),
                         *in,
                         pt_scalar_shape,
                         out);
435
    }
436 437
#endif
#ifdef PADDLE_WITH_XPU
438 439
    if (platform::is_xpu_place(ctx.GetPlace())) {
      auto &dev_ctx = ctx.device_context<platform::XPUDeviceContext>();
440 441 442 443
      phi::ReshapeKernel(static_cast<const phi::XPUContext &>(dev_ctx),
                         *in,
                         pt_scalar_shape,
                         out);
444
    }
445
#endif
Y
yuyang18 已提交
446
  }
Y
yuyang18 已提交
447 448 449 450 451
};

class ReshapeGradKernel {
 public:
  void operator()(const framework::ExecutionContext &ctx) const {
452 453
    auto *d_out = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto *d_x = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
454
    d_x->mutable_data(ctx.GetPlace(), d_out->type());
455 456

    if (platform::is_cpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
457
      auto &dev_ctx = ctx.device_context<phi::CPUContext>();
458 459
      phi::ReshapeGradKernel(
          static_cast<const phi::CPUContext &>(dev_ctx), *d_out, d_x);
460 461 462
    }
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    if (platform::is_gpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
463
      auto &dev_ctx = ctx.device_context<phi::GPUContext>();
464 465
      phi::ReshapeGradKernel(
          static_cast<const phi::GPUContext &>(dev_ctx), *d_out, d_x);
466 467 468 469 470
    }
#endif
#ifdef PADDLE_WITH_XPU
    if (platform::is_xpu_place(ctx.GetPlace())) {
      auto &dev_ctx = ctx.device_context<platform::XPUDeviceContext>();
471 472
      phi::ReshapeGradKernel(
          static_cast<const phi::XPUContext &>(dev_ctx), *d_out, d_x);
473 474
    }
#endif
Y
yuyang18 已提交
475
  }
Y
yuyang18 已提交
476 477
};

478 479 480
class ReshapeDoubleGradKernel {
 public:
  void operator()(const framework::ExecutionContext &ctx) const {
481 482 483
    auto *dd_x = ctx.Input<phi::DenseTensor>("DDX");
    auto *d_out = ctx.Input<phi::DenseTensor>("DOut");
    auto *dd_out = ctx.Output<phi::DenseTensor>("DDOut");
484
    dd_out->mutable_data(ctx.GetPlace(), dd_x->type());
485

486
    if (platform::is_cpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
487
      auto &dev_ctx = ctx.device_context<phi::CPUContext>();
488
      phi::ReshapeDoubleGradKernel(
489
          static_cast<const phi::CPUContext &>(dev_ctx), *d_out, *dd_x, dd_out);
490 491 492
    }
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    if (platform::is_gpu_place(ctx.GetPlace())) {
L
Leo Chen 已提交
493
      auto &dev_ctx = ctx.device_context<phi::GPUContext>();
494
      phi::ReshapeDoubleGradKernel(
495
          static_cast<const phi::GPUContext &>(dev_ctx), *d_out, *dd_x, dd_out);
496 497 498 499 500
    }
#endif
#ifdef PADDLE_WITH_XPU
    if (platform::is_xpu_place(ctx.GetPlace())) {
      auto &dev_ctx = ctx.device_context<platform::XPUDeviceContext>();
501
      phi::ReshapeDoubleGradKernel(
502
          static_cast<const phi::XPUContext &>(dev_ctx), *d_out, *dd_x, dd_out);
503 504
    }
#endif
505 506 507
  }
};

508 509 510 511 512 513 514
// FIXME(zcd): reshape2 adds an intermediate output(XShape) based on reshape,
// the XShape is used to carry the shape and lod of X which will be used in
// reshape_grad, in this way, the framework can reuse the memory of X
// immediately the reshape_op is finished.
// Considering compatibility issues, we could not fix reshape_op
class Reshape2Op : public ReshapeOp {
 public:
515 516
  Reshape2Op(const std::string &type,
             const framework::VariableNameMap &inputs,
517 518 519
             const framework::VariableNameMap &outputs,
             const framework::AttributeMap &attrs)
      : ReshapeOp(type, inputs, outputs, attrs) {}
520
  void InferShape(framework::InferShapeContext *ctx) const override {
521 522
    PADDLE_ENFORCE_EQ(ctx->HasOutput("XShape"),
                      true,
523 524 525 526 527 528 529 530 531 532 533 534 535
                      platform::errors::InvalidArgument(
                          "Output(XShape) of ReshapeOp should not be null."));
    const auto &x_dims = ctx->GetInputDim("X");
    std::vector<int64_t> xshape_dims(x_dims.size() + 1);
    xshape_dims[0] = 0;
    for (int i = 0; i < x_dims.size(); ++i) {
      xshape_dims[i + 1] = x_dims[i];
    }
    ctx->SetOutputDim("XShape", phi::make_ddim(xshape_dims));
    ctx->ShareLoD("X", /*->*/ "XShape");

    ReshapeOp::InferShape(ctx);
  }
536 537 538 539 540 541 542 543 544 545
};

class Reshape2OpMaker : public ReshapeOpMaker {
 public:
  void Make() override {
    ReshapeOpMaker::Make();
    AddOutput("XShape",
              "XShape is just used to store the shape and lod of X, which will "
              "be used in FlattenGradOp.")
        .AsIntermediate();
546 547 548 549
    AddAttr<bool>(
        "use_quantizer",
        "(bool, default false) "
        "This parameter is no longer used. Use 'mkldnn_data_type' instead.")
550
        .SetDefault(false);
551 552 553 554
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
555 556
        .InEnum({"float32", "int8", "bfloat16"})
        .AsExtra();
557 558 559
  }
};

H
hong 已提交
560 561
template <typename T>
class Reshape2GradMaker : public framework::SingleGradOpMaker<T> {
562
 public:
H
hong 已提交
563
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
564

565
  void Apply(GradOpPtr<T> grad_op) const override {
566
    grad_op->SetType("reshape2_grad");
H
hong 已提交
567 568 569 570
    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());
571 572 573
  }
};

H
hong 已提交
574 575
template <typename T>
class Reshape2DoubleGradMaker : public framework::SingleGradOpMaker<T> {
576
 public:
H
hong 已提交
577
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
578

579
  void Apply(GradOpPtr<T> grad_op) const override {
580
    grad_op->SetType("reshape2_grad_grad");
H
hong 已提交
581 582 583 584
    grad_op->SetInput("DOut", this->Input(framework::GradVarName("Out")));
    grad_op->SetInput("DDX", this->OutputGrad(framework::GradVarName("X")));
    grad_op->SetOutput("DDOut", this->InputGrad(framework::GradVarName("Out")));
    grad_op->SetAttrMap(this->Attrs());
585 586 587
  }
};

588 589 590 591 592 593 594 595 596
class Reshape2GradOp : public framework::OperatorWithKernel {
 public:
  Reshape2GradOp(const std::string &type,
                 const framework::VariableNameMap &inputs,
                 const framework::VariableNameMap &outputs,
                 const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
597
    PADDLE_ENFORCE_EQ(
598 599
        ctx->HasInput("XShape"),
        true,
600
        platform::errors::InvalidArgument("Input(XShape) shouldn't be null."));
601 602
    PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName("Out")),
                      true,
603 604
                      platform::errors::InvalidArgument(
                          "Input(Out@GRAD) shouldn't be null."));
605 606 607 608 609 610 611 612

    // Construct MetaTensor for InferMeta Func
    using CompatMetaTensor = framework::CompatMetaTensor;
    CompatMetaTensor xshape(ctx->GetInputVarPtrs("XShape")[0],
                            ctx->IsRuntime());
    CompatMetaTensor dx(ctx->GetOutputVarPtrs(framework::GradVarName("X"))[0],
                        ctx->IsRuntime());
    phi::KernelWithXShapeInferMeta(xshape, &dx);
613 614 615 616 617
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
618 619 620 621
    auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));

    return framework::OpKernelType(input_data_type, ctx.GetPlace());
622
  }
623 624

  framework::OpKernelType GetKernelTypeForVar(
625 626
      const std::string &var_name,
      const Tensor &tensor,
627 628 629 630
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "ShapeTensor") {
      return expected_kernel_type;
    }
631 632
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
633
  }
634 635
};

636 637 638 639 640 641 642 643 644 645 646
class Reshape2DoubleGradOp : public framework::OperatorWithKernel {
 public:
  Reshape2DoubleGradOp(const std::string &type,
                       const framework::VariableNameMap &inputs,
                       const framework::VariableNameMap &outputs,
                       const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
647 648 649
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "DDX"),
        ctx.device_context());
650 651 652
  }

  framework::OpKernelType GetKernelTypeForVar(
653 654
      const std::string &var_name,
      const Tensor &tensor,
655 656 657 658
      const framework::OpKernelType &expected_kernel_type) const override {
    if (var_name == "ShapeTensor") {
      return expected_kernel_type;
    }
659 660
    return framework::OpKernelType(
        expected_kernel_type.data_type_, tensor.place(), tensor.layout());
661 662 663
  }
};

664 665
DECLARE_INPLACE_OP_INFERER(ReshapeOpInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(ReshapeGradInplaceInferer,
666 667
                           {framework::GradVarName("Out"),
                            framework::GradVarName("X")});
668 669
DECLARE_INPLACE_OP_INFERER(ReshapeDoubleGradInplaceInferer, {"DDX", "DDOut"});
DECLARE_NO_NEED_BUFFER_VARS_INFERER(ReshapeDoubleGradOpNoNeedBufferVarInferer,
Z
Zeng Jinle 已提交
670
                                    "DOut");
D
dzhwinter 已提交
671

Y
Yibing Liu 已提交
672 673 674
}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;
675
namespace plat = paddle::platform;
Y
Yibing Liu 已提交
676

H
hong 已提交
677
REGISTER_OPERATOR(
678 679 680
    reshape,
    ops::ReshapeOp,
    ops::ReshapeOpMaker,
H
hong 已提交
681 682
    paddle::framework::DefaultGradOpMaker<paddle::framework::OpDesc, true>,
    paddle::framework::DefaultGradOpMaker<paddle::imperative::OpBase, true>,
683
    ops::ReshapeOpInplaceInferer);
684 685
REGISTER_OPERATOR(reshape_grad,
                  ops::ReshapeGradOp,
686
                  ops::ReshapeGradInplaceInferer);
687

688 689 690 691 692 693 694 695 696 697
REGISTER_OP_CPU_KERNEL_FUNCTOR(reshape,
                               float,
                               ops::ReshapeKernel,
                               double,
                               ops::ReshapeKernel,
                               int16_t,
                               ops::ReshapeKernel,
                               int,
                               ops::ReshapeKernel,
                               int64_t,
698
                               ops::ReshapeKernel);
699 700 701 702 703 704 705 706 707 708
REGISTER_OP_CPU_KERNEL_FUNCTOR(reshape_grad,
                               float,
                               ops::ReshapeGradKernel,
                               double,
                               ops::ReshapeGradKernel,
                               int16_t,
                               ops::ReshapeGradKernel,
                               int,
                               ops::ReshapeGradKernel,
                               int64_t,
709
                               ops::ReshapeGradKernel);
710

711 712 713
REGISTER_OPERATOR(reshape2,
                  ops::Reshape2Op,
                  ops::Reshape2OpMaker,
H
hong 已提交
714 715
                  ops::Reshape2GradMaker<paddle::framework::OpDesc>,
                  ops::Reshape2GradMaker<paddle::imperative::OpBase>,
716
                  ops::ReshapeOpInplaceInferer);
717 718
REGISTER_OPERATOR(reshape2_grad,
                  ops::Reshape2GradOp,
H
hong 已提交
719 720
                  ops::Reshape2DoubleGradMaker<paddle::framework::OpDesc>,
                  ops::Reshape2DoubleGradMaker<paddle::imperative::OpBase>,
721
                  ops::ReshapeGradInplaceInferer);
722 723 724

DECLARE_INFER_SHAPE_FUNCTOR(reshape2_grad_grad,
                            Reshape2DoubleGradInferShapeFunctor,
725
                            PD_INFER_META(phi::ReshapeDoubleGradInferMeta));
726

727 728
REGISTER_OPERATOR(reshape2_grad_grad,
                  ops::Reshape2DoubleGradOp,
729
                  ops::ReshapeDoubleGradInplaceInferer,
730 731
                  ops::ReshapeDoubleGradOpNoNeedBufferVarInferer,
                  Reshape2DoubleGradInferShapeFunctor);
732

733
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
REGISTER_OP_CUDA_KERNEL_FUNCTOR(reshape,
                                float,
                                ops::ReshapeKernel,
                                double,
                                ops::ReshapeKernel,
                                int16_t,
                                ops::ReshapeKernel,
                                int,
                                ops::ReshapeKernel,
                                uint8_t,
                                ops::ReshapeKernel,
                                int64_t,
                                ops::ReshapeKernel,
                                plat::float16,
                                ops::ReshapeKernel,
                                plat::bfloat16,
                                ops::ReshapeKernel);
REGISTER_OP_CUDA_KERNEL_FUNCTOR(reshape_grad,
                                float,
                                ops::ReshapeGradKernel,
                                double,
                                ops::ReshapeGradKernel,
                                int16_t,
                                ops::ReshapeKernel,
                                int,
                                ops::ReshapeGradKernel,
                                int64_t,
                                ops::ReshapeGradKernel,
                                uint8_t,
                                ops::ReshapeGradKernel,
                                plat::float16,
                                ops::ReshapeGradKernel,
                                plat::bfloat16,
767
                                ops::ReshapeGradKernel);
768
#endif