reshape_mkldnn_op.cc 18.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

15
#include "paddle/fluid/operators/flatten_op.h"
16 17 18
#include "paddle/fluid/operators/squeeze_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

19 20 21 22 23 24 25 26 27 28 29
namespace {
enum class ReshapeKernelOpName {
  reshape,
  reshape2,
  squeeze,
  squeeze2,
  flatten,
  flatten2,
};
}  // anonymous namespace

30 31 32 33 34
namespace paddle {
namespace operators {

using paddle::framework::LoDTensor;
using platform::GetMKLDNNFormat;
35
using platform::to_void_cast;
36

J
jakpiase 已提交
37
static std::vector<int> extract_shape(
38
    const std::vector<const phi::DenseTensor*>& list_new_shape_tensor) {
J
jakpiase 已提交
39 40 41 42 43
  std::vector<int> vec_new_shape;
  vec_new_shape.reserve(list_new_shape_tensor.size());

  for (const auto& tensor : list_new_shape_tensor) {
    PADDLE_ENFORCE_EQ(
44 45
        tensor->dims(),
        phi::make_ddim({1}),
J
jakpiase 已提交
46 47 48 49 50 51 52 53 54 55 56
        platform::errors::InvalidArgument(
            "If the element type of 'shape' in ReshapeOp is Tensor, "
            "the element's shape must be [1]. But received the element's shape "
            "is [%s]",
            tensor->dims()));
    vec_new_shape.emplace_back(*tensor->data<int32_t>());
  }

  return vec_new_shape;
}

57
template <typename T, ReshapeKernelOpName op_name>
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
class ReshapeMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    RunKernel(ctx);
  }

 private:
  void RunKernel(const framework::ExecutionContext& ctx) const {
    const auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    auto* x = ctx.Input<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");

73 74
    framework::DDim x_dims, out_dims;
    InferInOutShape(ctx, x_dims, out_dims);
75

76
    auto x_vec_dims = phi::vectorize(x_dims);
77

78 79 80
    dnnl::memory::data_type x_type =
        framework::ToMKLDNNDataType(framework::TransToProtoVarType(x->dtype()));
    platform::ReorderMKLDNNHandler reorder_handler(
81 82 83
        x_vec_dims,
        framework::TransToProtoVarType(x->dtype()),
        x_type,
84
        onednn_engine);
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        x->format(), platform::to_void_cast(x->data<T>()));
    out->Resize(x_dims);  // to match x numel, format is changed later
    // reorder is done into a plain tag to allow usage with blocked formats
    auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
        out, getPlainFormatTag(x), ctx.GetPlace());
    auto reorder_p = reorder_handler.AcquireReorder(reorder_src_memory_p,
                                                    reorder_dst_memory_p);

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);

    astream.wait();

    out->Resize(out_dims);
    out->set_layout(framework::DataLayout::kMKLDNN);
102
    out->set_format(GetMKLDNNFormat(
103
        reorder_dst_memory_p->get_desc().reshape(phi::vectorize(out_dims))));
104 105
  }

106
  void InferInOutShape(const framework::ExecutionContext& ctx,
107 108
                       framework::DDim& x_dims,            // NOLINT
                       framework::DDim& out_dims) const {  // NOLINT
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    switch (op_name) {
      case ReshapeKernelOpName::reshape:
        InferShapeReshapeOp(ctx, x_dims, out_dims);
        break;
      case ReshapeKernelOpName::reshape2:
        InferShapeReshape2Op(ctx, x_dims, out_dims);
        break;
      case ReshapeKernelOpName::squeeze:
        InferShapeSqueezeOp(ctx, x_dims, out_dims);
        break;
      case ReshapeKernelOpName::squeeze2:
        InferShapeSqueeze2Op(ctx, x_dims, out_dims);
        break;
      case ReshapeKernelOpName::flatten:
        InferShapeFlattenOp(ctx, x_dims, out_dims);
        break;
      case ReshapeKernelOpName::flatten2:
        InferShapeFlattenOp(ctx, x_dims, out_dims);
        break;
      default:
        PADDLE_THROW(paddle::platform::errors::OutOfRange(
            "Reshape kernel doesn not support that operator name"));
    }
  }

  void InferShapeReshapeOp(const framework::ExecutionContext& ctx,
135 136
                           framework::DDim& x_dims,            // NOLINT
                           framework::DDim& out_dims) const {  // NOLINT
137 138 139 140 141 142 143 144
    auto* x = ctx.Input<LoDTensor>("X");
    auto* out = ctx.Output<LoDTensor>("Out");
    x_dims = x->dims();
    out_dims = out->dims();
    ChangeReshapeOutDimsIfNeeded(ctx, x_dims, out_dims);
  }

  void InferShapeReshape2Op(const framework::ExecutionContext& ctx,
145 146
                            framework::DDim& x_dims,            // NOLINT
                            framework::DDim& out_dims) const {  // NOLINT
147 148 149
    auto* out = ctx.Output<LoDTensor>("Out");
    auto* xshape = ctx.Output<LoDTensor>("XShape");
    auto xshape_dims = xshape->dims();
150
    x_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size());
