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
// only can include the headers in paddle/phi/api dirs
#include "paddle/phi/backends/cpu/cpu_context.h"
23
#include "paddle/phi/common/int_array.h"
24
#include "paddle/phi/core/infermeta_utils.h"
25
#include "paddle/phi/infermeta/backward.h"
26
#include "paddle/phi/infermeta/unary.h"
27 28
#include "paddle/phi/kernels/reshape_grad_kernel.h"
#include "paddle/phi/kernels/reshape_kernel.h"
29

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

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

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

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

61 62 63 64 65 66 67 68 69 70 71
    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;
      }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

623
  phi::KernelKey GetKernelTypeForVar(
624
      const std::string &var_name,
625
      const phi::DenseTensor &tensor,
626
      const phi::KernelKey &expected_kernel_type) const override {
627
    if (var_name == "ShapeTensor") {
628 629 630
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
631
    }
632 633
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
634
  }
635 636
};

637 638 639 640 641 642 643 644 645
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:
646
  phi::KernelKey GetExpectedKernelType(
647
      const framework::ExecutionContext &ctx) const override {
648 649
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "DDX"),
                          ctx.GetPlace());
650 651
  }

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

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

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

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

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

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

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

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

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