reshape_op.cc 29.4 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 {

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

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

62 63 64 65 66 67 68 69 70 71 72
    if (ctx->IsRuntime()) {
      auto *x_var =
          PADDLE_GET(framework::Variable *, ctx->GetInputVarPtrs("X")[0]);
      auto *out_var =
          PADDLE_GET(framework::Variable *, ctx->GetOutputVarPtrs("Out")[0]);
      // inplace, can not to run infer shape.
      if (x_var == out_var) {
        return;
      }
    }

73 74
    if (ctx->HasInputs("ShapeTensor")) {
      // top prority shape
75
      auto ShapeTensor = ctx->Inputs("ShapeTensor");
76
      PADDLE_ENFORCE_GT(
77 78
          ShapeTensor.size(),
          0,
79 80 81 82 83
          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()));
84 85 86 87 88 89
      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(
90 91
              static_cast<int>(i),
              in_dims.size(),
92 93 94 95
              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].",
96 97 98
                  i,
                  in_dims.size(),
                  in_dims));
99 100 101
          infer_shape[i] = in_dims[i];
        }
      }
102
      auto infer_out_dims = phi::make_ddim(infer_shape);
103 104 105
      ctx->SetOutputDim("Out", infer_out_dims);
      return;
    }
Y
yuyang18 已提交
106

107 108 109 110 111 112 113 114
    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);
115
      auto out_dims = phi::make_ddim(vec_dims);
116 117
      ctx->SetOutputDim("Out", out_dims);
      ctx->ShareLoD("X", /*->*/ "Out");
118 119
      return;
    }
120 121

    if (ctx->HasInput("Shape") && !shape.empty() && ctx->IsRuntime()) {
Y
yuyang18 已提交
122 123 124 125 126
      // 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;
    }
127

Y
yuyang18 已提交
128 129 130 131 132 133 134 135 136 137 138 139
    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) {
140 141
    const int64_t in_size = phi::product(in_dims);
    auto in_dims_vec = phi::vectorize(in_dims);
142 143
    bool all_positive = std::all_of(in_dims_vec.cbegin(),
                                    in_dims_vec.cend(),
C
chengduo 已提交
144
                                    [](int64_t i) { return i > 0; });
Y
yuyang18 已提交
145 146 147 148 149 150 151 152 153 154
    // 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) {
155
        PADDLE_ENFORCE_EQ(
156 157
            unk_dim_idx,
            -1,
158 159 160
            platform::errors::InvalidArgument(
                "Only one dimension value of 'shape' in ReshapeOp can "
                "be -1. But received shape = [%s], shape[%d] is also -1.",
161 162
                phi::make_ddim(shape),
                i));
Y
yuyang18 已提交
163 164
        unk_dim_idx = i;
      } else if (shape[i] == copy_dim_val) {
165
        PADDLE_ENFORCE_LT(
166 167
            static_cast<int>(i),
            in_dims.size(),
168 169 170 171 172
            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.",
173 174 175 176
                phi::make_ddim(shape),
                i,
                in_dims,
                in_dims.size()));
Y
yuyang18 已提交
177
      } else {
178
        PADDLE_ENFORCE_GT(
179 180
            shape[i],
            0,
181 182
            platform::errors::InvalidArgument(
                "Each dimension value of 'shape' in ReshapeOp must not "
T
tianshuo78520a 已提交
183
                "be negative except one unknown dimension. "
184
                "But received  shape = [%s], shape[%d] = %d.",
185 186 187
                phi::make_ddim(shape),
                i,
                shape[i]));
Y
yuyang18 已提交
188 189
      }

190 191
      // NOTE all non-zero values will be converted to True (include negative
      // value)
Y
yuyang18 已提交
192 193 194 195 196 197
      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 已提交