151 152 153 154 155 156
    out_dims = out->dims();
    ChangeReshapeOutDimsIfNeeded(ctx, x_dims, out_dims);
  }

  // in reshape1/2 ops  "ShapeTensor" has highest priority and "Shape" has
  // second highest priority
157 158 159 160
  void ChangeReshapeOutDimsIfNeeded(
      const framework::ExecutionContext& ctx,
      framework::DDim& x_dims,            // NOLINT
      framework::DDim& out_dims) const {  // NOLINT
161 162
    auto list_new_shape_tensor =
        ctx.MultiInput<phi::DenseTensor>("ShapeTensor");
163 164 165 166 167 168 169 170 171 172 173 174 175 176
    if (list_new_shape_tensor.size() > 0) {
      auto new_shape = extract_shape(list_new_shape_tensor);
      out_dims = ValidateShape(new_shape, x_dims);
    } else if (ctx.HasInput("Shape")) {
      auto* shape_tensor = ctx.Input<framework::LoDTensor>("Shape");
      auto* shape_data = shape_tensor->data<int>();

      auto shape =
          std::vector<int>(shape_data, shape_data + shape_tensor->numel());
      out_dims = ValidateShape(shape, x_dims);
    }
  }

  void InferShapeSqueezeOp(const framework::ExecutionContext& ctx,
177 178
                           framework::DDim& x_dims,            // NOLINT
                           framework::DDim& out_dims) const {  // NOLINT
179 180 181 182 183 184 185
    auto* x = ctx.Input<LoDTensor>("X");
    x_dims = x->dims();
    const auto& axes = ctx.Attr<std::vector<int>>("axes");
    out_dims = GetOutputShape(axes, x_dims, true);
  }

  void InferShapeSqueeze2Op(const framework::ExecutionContext& ctx,
186 187
                            framework::DDim& x_dims,            // NOLINT
                            framework::DDim& out_dims) const {  // NOLINT
188 189 190
    auto* out = ctx.Output<LoDTensor>("Out");
    auto* xshape = ctx.Output<LoDTensor>("XShape");
    auto xshape_dims = xshape->dims();
191
    x_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size());
192 193 194 195
    out_dims = out->dims();
  }

  void InferShapeFlattenOp(const framework::ExecutionContext& ctx,
196 197
                           framework::DDim& x_dims,            // NOLINT
                           framework::DDim& out_dims) const {  // NOLINT
198 199 200
    auto x = ctx.Input<LoDTensor>("X");
    x_dims = x->dims();
    auto axes = ctx.Attr<int>("axis");
201
    out_dims = phi::make_ddim(
L
Leo Chen 已提交
202
        FlattenKernel<phi::CPUContext, float>::GetOutputShape(axes, x_dims));
203 204
  }

205
 protected:
206 207
  static dnnl::memory::format_tag getPlainFormatTag(
      const phi::DenseTensor* tensor) {
208 209
    auto tensor_dims_size = tensor->dims().size();
    PADDLE_ENFORCE_EQ(
210 211
        tensor_dims_size <= 6 && tensor_dims_size >= 1,
        true,
212 213 214 215 216
        platform::errors::InvalidArgument(
            "Dims for squeeze_grad oneDNN op must be in range <1, 6>"));

    switch (tensor_dims_size) {
      case 1:
217
        return dnnl::memory::format_tag::a;
218
      case 2:
219
        return dnnl::memory::format_tag::ab;
220
      case 3:
221
        return dnnl::memory::format_tag::abc;
222
      case 4:
223
        return dnnl::memory::format_tag::abcd;
224
      case 5:
225
        return dnnl::memory::format_tag::abcde;
226
      default:
227
        return dnnl::memory::format_tag::abcdef;
228 229 230 231 232
    }
  }

  static framework::DDim ValidateShape(const std::vector<int>& shape,
                                       const framework::DDim& in_dims) {
233 234
    const int64_t in_size = phi::product(in_dims);
    auto in_dims_vec = phi::vectorize(in_dims);
235 236
    bool all_positive = std::all_of(in_dims_vec.cbegin(),
                                    in_dims_vec.cend(),
237 238 239 240 241 242 243 244 245 246 247 248
                                    [](int64_t i) { return i > 0; });
    // 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) {
        PADDLE_ENFORCE_EQ(
249 250
            unk_dim_idx,
            -1,
251 252 253
            platform::errors::InvalidArgument(
                "Only one dimension value of 'shape' in ReshapeOp can "
                "be -1. But received shape = [%s], shape[%d] is also -1.",
254 255
                phi::make_ddim(shape),
                i));
256 257 258
        unk_dim_idx = i;
      } else if (shape[i] == copy_dim_val) {
        PADDLE_ENFORCE_LT(
259 260
            static_cast<int>(i),
            in_dims.size(),
261 262 263 264 265
            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.",
266 267 268 269
                phi::make_ddim(shape),
                i,
                in_dims,
                in_dims.size()));
270 271
      } else {
        PADDLE_ENFORCE_GT(
272 273
            shape[i],
            0,
274 275 276 277
            platform::errors::InvalidArgument(
                "Each dimension value of 'shape' in ReshapeOp must not "
                "be negative except one unknown dimension. "
                "But received  shape = [%s], shape[%d] = %d.",
278 279 280
                phi::make_ddim(shape),
                i,
                shape[i]));
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
      }

      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) {
      if (all_positive) {
        // 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;
        PADDLE_ENFORCE_EQ(
296 297
            output_shape[unk_dim_idx] * capacity,
            -in_size,
298 299 300 301 302 303
            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, "
                "'shape' is [%s], known capacity of 'shape' is %d.",
304 305 306 307
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
308 309 310 311 312 313
      } else {
        output_shape[unk_dim_idx] = -1;
      }
    } else {
      if (all_positive) {
        PADDLE_ENFORCE_EQ(
314 315
            capacity,
            in_size,
316 317 318 319 320 321
            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.",
322 323 324 325
                in_dims,
                in_size,
                phi::make_ddim(shape),
                capacity));
326 327
      }
    }
328
    return phi::make_ddim(output_shape);
329 330 331
  }
};

332 333
template <typename T, ReshapeKernelOpName op_name>
class ReshapeGradMKLDNNKernel : public ReshapeMKLDNNKernel<T, op_name> {
334 335 336 337 338 339 340 341 342 343 344 345 346 347
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    RunKernel(ctx);
  }

 private:
  void RunKernel(const framework::ExecutionContext& ctx) const {
    const auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    auto* dout = ctx.Input<LoDTensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<LoDTensor>(framework::GradVarName("X"));

348 349 350
    framework::DDim dx_dims;
    InferOutputShapeInGrad(ctx, dx_dims);

351
    auto dout_vec_dims = phi::vectorize(dout->dims());
352

353 354 355
    dnnl::memory::data_type dout_type = framework::ToMKLDNNDataType(
        framework::TransToProtoVarType(dout->dtype()));
    platform::ReorderMKLDNNHandler reorder_handler(
356 357 358
        dout_vec_dims,
        framework::TransToProtoVarType(dout->dtype()),
        dout_type,
359
        onednn_engine);
360 361 362 363 364 365 366 367 368 369 370 371

    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        dout->format(), platform::to_void_cast(dout->data<T>()));
    auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
        dx, this->getPlainFormatTag(dout), ctx.GetPlace());
    auto reorder_p = reorder_handler.AcquireReorder(reorder_src_memory_p,
                                                    reorder_dst_memory_p);

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
    astream.wait();

372
    dx->Resize(dx_dims);
373
    dx->set_layout(framework::DataLayout::kMKLDNN);
374
    dx->set_format(GetMKLDNNFormat(
375
        reorder_dst_memory_p->get_desc().reshape(phi::vectorize(dx_dims))));
376 377
  }