198
      if (all_positive) {
Y
yuyang18 已提交
199 200 201 202 203
        // 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;
204
        PADDLE_ENFORCE_EQ(
205 206
            output_shape[unk_dim_idx] * capacity,
            -in_size,
207 208 209 210 211
            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, "
212
                "'shape' is [%s], known capacity of 'shape' is %d.",
213 214 215 216
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
Y
yuyang18 已提交
217 218 219 220
      } else {
        output_shape[unk_dim_idx] = -1;
      }
    } else {
Y
Yamei-Lee 已提交
221 222
      if (all_positive) {
        PADDLE_ENFORCE_EQ(
223 224
            capacity,
            in_size,
225 226 227 228 229 230
            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.",
231 232 233 234
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
Y
Yamei-Lee 已提交
235
      }
Y
yuyang18 已提交
236
    }
237 238 239 240 241

    // 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 已提交
242
      PADDLE_ENFORCE_LE(
243 244
          capacity,
          in_size,
245 246 247 248 249
          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.",
250 251 252 253
              in_dims,
              in_size,
              phi::make_ddim(shape),
              capacity));
254 255
    }

256
    return phi::make_ddim(output_shape);
Y
yuyang18 已提交
257 258 259
  }

 protected:
260
  phi::KernelKey GetExpectedKernelType(
Y
yuyang18 已提交
261
      const framework::ExecutionContext &ctx) const override {
262 263
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
264
    return phi::KernelKey(input_data_type, ctx.GetPlace());
Y
yuyang18 已提交
265
  }
266

267
  phi::KernelKey GetKernelTypeForVar(
268
      const std::string &var_name,
269
      const phi::DenseTensor &tensor,
270
      const phi::KernelKey &expected_kernel_type) const override {
271
    if (var_name == "ShapeTensor") {
272 273 274
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
275
    }
276 277
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
278
  }
Y
yuyang18 已提交
279 280
};

Y
Yibing Liu 已提交
281 282
class ReshapeOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
283
  void Make() override {
284 285
    AddInput("X", "(Tensor). The input tensor of reshape operator.");
    AddInput("Shape",
286 287 288
             "(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 已提交
289
             "set correctly to guarantee shape inference in compile time.")
290
        .AsDispensable();
291 292
    AddInput(
        "ShapeTensor",
293 294 295 296
        "(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].")
297 298
        .AsDuplicable()
        .AsDispensable();
299
    AddOutput("Out", "(Tensor). The output tensor of reshape operator.");
C
caoying03 已提交
300
    AddAttr<std::vector<int>>(
301 302 303 304
        "shape",
        "(std::vector<int>) Target shape of reshape operator."
        "It has the lowest priority compare with Input(Shape) and "
        " Input(ShapeTensor).")
305
        .SetDefault({});
306 307
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
Z
zmx 已提交
308 309
        .SetDefault(false)
        .AsExtra();
K
kexinzhao 已提交
310 311
    AddComment(R"DOC(
Reshape Operator.
Y
Yibing Liu 已提交
312

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

C
caoying03 已提交
316
Examples:
Y
Yibing Liu 已提交
317

C
caoying03 已提交
318 319 320 321
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.

322
2. Given a 3-D tensor Input(X) with a shape [2, 4, 6], and the target shape
C
caoying03 已提交
323 324 325 326 327 328
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.

329
3. Given a 3-D tensor Input(X) with a shape [2, 4, 6], and the target shape
C
caoying03 已提交
330 331 332 333
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 已提交
334

C
caoying03 已提交
335
Note:
Y
Yibing Liu 已提交
336

C
caoying03 已提交
337 338 339
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.
340 341

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

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

Y
Yibing Liu 已提交
350 351 352 353 354 355 356 357 358 359 360 361
)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) {}

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

 protected:
375
  phi::KernelKey GetExpectedKernelType(
376
      const framework::ExecutionContext &ctx) const override {
377 378
    auto input_data_type =
        framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
379
    return phi::KernelKey(input_data_type, ctx.GetPlace());
380
  }