378
  void InferOutputShapeInGrad(const framework::ExecutionContext& ctx,
379
                              framework::DDim& x_dims) const {  // NOLINT
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    switch (op_name) {
      case ReshapeKernelOpName::reshape:
        InferShapeReshapeSqueezeGradOp(ctx, x_dims);
        break;
      case ReshapeKernelOpName::reshape2:
        InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims);
        break;
      case ReshapeKernelOpName::squeeze:
        InferShapeReshapeSqueezeGradOp(ctx, x_dims);
        break;
      case ReshapeKernelOpName::squeeze2:
        InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims);
        break;
      case ReshapeKernelOpName::flatten:
        InferShapeFlattenGradOp(ctx, x_dims);
        break;
      case ReshapeKernelOpName::flatten2:
        InferShapeReshape2Squeeze2Flatten2GradOp(ctx, x_dims);
        break;
      default:
        PADDLE_THROW(paddle::platform::errors::OutOfRange(
            "Reshape grad kernel doesn not support that operator name"));
    }
  }
404

405 406 407
  void InferShapeReshapeSqueezeGradOp(
      const framework::ExecutionContext& ctx,
      framework::DDim& dx_dims) const {  // NOLINT
408 409 410
    auto* dx = ctx.Output<LoDTensor>(framework::GradVarName("X"));
    dx_dims = dx->dims();
  }
411

412
  void InferShapeReshape2Squeeze2Flatten2GradOp(
413 414
      const framework::ExecutionContext& ctx,
      framework::DDim& dx_dims) const {  // NOLINT
415
    auto xshape_dims = ctx.Input<framework::LoDTensor>("XShape")->dims();
416
    dx_dims = phi::slice_ddim(xshape_dims, 1, xshape_dims.size());
417
  }
418

419
  void InferShapeFlattenGradOp(const framework::ExecutionContext& ctx,
420
                               framework::DDim& dx_dims) const {  // NOLINT
421 422 423 424 425
    dx_dims = ctx.Input<LoDTensor>("X")->dims();
  }
};
}  // namespace operators
}  // namespace paddle
426

427 428
namespace ops = paddle::operators;
REGISTER_OP_KERNEL(
429 430 431
    squeeze,
    MKLDNN,
    paddle::platform::CPUPlace,
432 433 434 435 436
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::squeeze>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::squeeze>);

REGISTER_OP_KERNEL(
437 438 439
    squeeze_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
440 441 442 443 444
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::squeeze>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::squeeze>);

REGISTER_OP_KERNEL(
445 446 447
    squeeze2,
    MKLDNN,
    paddle::platform::CPUPlace,
448 449 450 451 452
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::squeeze2>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::squeeze2>);

REGISTER_OP_KERNEL(
453 454 455
    squeeze2_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
456 457 458 459 460
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::squeeze2>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::squeeze2>);

REGISTER_OP_KERNEL(
461 462 463
    reshape,
    MKLDNN,
    paddle::platform::CPUPlace,
464 465 466 467 468
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::reshape>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::reshape>);

REGISTER_OP_KERNEL(
469 470 471
    reshape_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
472 473 474 475 476
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::reshape>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::reshape>);

REGISTER_OP_KERNEL(
477 478 479
    reshape2,
    MKLDNN,
    paddle::platform::CPUPlace,
480 481 482 483 484
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::reshape2>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::reshape2>);

REGISTER_OP_KERNEL(
485 486 487
    reshape2_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
488 489 490 491 492
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::reshape2>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::reshape2>);

REGISTER_OP_KERNEL(
493 494 495
    flatten,
    MKLDNN,
    paddle::platform::CPUPlace,
496 497 498 499 500
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::flatten>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::flatten>);

REGISTER_OP_KERNEL(
501 502 503
    flatten_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
504 505 506 507 508
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::flatten>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::flatten>);

REGISTER_OP_KERNEL(
509 510 511
    flatten2,
    MKLDNN,
    paddle::platform::CPUPlace,
512 513 514 515 516
    ops::ReshapeMKLDNNKernel<float, ReshapeKernelOpName::flatten2>,
    ops::ReshapeMKLDNNKernel<paddle::platform::bfloat16,
                             ReshapeKernelOpName::flatten2>);

REGISTER_OP_KERNEL(
517 518 519
    flatten2_grad,
    MKLDNN,
    paddle::platform::CPUPlace,
520 521 522
    ops::ReshapeGradMKLDNNKernel<float, ReshapeKernelOpName::flatten2>,
    ops::ReshapeGradMKLDNNKernel<paddle::platform::bfloat16,
                                 ReshapeKernelOpName::flatten2>);