Y
Yibing Liu 已提交
381 382
};

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

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

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

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

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

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

512 513 514 515 516 517 518
// 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:
519 520
  Reshape2Op(const std::string &type,
             const framework::VariableNameMap &inputs,
521 522 523
             const framework::VariableNameMap &outputs,
             const framework::AttributeMap &attrs)
      : ReshapeOp(type, inputs, outputs, attrs) {}
524
  void InferShape(framework::InferShapeContext *ctx) const override {
525 526 527 528 529 530 531 532 533
    if (ctx->HasOutput("XShape")) {
      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");
534 535 536
    }
    ReshapeOp::InferShape(ctx);
  }
537 538 539 540 541 542 543 544 545 546
};

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();
547 548 549 550
    AddAttr<bool>(
        "use_quantizer",
        "(bool, default false) "
        "This parameter is no longer used. Use 'mkldnn_data_type' instead.")
551
        .SetDefault(false);
552 553 554 555
    AddAttr<std::string>(
        "mkldnn_data_type",
        "(string, default \"float32\"). Data type of mkldnn kernel")
        .SetDefault("float32")
556 557
        .InEnum({"float32", "int8", "bfloat16"})
        .AsExtra();
558 559 560
  }
};

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

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

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

580
  void Apply(GradOpPtr<T> grad_op) const override {
581
    grad_op->SetType("reshape2_grad_grad");
H
hong 已提交
582 583 584 585
    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());
586 587 588
  }
};

589 590 591 592 593 594 595 596 597
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 {
598
    PADDLE_ENFORCE_EQ(
599 600
        ctx->HasInput("XShape"),
        true,
601
        platform::errors::InvalidArgument("Input(XShape) shouldn't be null."));
602 603
    PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName("Out")),
                      true,
604 605
                      platform::errors::InvalidArgument(
                          "Input(Out@GRAD) shouldn't be null."));
606 607 608 609 610 611 612 613

    // 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);
614 615 616
  }

 protected:
617
  phi::KernelKey GetExpectedKernelType(
618
      const framework::ExecutionContext &ctx) const override {
619 620
    auto input_data_type = framework::OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
621
    return phi::KernelKey(input_data_type, ctx.GetPlace());
622
  }
623

624
  phi::KernelKey GetKernelTypeForVar(
625
      const std::string &var_name,
626
      const phi::DenseTensor &tensor,
627
      const phi::KernelKey &expected_kernel_type) const override {
628
    if (var_name == "ShapeTensor") {
629 630 631
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
632
    }
633 634
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
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:
647
  phi::KernelKey GetExpectedKernelType(
648
      const framework::ExecutionContext &ctx) const override {
649 650
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "DDX"),
                          ctx.GetPlace());
651 652
  }

653
  phi::KernelKey GetKernelTypeForVar(
654
      const std::string &var_name,
655
      const phi::DenseTensor &tensor,
656
      const phi::KernelKey &expected_kernel_type) const override {
657
    if (var_name == "ShapeTensor") {
658 659 660
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
661
    }
662 663
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
664 665 666
  }
};

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

Y
Yibing Liu 已提交
675 676 677
}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;
678
namespace plat = paddle::platform;
Y
Yibing Liu 已提交
679

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

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

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

DECLARE_INFER_SHAPE_FUNCTOR(reshape2_grad_grad,
                            Reshape2DoubleGradInferShapeFunctor,
728
                            PD_INFER_META(phi::ReshapeDoubleGradInferMeta));
729

730 731
REGISTER_OPERATOR(reshape2_grad_grad,
                  ops::Reshape2DoubleGradOp,
732
                  ops::ReshapeDoubleGradInplaceInferer,
733 734
                  ops::ReshapeDoubleGradOpNoNeedBufferVarInferer,
                  Reshape2DoubleGradInferShapeFunctor);
735

736
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
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 767 768 769
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,
770
                                ops::ReshapeGradKernel);
771
#endif