pattern_rewrite_test.cc 43.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2023 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.

#include <gtest/gtest.h>
16
#include <cstdint>
17 18 19 20
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
21

22
#include "paddle/fluid/ir/dialect/pd_attribute.h"
23
#include "paddle/fluid/ir/transforms/transform_general_functions.h"
24
#include "paddle/ir/core/builder.h"
25 26
#include "paddle/ir/core/builtin_attribute.h"
#include "paddle/ir/core/builtin_dialect.h"
27
#include "paddle/ir/core/builtin_op.h"
28
#include "paddle/ir/core/cast_utils.h"
29
#include "paddle/ir/core/dialect.h"
30
#include "paddle/ir/core/enforce.h"
31
#include "paddle/ir/core/ir_context.h"
32
#include "paddle/ir/core/op_info.h"
33
#include "paddle/ir/core/parameter.h"
34
#include "paddle/ir/core/program.h"
35
#include "paddle/ir/core/value.h"
36 37 38 39
#include "paddle/ir/pass/pass.h"
#include "paddle/ir/pass/pass_manager.h"
#include "paddle/ir/pattern_rewrite/frozen_rewrite_pattern_set.h"
#include "paddle/ir/pattern_rewrite/pattern_applicator.h"
40
#include "paddle/ir/pattern_rewrite/pattern_match.h"
41
#include "paddle/ir/pattern_rewrite/pattern_rewrite_driver.h"
42
#include "paddle/ir/transforms/dce.h"
43

44 45 46
// NOTE(zhangbo9674): File pd_op.h is generated by op_gen.py, see details in
// paddle/fluid/ir/dialect/CMakeLists.txt.
#include "paddle/fluid/ir/dialect/pd_op.h"
47 48

#include "paddle/fluid/ir/dialect/pd_dialect.h"
49
#include "paddle/fluid/ir/dialect/pd_type.h"
50
#include "paddle/phi/core/ddim.h"
51

52 53 54 55 56 57 58
// build Conv2dFusionOp
#include "paddle/fluid/ir/interface/infermeta.h"
#include "paddle/fluid/ir/interface/op_yaml_info.h"
#include "paddle/ir/core/op_base.h"
#include "paddle/phi/api/lib/utils/allocator.h"
#include "paddle/phi/infermeta/multiary.h"

59 60 61 62 63 64 65
// Define op1.
class Operation1 : public ir::Op<Operation1> {
 public:
  using Op::Op;
  static const char *name() { return "test.Operation1"; }
  static constexpr uint32_t attributes_num = 2;
  static const char *attributes_name[attributes_num];
66
  void Verify();
67 68
  static void InferShape() { VLOG(2) << "This is op2's InferShape interface."; }
};
69

70 71 72 73 74 75 76 77 78 79 80
void Operation1::Verify() {
  auto &attributes = this->attributes();
  if (attributes.count("op2_attr1") == 0 ||
      (!attributes.at("op2_attr1").isa<ir::StrAttribute>())) {
    throw("Type of attribute: parameter_name is not right.");
  }
  if (attributes.count("op2_attr2") == 0 ||
      (!attributes.at("op2_attr2").isa<ir::StrAttribute>())) {
    throw("Type of attribute: parameter_name is not right.");
  }
}
81 82
const char *Operation1::attributes_name[attributes_num] = {"op2_attr1",
                                                           "op2_attr2"};
83 84
IR_DECLARE_EXPLICIT_TYPE_ID(Operation1)
IR_DEFINE_EXPLICIT_TYPE_ID(Operation1)
85 86 87 88 89 90 91 92 93 94 95 96 97

// Define a dialect, op1 and op2 will be registered by this dialect.
class TestDialect : public ir::Dialect {
 public:
  explicit TestDialect(ir::IrContext *context)
      : ir::Dialect(name(), context, ir::TypeId::get<TestDialect>()) {
    initialize();
  }
  static const char *name() { return "test"; }

 private:
  void initialize() { RegisterOps<Operation1>(); }
};
98 99
IR_DECLARE_EXPLICIT_TYPE_ID(TestDialect)
IR_DEFINE_EXPLICIT_TYPE_ID(TestDialect)
100 101 102 103 104 105 106 107 108

// TODO(wilber): Add logical when ir support erase, replace or update.
class TestPatternRewrite : public ir::OpRewritePattern<Operation1> {
 public:
  using ir::OpRewritePattern<Operation1>::OpRewritePattern;

  void Rewrite(Operation1 op, ir::PatternRewriter &rewriter) const override {}
  bool Match(Operation1 op) const override { return false; }
};
109

110 111 112 113 114 115 116 117 118 119
class TestPatternRewrite2 : public ir::OpRewritePattern<Operation1> {
 public:
  using ir::OpRewritePattern<Operation1>::OpRewritePattern;
  bool MatchAndRewrite(
      Operation1 op,
      ir::PatternRewriter &rewriter) const override {  // NOLINT
    return false;
  }
};

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
TEST(PatternRewrite, PatternBenefit) {
  ir::PatternBenefit benefit1(1);
  EXPECT_EQ(benefit1.benefit(), 1U);
  ir::PatternBenefit benefit2(2);
  EXPECT_EQ(benefit2.benefit(), 2U);

  EXPECT_TRUE(benefit2 > benefit1);
  EXPECT_TRUE(benefit2 >= benefit1);
  EXPECT_TRUE(benefit1 < benefit2);
  EXPECT_TRUE(benefit1 <= benefit2);
  EXPECT_TRUE(benefit1 != benefit2);
  ir::PatternBenefit benefit3(2);
  EXPECT_TRUE(benefit2 == benefit3);
}

TEST(RewritePattern, RewritePatternSet) {
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  ir::IrContext *ctx = ir::IrContext::Instance();
  ctx->GetOrRegisterDialect<ir::BuiltinDialect>();
  auto *test_dialect = ctx->GetOrRegisterDialect<TestDialect>();
  test_dialect->RegisterOp<Operation1>();

  ir::RewritePatternSet ps(ctx);
  ps.Add<TestPatternRewrite>(ctx, 1);
  EXPECT_EQ(ps.native_patterns().size(), 1U);
  EXPECT_TRUE(ps.native_patterns().back()->debug_labels().empty());
  EXPECT_EQ(ps.native_patterns().back()->benefit(), 1U);
  ps.AddWithLabel<TestPatternRewrite2>({"TestPatternRewrite2"}, ctx, 2);
  EXPECT_EQ(ps.native_patterns().size(), 2U);
  EXPECT_EQ(ps.native_patterns().back()->debug_labels()[0],
            "TestPatternRewrite2");
  EXPECT_EQ(ps.native_patterns().back()->benefit(), 2U);

  ps.Clear();
  ps.Add<TestPatternRewrite, TestPatternRewrite2>(ctx, 2);
  EXPECT_EQ(ps.native_patterns().size(), 2U);
  EXPECT_EQ(ps.native_patterns()[0]->benefit(), 2U);
  EXPECT_EQ(ps.native_patterns()[1]->benefit(), 2U);
}
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

// TODO(wilber): Add actual case.
// TEST(PatternRewrite, PatternApplicator) {
//   ir::IrContext *ctx = ir::IrContext::Instance();
//   ctx->GetOrRegisterDialect<ir::BuiltinDialect>();
//   auto *test_dialect = ctx->GetOrRegisterDialect<TestDialect>();
//   test_dialect->RegisterOp<Operation1>();
//   ir::RewritePatternSet ps(ctx);
//   ps.Add<TestPatternRewrite, TestPatternRewrite2>(ctx, 2);
//   ir::FrozenRewritePatternSet frozen_set(std::move(ps));
//   ir::PatternApplicator applicator(frozen_set);
//   applicator.ApplyDefaultCostModel();
// }

// // TODO(wilber): Add actual case.
TEST(PatternRewrite, FrozenRewritePatternSet) {
  ir::FrozenRewritePatternSet frozen_set;
  EXPECT_TRUE(frozen_set.match_any_op_native_patterns().empty());
  EXPECT_TRUE(frozen_set.op_specific_native_patterns().empty());

  ir::IrContext *ctx = ir::IrContext::Instance();
  ctx->GetOrRegisterDialect<ir::BuiltinDialect>();
  auto *test_dialect = ctx->GetOrRegisterDialect<TestDialect>();
  test_dialect->RegisterOp<Operation1>();
  ir::RewritePatternSet ps(ctx);
  ps.Add<TestPatternRewrite, TestPatternRewrite2>(ctx, 2);

  ir::FrozenRewritePatternSet frozen_set2(std::move(ps));
  EXPECT_TRUE(frozen_set2.match_any_op_native_patterns().empty());
  const auto &pattern_maps = frozen_set2.op_specific_native_patterns();
  EXPECT_EQ(pattern_maps.size(), 1U);
  EXPECT_EQ(pattern_maps.at(ctx->GetRegisteredOpInfo("test.Operation1")).size(),
            2U);
}

Y
Yuanle Liu 已提交
193
class RedundantTransposeFusePattern
194 195 196 197 198 199
    : public ir::OpRewritePattern<paddle::dialect::TransposeOp> {
 public:
  using ir::OpRewritePattern<paddle::dialect::TransposeOp>::OpRewritePattern;

  bool MatchAndRewrite(paddle::dialect::TransposeOp op,
                       ir::PatternRewriter &rewriter) const override {
200
    auto prev_op = ir::GetDefiningOpForInput<0>(op);
201 202 203 204 205 206 207 208
    std::vector<int> axis_last = GetAxis(op);
    auto prev_trans_op = prev_op->dyn_cast<paddle::dialect::TransposeOp>();
    if (prev_trans_op) {
      std::vector<int> axis_first = GetAxis(prev_trans_op);
      IR_ENFORCE(axis_first.size() == axis_last.size(),
                 "tranpose op's perm rank should be same.");
      auto new_perm = GetPerm(axis_first, axis_last);
      rewriter.SetInsertionPoint(op);
209 210 211
      auto new_transpose_op = rewriter.Build<paddle::dialect::TransposeOp>(
          ir::GetDefiningOpForInput<0>(prev_trans_op)->result(0), new_perm);
      rewriter.ReplaceOp(op, {new_transpose_op.out()});
212 213 214 215 216 217 218 219
      return true;
    }

    return false;
  }

 private:
  std::vector<int> GetAxis(paddle::dialect::TransposeOp op) const {
220
    auto array_attr = op.attribute<ir::ArrayAttribute>("perm").data();
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    std::vector<int> axis(array_attr.size());
    for (size_t i = 0; i < array_attr.size(); ++i) {
      axis[i] = array_attr[i].dyn_cast<ir::Int32Attribute>().data();
    }
    return axis;
  }

  std::vector<int> GetPerm(const std::vector<int> &perm1,
                           const std::vector<int> &perm2) const {
    int n = perm1.size();
    std::vector<int> axis(n), axis1(n), axis2(n);
    std::iota(axis.begin(), axis.end(), 0);
    for (int i = 0; i < n; ++i) {
      axis1[i] = axis[perm1[i]];
    }
    for (int i = 0; i < n; ++i) {
      axis2[i] = axis1[perm2[i]];
    }
    return axis2;
  }
};

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
class Conv2dBnFusePattern
    : public ir::OpRewritePattern<paddle::dialect::BatchNormOp> {
 public:
  using ir::OpRewritePattern<paddle::dialect::BatchNormOp>::OpRewritePattern;
  bool MatchAndRewrite(
      paddle::dialect::BatchNormOp op,
      ir::PatternRewriter &rewriter) const override {  // NOLINT
    // The next op should be batch_norm.
    paddle::dialect::Conv2dOp conv2d_op =
        ir::GetDefiningOpForInput(op)->dyn_cast<paddle::dialect::Conv2dOp>();
    if (!conv2d_op) return false;

    ir::OpResult conv2d_out = conv2d_op.out();
    if (!conv2d_out.HasOneUse()) return false;

    ir::Value conv2d_filter = conv2d_op.filter();

    // ir::GetParameterOp filter_parameter_op =
    //     conv2d_filter.GetDefiningOp()->dyn_cast<ir::GetParameterOp>();
    // if (!filter_parameter_op) return false;

    ir::OpResult conv2d_filter_result = conv2d_filter.dyn_cast<ir::OpResult>();
    IR_ENFORCE(conv2d_filter_result);

    ir::Value bn_input = op.x();
    IR_ENFORCE(bn_input == conv2d_out);

    ir::Value bn_mean = op.mean();
    ir::Value bn_variance = op.variance();
    ir::Value bn_scale = op.scale();
    ir::Value bn_bias = op.bias();

    // --- deal with filter ---
Y
Yuanle Liu 已提交
276
    rewriter.SetInsertionPoint(op);
277 278 279 280 281 282
    phi::DDim bn_variance_shape =
        bn_variance.type().dyn_cast<paddle::dialect::DenseTensorType>().dims();
    float epsilon = op.attribute<ir::FloatAttribute>("epsilon").data();
    paddle::dialect::FullOp full_op = rewriter.Build<paddle::dialect::FullOp>(
        phi::vectorize(bn_variance_shape), epsilon);
    paddle::dialect::AddOp add_op = rewriter.Build<paddle::dialect::AddOp>(
Y
Yuanle Liu 已提交
283
        bn_variance.dyn_cast<ir::OpResult>(), full_op.out());
284 285 286
    paddle::dialect::SqrtOp sqrt_op =
        rewriter.Build<paddle::dialect::SqrtOp>(add_op.out());
    paddle::dialect::DivideOp div_op =
Y
Yuanle Liu 已提交
287 288
        rewriter.Build<paddle::dialect::DivideOp>(
            bn_scale.dyn_cast<ir::OpResult>(), sqrt_op.out());
289 290 291 292 293 294 295 296 297 298 299 300 301
    // reshape scale
    phi::DDim conv2d_filter_shape = ir::GetShapeFromValue(conv2d_filter);
    phi::DDim bn_scale_shape =
        bn_scale.type().dyn_cast<paddle::dialect::DenseTensorType>().dims();
    std::vector<int64_t> bn_scale_new_shape(conv2d_filter_shape.size(), 1);
    bn_scale_new_shape[0] = bn_scale_shape[0];
    paddle::dialect::ReshapeOp reshape_scale_op =
        rewriter.Build<paddle::dialect::ReshapeOp>(div_op.out(),
                                                   bn_scale_new_shape);
    // new filter --> mul_op.out()
    paddle::dialect::MultiplyOp mul_op =
        rewriter.Build<paddle::dialect::MultiplyOp>(conv2d_filter_result,
                                                    reshape_scale_op.out());
Y
Yuanle Liu 已提交
302 303 304 305 306 307

    auto conv2d_attributes = conv2d_op->attributes();
    auto new_conv2d_op = rewriter.Build<paddle::dialect::Conv2dOp>(
        conv2d_op.input().dyn_cast<ir::OpResult>(),
        mul_op.out(),
        conv2d_attributes);
308 309 310

    // --- deal with bias ---
    paddle::dialect::MultiplyOp mul_bias_op =
Y
Yuanle Liu 已提交
311 312
        rewriter.Build<paddle::dialect::MultiplyOp>(
            bn_mean.dyn_cast<ir::OpResult>(), div_op.out());
313 314
    // new bias --> sub_op.out()
    paddle::dialect::SubtractOp sub_op =
Y
Yuanle Liu 已提交
315 316
        rewriter.Build<paddle::dialect::SubtractOp>(
            bn_bias.dyn_cast<ir::OpResult>(), mul_bias_op.out());
317
    // reshape new bias
Y
Yuanle Liu 已提交
318 319
    phi::DDim new_conv2d_out_shape = ir::GetShapeFromValue(new_conv2d_op.out());
    std::vector<int64_t> new_bias_new_shape(new_conv2d_out_shape.size(), 1);
320
    std::string data_format =
Y
Yuanle Liu 已提交
321
        new_conv2d_op.attribute<ir::StrAttribute>("data_format").data();
322
    IR_ENFORCE(data_format == "NCHW", "Only support NCHW now.");
Y
Yuanle Liu 已提交
323 324
    new_bias_new_shape[0] = new_conv2d_out_shape[0];
    new_bias_new_shape[1] = new_conv2d_out_shape[1];
325 326 327 328
    paddle::dialect::ReshapeOp reshape_bias_op =
        rewriter.Build<paddle::dialect::ReshapeOp>(sub_op.out(),
                                                   new_bias_new_shape);
    paddle::dialect::AddOp add_bias_op = rewriter.Build<paddle::dialect::AddOp>(
Y
Yuanle Liu 已提交
329 330 331
        new_conv2d_op.out(), reshape_bias_op.out());

    rewriter.ReplaceAllUsesWith(op.out(), add_bias_op.out());
332 333

    rewriter.EraseOp(op);
Y
Yuanle Liu 已提交
334
    rewriter.EraseOp(conv2d_op);
335 336 337 338
    return true;
  }
};

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 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 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
namespace paddle {
namespace dialect {
class Conv2dFusionOpTest : public ir::Op<Conv2dFusionOpTest,
                                         OpYamlInfoInterface,
                                         InferMetaInterface> {
 public:
  using Op::Op;
  static const char *name() { return "pd.conv2d_fusion_test"; }
  static const char *attributes_name[10];
  static constexpr uint32_t attributes_num = 10;
  static OpInfoTuple GetOpInfo();
  static void Build(ir::Builder &builder,             // NOLINT
                    ir::OperationArgument &argument,  // NOLINT
                    ir::OpResult input_,
                    ir::OpResult filter_,
                    ir::OpResult bias_,
                    ir::OpResult residual_,
                    const std::vector<int> &strides,
                    const std::vector<int> &paddings_t,
                    std::string padding_algorithm,
                    const std::vector<int> &dilations_t,
                    int groups,
                    std::string data_format,
                    std::string activation,
                    bool exhaustive_search,
                    const std::vector<int> &channels,
                    int user_workspace_size);

  static void Build(ir::Builder &builder,             // NOLINT
                    ir::OperationArgument &argument,  // NOLINT
                    ir::OpResult input_,
                    ir::OpResult filter_,
                    ir::OpResult bias_,
                    ir::OpResult residual_,
                    ir::AttributeMap attributes);
  void Verify();
  ir::Value input() { return operand(0); }
  ir::Value filter() { return operand(1); }
  ir::Value bias() { return operand(2); }
  ir::Value residual() { return operand(3); }
  ir::OpResult output() { return result(0); }
  ir::OpResult outputs() { return result(1); }
  ir::Attribute attribute(const std::string &name) {
    {
      PADDLE_ENFORCE(
          attributes().count(name) > 0,
          phi::errors::PreconditionNotMet("Attribute is not exist."));
      return attributes().at(name);
    }
  }
  template <typename T>
  T attribute(const std::string &name) {
    {
      PADDLE_ENFORCE(
          attributes().count(name) > 0 && attributes().at(name).isa<T>(),
          phi::errors::PreconditionNotMet("Attribute is not right."));
      return attributes().at(name).dyn_cast<T>();
    }
  }

  static void InferMeta(phi::InferMetaContext *infer_meta);
};

const char *Conv2dFusionOpTest::attributes_name[10] = {"strides",
                                                       "paddings_t",
                                                       "padding_algorithm",
                                                       "dilations_t",
                                                       "groups",
                                                       "data_format",
                                                       "activation",
                                                       "exhaustive_search",
                                                       "channels",
                                                       "user_workspace_size"};

OpInfoTuple Conv2dFusionOpTest::GetOpInfo() {
  std::vector<paddle::dialect::OpInputInfo> inputs = {
      OpInputInfo(
          "input", "paddle::dialect::DenseTensorType", false, false, false),
      OpInputInfo(
          "filter", "paddle::dialect::DenseTensorType", false, false, false),
      OpInputInfo(
          "bias", "paddle::dialect::DenseTensorType", false, false, false),
      OpInputInfo(
          "residual", "paddle::dialect::DenseTensorType", true, false, false)};
  std::vector<paddle::dialect::OpAttributeInfo> attributes = {
      OpAttributeInfo("strides", "ir::ArrayAttribute<ir::Int32Attribute>", ""),
      OpAttributeInfo(
          "paddings_t", "ir::ArrayAttribute<ir::Int32Attribute>", ""),
      OpAttributeInfo("padding_algorithm", "ir::StrAttribute", ""),
      OpAttributeInfo(
          "dilations_t", "ir::ArrayAttribute<ir::Int32Attribute>", ""),
      OpAttributeInfo("groups", "ir::Int32Attribute", ""),
      OpAttributeInfo("data_format", "ir::StrAttribute", ""),
      OpAttributeInfo("activation", "ir::StrAttribute", ""),
      OpAttributeInfo("exhaustive_search", "ir::BoolAttribute", ""),
      OpAttributeInfo("channels", "ir::ArrayAttribute<ir::Int32Attribute>", ""),
      OpAttributeInfo("user_workspace_size", "ir::Int32Attribute", "")};
  std::vector<paddle::dialect::OpOutputInfo> outputs = {
      OpOutputInfo("output", "paddle::dialect::DenseTensorType", false, false),
      OpOutputInfo("outputs",
                   "ir::VectorType<paddle::dialect::DenseTensorType>",
                   false,
                   false)};
  paddle::dialect::OpRunTimeInfo run_time_info =
      OpRunTimeInfo("Conv2dFusionInferMeta",
                    {"input",
                     "filter",
                     "bias",
                     "residual",
                     "strides",
                     "paddings_t",
                     "padding_algorithm",
                     "dilations_t",
                     "groups",
                     "data_format",
                     "activation",
                     "exhaustive_search",
                     "channels",
                     "user_workspace_size"},
                    {"ConvFusionKernel"},
                    {"input",
                     "filter",
                     "bias",
                     "residual",
                     "strides",
                     "paddings_t",
                     "padding_algorithm",
                     "dilations_t",
                     "groups",
                     "data_format",
                     "activation",
                     "exhaustive_search",
                     "channels",
                     "user_workspace_size"},
                    {"input"},
                    {},
                    {});

  return std::make_tuple(inputs, attributes, outputs, run_time_info);
}

void Conv2dFusionOpTest::Build(ir::Builder &builder,
                               ir::OperationArgument &argument,
                               ir::OpResult input_,
                               ir::OpResult filter_,
                               ir::OpResult bias_,
                               ir::OpResult residual_,
                               ir::AttributeMap attributes) {
  std::vector<int> strides;
  for (size_t i = 0;
       i < attributes.at("strides").dyn_cast<ir::ArrayAttribute>().size();
       i++) {
    strides.push_back(attributes.at("strides")
                          .dyn_cast<ir::ArrayAttribute>()[i]
                          .dyn_cast<ir::Int32Attribute>()
                          .data());
  }

  std::vector<int> paddings_t;
  for (size_t i = 0;
       i < attributes.at("paddings_t").dyn_cast<ir::ArrayAttribute>().size();
       i++) {
    paddings_t.push_back(attributes.at("paddings_t")
                             .dyn_cast<ir::ArrayAttribute>()[i]
                             .dyn_cast<ir::Int32Attribute>()
                             .data());
  }

  std::string padding_algorithm =
      attributes.at("padding_algorithm").dyn_cast<ir::StrAttribute>().data();
  std::vector<int> dilations_t;
  for (size_t i = 0;
       i < attributes.at("dilations_t").dyn_cast<ir::ArrayAttribute>().size();
       i++) {
    dilations_t.push_back(attributes.at("dilations_t")
                              .dyn_cast<ir::ArrayAttribute>()[i]
                              .dyn_cast<ir::Int32Attribute>()
                              .data());
  }
  int groups = attributes.at("groups").dyn_cast<ir::Int32Attribute>().data();
  std::string data_format =
      attributes.at("data_format").dyn_cast<ir::StrAttribute>().data();
  std::string activation =
      attributes.at("activation").dyn_cast<ir::StrAttribute>().data();
  bool exhaustive_search =
      attributes.at("exhaustive_search").dyn_cast<ir::BoolAttribute>().data();
  std::vector<int> channels;
  for (size_t i = 0;
       i < attributes.at("channels").dyn_cast<ir::ArrayAttribute>().size();
       i++) {
    channels.push_back(attributes.at("channels")
                           .dyn_cast<ir::ArrayAttribute>()[i]
                           .dyn_cast<ir::Int32Attribute>()
                           .data());
  }
  int user_workspace_size = attributes.at("user_workspace_size")
                                .dyn_cast<ir::Int32Attribute>()
                                .data();

  VLOG(4) << "Builder construction inputs";
  std::vector<ir::OpResult> argument_inputs = {
      input_, filter_, bias_, residual_};
  argument.AddOperands(argument_inputs.begin(), argument_inputs.end());

  VLOG(4) << "Builder construction attributes";
  std::vector<ir::Attribute> vec_strides;
  for (size_t i = 0; i < static_cast<size_t>(strides.size()); i++) {
    ir::Attribute attr_strides =
        ir::Int32Attribute::get(ir::IrContext::Instance(), strides[i]);

    vec_strides.push_back(attr_strides);
  }
  ir::Attribute attr_strides =
      ir::ArrayAttribute::get(ir::IrContext::Instance(), vec_strides);
  argument.AddAttribute("strides", attr_strides);
  std::vector<ir::Attribute> vec_paddings_t;
  for (size_t i = 0; i < static_cast<size_t>(paddings_t.size()); i++) {
    ir::Attribute attr_paddings_t =
        ir::Int32Attribute::get(ir::IrContext::Instance(), paddings_t[i]);

    vec_paddings_t.push_back(attr_paddings_t);
  }
  ir::Attribute attr_paddings_t =
      ir::ArrayAttribute::get(ir::IrContext::Instance(), vec_paddings_t);
  argument.AddAttribute("paddings_t", attr_paddings_t);
  ir::Attribute attr_padding_algorithm =
      ir::StrAttribute::get(ir::IrContext::Instance(), padding_algorithm);
  argument.AddAttribute("padding_algorithm", attr_padding_algorithm);
  std::vector<ir::Attribute> vec_dilations_t;
  for (size_t i = 0; i < static_cast<size_t>(dilations_t.size()); i++) {
    ir::Attribute attr_dilations_t =
        ir::Int32Attribute::get(ir::IrContext::Instance(), dilations_t[i]);

    vec_dilations_t.push_back(attr_dilations_t);
  }
  ir::Attribute attr_dilations_t =
      ir::ArrayAttribute::get(ir::IrContext::Instance(), vec_dilations_t);
  argument.AddAttribute("dilations_t", attr_dilations_t);
  ir::Attribute attr_groups =
      ir::Int32Attribute::get(ir::IrContext::Instance(), groups);
  argument.AddAttribute("groups", attr_groups);
  ir::Attribute attr_data_format =
      ir::StrAttribute::get(ir::IrContext::Instance(), data_format);
  argument.AddAttribute("data_format", attr_data_format);
  ir::Attribute attr_activation =
      ir::StrAttribute::get(ir::IrContext::Instance(), activation);
  argument.AddAttribute("activation", attr_activation);
  ir::Attribute attr_exhaustive_search =
      ir::BoolAttribute::get(ir::IrContext::Instance(), exhaustive_search);
  argument.AddAttribute("exhaustive_search", attr_exhaustive_search);
  std::vector<ir::Attribute> vec_channels;
  for (size_t i = 0; i < static_cast<size_t>(channels.size()); i++) {
    ir::Attribute attr_channels =
        ir::Int32Attribute::get(ir::IrContext::Instance(), channels[i]);

    vec_channels.push_back(attr_channels);
  }
  ir::Attribute attr_channels =
      ir::ArrayAttribute::get(ir::IrContext::Instance(), vec_channels);
  argument.AddAttribute("channels", attr_channels);
  ir::Attribute attr_user_workspace_size =
      ir::Int32Attribute::get(ir::IrContext::Instance(), user_workspace_size);
  argument.AddAttribute("user_workspace_size", attr_user_workspace_size);

  VLOG(4) << "Builder construction outputs";
  paddle::dialect::DenseTensorType input =
      input_.type().dyn_cast<paddle::dialect::DenseTensorType>();
  (void)input;
  paddle::dialect::DenseTensorType filter =
      filter_.type().dyn_cast<paddle::dialect::DenseTensorType>();
  (void)filter;
  paddle::dialect::DenseTensorType bias =
      bias_.type().dyn_cast<paddle::dialect::DenseTensorType>();
  (void)bias;
  // paddle::dialect::DenseTensorType residual =
  // residual_.type().dyn_cast<paddle::dialect::DenseTensorType>();
  // (void)residual;

  VLOG(4) << "Builder construction  dense_input";
  phi::DenseTensor dense_input(
      std::make_unique<paddle::experimental::DefaultAllocator>(
          paddle::platform::CPUPlace())
          .get(),
      phi::DenseTensorMeta(TransToPhiDataType(input.dtype()),
                           input.dims(),
                           input.data_layout(),
                           input.lod(),
                           input.offset()));
  VLOG(4) << "Builder construction  meta_input";
  phi::MetaTensor meta_input(&dense_input);

  VLOG(4) << "Builder construction  dense_filter";
  phi::DenseTensor dense_filter(
      std::make_unique<paddle::experimental::DefaultAllocator>(
          paddle::platform::CPUPlace())
          .get(),
      phi::DenseTensorMeta(TransToPhiDataType(filter.dtype()),
                           filter.dims(),
                           filter.data_layout(),
                           filter.lod(),
                           filter.offset()));
  VLOG(4) << "Builder construction  meta_filter";
  phi::MetaTensor meta_filter(&dense_filter);

  VLOG(4) << "Builder construction  dense_bias";
  phi::DenseTensor dense_bias(
      std::make_unique<paddle::experimental::DefaultAllocator>(
          paddle::platform::CPUPlace())
          .get(),
      phi::DenseTensorMeta(TransToPhiDataType(bias.dtype()),
                           bias.dims(),
                           bias.data_layout(),
                           bias.lod(),
                           bias.offset()));
  VLOG(4) << "Builder construction  meta_bias";
  phi::MetaTensor meta_bias(&dense_bias);

  // VLOG(4) << "Builder construction  dense_residual";
  // phi::DenseTensor
  // dense_residual(std::make_unique<paddle::experimental::DefaultAllocator>(paddle::platform::CPUPlace()).get(),
  //                               phi::DenseTensorMeta(TransToPhiDataType(residual.dtype()),
  //                                                    residual.dims(),
  //                                                    residual.data_layout(),
  //                                                    residual.lod(),
  //                                                    residual.offset()));
  VLOG(4) << "Builder construction  meta_residual";
  // phi::MetaTensor meta_residual(&dense_residual);
  phi::MetaTensor meta_residual;
  phi::DenseTensor dense_output;
  phi::MetaTensor meta_output(&dense_output);
  std::vector<phi::DenseTensor> vec_dense_outputs((channels.size()),
                                                  phi::DenseTensor());
  std::vector<phi::MetaTensor> vec_meta_outputs;
  for (size_t i = 0; i < static_cast<size_t>(channels.size()); i++) {
    vec_meta_outputs.push_back(phi::MetaTensor(&vec_dense_outputs[i]));
  }
  std::vector<phi::MetaTensor *> meta_outputs;
  for (size_t i = 0; i < static_cast<size_t>(vec_meta_outputs.size()); i++) {
    meta_outputs.push_back(&vec_meta_outputs[i]);
  }

  phi::FusedConvInferMeta(meta_input,
                          meta_filter,
                          meta_bias,
                          meta_residual,
                          strides,
                          paddings_t,
                          padding_algorithm,
                          dilations_t,
                          groups,
                          data_format,
                          "float32",
                          "identity",
                          false,
                          false,
                          &meta_output,
                          phi::MetaConfig());

  std::vector<ir::Type> argument_outputs;
  auto output_dense_tensor_type = paddle::dialect::DenseTensorType::get(
      ir::IrContext::Instance(),
      TransToIrDataType(dense_output.dtype()),
      dense_output.dims(),
      dense_output.layout(),
      dense_output.lod(),
      dense_output.offset());
  LOG(INFO) << output_dense_tensor_type;

  argument_outputs.push_back(output_dense_tensor_type);

  std::vector<ir::Type> outputs_types;
  for (size_t i = 0; i < static_cast<size_t>(channels.size()); i++) {
    outputs_types.push_back(paddle::dialect::DenseTensorType::get(
        ir::IrContext::Instance(),
        TransToIrDataType(vec_dense_outputs[i].dtype()),
        vec_dense_outputs[i].dims(),
        vec_dense_outputs[i].layout(),
        vec_dense_outputs[i].lod(),
        vec_dense_outputs[i].offset()));
  }
  ir::Type outputs_vector_type =
      ir::VectorType::get(ir::IrContext::Instance(), outputs_types);
  argument_outputs.push_back(outputs_vector_type);
  argument.AddOutputs(argument_outputs.begin(), argument_outputs.end());
}

void Conv2dFusionOpTest::Verify() {
  VLOG(4)
      << "Start Verifying inputs, outputs and attributes for: Conv2dFusionOp.";
  VLOG(4) << "Verifying inputs:";
  {
    auto input_size = num_operands();
    PADDLE_ENFORCE_EQ(
        input_size,
        4u,
        phi::errors::PreconditionNotMet(
            "The size %d of inputs must be equal to 4.", input_size));
    PADDLE_ENFORCE(
        (*this)->operand(0).type().isa<paddle::dialect::DenseTensorType>(),
        phi::errors::PreconditionNotMet(
            "Type validation failed for the 0th input."));
    PADDLE_ENFORCE(
        (*this)->operand(1).type().isa<paddle::dialect::DenseTensorType>(),
        phi::errors::PreconditionNotMet(
            "Type validation failed for the 1th input."));
    PADDLE_ENFORCE(
        (*this)->operand(2).type().isa<paddle::dialect::DenseTensorType>(),
        phi::errors::PreconditionNotMet(
            "Type validation failed for the 2th input."));
    if (auto val = (*this)->op_operand(3)) {
      PADDLE_ENFORCE(val.type().isa<paddle::dialect::DenseTensorType>(),
                     phi::errors::PreconditionNotMet(
                         "Type validation failed for the 3th input."));
    }
  }
  VLOG(4) << "Verifying attributes:";
  {
    auto &attributes = this->attributes();
    PADDLE_ENFORCE(attributes.count("strides") > 0 &&
                       attributes.at("strides").isa<ir::ArrayAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: strides is not right."));
    for (size_t i = 0;
         i < attributes.at("strides").dyn_cast<ir::ArrayAttribute>().size();
         i++) {
      PADDLE_ENFORCE(attributes.at("strides")
                         .dyn_cast<ir::ArrayAttribute>()[i]
                         .isa<ir::Int32Attribute>(),
                     phi::errors::PreconditionNotMet(
                         "Type of attribute: strides is not right."));
    }
    PADDLE_ENFORCE(attributes.count("paddings_t") > 0 &&
                       attributes.at("paddings_t").isa<ir::ArrayAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: paddings_t is not right."));
    for (size_t i = 0;
         i < attributes.at("paddings_t").dyn_cast<ir::ArrayAttribute>().size();
         i++) {
      PADDLE_ENFORCE(attributes.at("paddings_t")
                         .dyn_cast<ir::ArrayAttribute>()[i]
                         .isa<ir::Int32Attribute>(),
                     phi::errors::PreconditionNotMet(
                         "Type of attribute: paddings_t is not right."));
    }
    PADDLE_ENFORCE(
        attributes.count("padding_algorithm") > 0 &&
            attributes.at("padding_algorithm").isa<ir::StrAttribute>(),
        phi::errors::PreconditionNotMet(
            "Type of attribute: padding_algorithm is not right."));
    PADDLE_ENFORCE(attributes.count("dilations_t") > 0 &&
                       attributes.at("dilations_t").isa<ir::ArrayAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: dilations_t is not right."));
    for (size_t i = 0;
         i < attributes.at("dilations_t").dyn_cast<ir::ArrayAttribute>().size();
         i++) {
      PADDLE_ENFORCE(attributes.at("dilations_t")
                         .dyn_cast<ir::ArrayAttribute>()[i]
                         .isa<ir::Int32Attribute>(),
                     phi::errors::PreconditionNotMet(
                         "Type of attribute: dilations_t is not right."));
    }
    PADDLE_ENFORCE(attributes.count("groups") > 0 &&
                       attributes.at("groups").isa<ir::Int32Attribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: groups is not right."));
    PADDLE_ENFORCE(attributes.count("data_format") > 0 &&
                       attributes.at("data_format").isa<ir::StrAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: data_format is not right."));
    PADDLE_ENFORCE(attributes.count("activation") > 0 &&
                       attributes.at("activation").isa<ir::StrAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: activation is not right."));
    PADDLE_ENFORCE(
        attributes.count("exhaustive_search") > 0 &&
            attributes.at("exhaustive_search").isa<ir::BoolAttribute>(),
        phi::errors::PreconditionNotMet(
            "Type of attribute: exhaustive_search is not right."));
    PADDLE_ENFORCE(attributes.count("channels") > 0 &&
                       attributes.at("channels").isa<ir::ArrayAttribute>(),
                   phi::errors::PreconditionNotMet(
                       "Type of attribute: channels is not right."));
    for (size_t i = 0;
         i < attributes.at("channels").dyn_cast<ir::ArrayAttribute>().size();
         i++) {
      PADDLE_ENFORCE(attributes.at("channels")
                         .dyn_cast<ir::ArrayAttribute>()[i]
                         .isa<ir::Int32Attribute>(),
                     phi::errors::PreconditionNotMet(
                         "Type of attribute: channels is not right."));
    }
    PADDLE_ENFORCE(
        attributes.count("user_workspace_size") > 0 &&
            attributes.at("user_workspace_size").isa<ir::Int32Attribute>(),
        phi::errors::PreconditionNotMet(
            "Type of attribute: user_workspace_size is not right."));
  }
  VLOG(4) << "Verifying outputs:";
  {
    auto output_size = num_results();
    PADDLE_ENFORCE_EQ(
        output_size,
        2u,
        phi::errors::PreconditionNotMet(
            "The size %d of outputs must be equal to 2.", output_size));
    PADDLE_ENFORCE(
        (*this)->result(0).type().isa<paddle::dialect::DenseTensorType>(),
        phi::errors::PreconditionNotMet(
            "Type validation failed for the 0th output."));
    auto output_1_type = (*this)->result(1).type();
    if (auto vec_type = output_1_type.dyn_cast<ir::VectorType>()) {
      for (size_t i = 0; i < vec_type.size(); i++) {
        PADDLE_ENFORCE(vec_type[i].isa<paddle::dialect::DenseTensorType>(),
                       phi::errors::PreconditionNotMet(
                           "Type validation failed for the 1th output."));
      }
    } else {
      PADDLE_ENFORCE(output_1_type.isa<paddle::dialect::DenseTensorType>(),
                     phi::errors::PreconditionNotMet(
                         "Type validation failed for the 1th output."));
    }
  }
  VLOG(4) << "End Verifying for: Conv2dFusionOp.";
}

void Conv2dFusionOpTest::InferMeta(phi::InferMetaContext *infer_meta) {
  auto fn = PD_INFER_META(phi::FusedConvInferMeta);
  fn(infer_meta);
}
}  // namespace dialect
}  // namespace paddle

IR_DECLARE_EXPLICIT_TYPE_ID(paddle::dialect::Conv2dFusionOpTest)
IR_DEFINE_EXPLICIT_TYPE_ID(paddle::dialect::Conv2dFusionOpTest)

class Conv2dFusionTestDialect : public ir::Dialect {
 public:
  explicit Conv2dFusionTestDialect(ir::IrContext *context)
      : ir::Dialect(name(), context, ir::TypeId::get<TestDialect>()) {
    initialize();
  }
  static const char *name() { return "con2d fusion test"; }

 private:
  void initialize() { RegisterOps<paddle::dialect::Conv2dFusionOpTest>(); }
};
IR_DECLARE_EXPLICIT_TYPE_ID(Conv2dFusionTestDialect)
IR_DEFINE_EXPLICIT_TYPE_ID(Conv2dFusionTestDialect)

class Conv2dAddFusePattern
    : public ir::OpRewritePattern<paddle::dialect::AddOp> {
 public:
  using ir::OpRewritePattern<paddle::dialect::AddOp>::OpRewritePattern;
  bool MatchAndRewrite(
      paddle::dialect::AddOp op,
      ir::PatternRewriter &rewriter) const override {  // NOLINT
    // The next op should be add.
    paddle::dialect::Conv2dOp conv2d_op =
        ir::GetDefiningOpForInput(op)->dyn_cast<paddle::dialect::Conv2dOp>();
    if (!conv2d_op) return false;

    ir::OpResult conv2d_out = conv2d_op.out();
    if (!conv2d_out.HasOneUse()) return false;

    ir::Value conv2d_filter = conv2d_op.filter();

    ir::OpResult conv2d_filter_result = conv2d_filter.dyn_cast<ir::OpResult>();
    IR_ENFORCE(conv2d_filter_result);

    ir::Value add_input = op.x();
    IR_ENFORCE(add_input == conv2d_out);

    ir::Value y = op.y();
    ir::OpResult bias = y.dyn_cast<ir::OpResult>();
    auto conv2d_attributes = conv2d_op.attributes();
    std::vector<std::string> conv2d_fusion_attrStr = {"strides",
                                                      "paddings_t",
                                                      "padding_algorithm",
                                                      "dilations_t",
                                                      "groups",
                                                      "data_format",
                                                      "activation",
                                                      "exhaustive_search",
                                                      "channels",
                                                      "user_workspace_size"};
    std::vector<ir::Attribute> con2d_fusing_attr = {
        conv2d_attributes.at("strides"),
        conv2d_attributes.at("paddings"),
        conv2d_attributes.at("padding_algorithm"),
        conv2d_attributes.at("dilations"),
        conv2d_attributes.at("groups"),
        conv2d_attributes.at("data_format"),
        ir::StrAttribute::get(ir::IrContext::Instance(), "identity"),
        ir::BoolAttribute::get(ir::IrContext::Instance(), true),
        ir::ArrayAttribute::get(ir::IrContext::Instance(),
                                std::vector<ir::Attribute>()),
        ir::Int32Attribute::get(ir::IrContext::Instance(), int32_t(0)),
    };
    ir::AttributeMap conv2d_fusion_attributes;
    for (size_t i = 0; i < conv2d_fusion_attrStr.size(); ++i) {
      conv2d_fusion_attributes[conv2d_fusion_attrStr[i]] = con2d_fusing_attr[i];
    }

    ir::OpResult tmpResidual;

    auto conv2d_fuse_op = rewriter.Build<paddle::dialect::Conv2dFusionOpTest>(
        ir::GetDefiningOpForInput<0>(conv2d_op)->result(0),
        conv2d_filter_result,
        bias,
        tmpResidual,
        conv2d_fusion_attributes);
    rewriter.ReplaceOp(op, std::vector<ir::Value>{conv2d_fuse_op.output()});
    return true;
  }
};

956 957 958 959 960
class TestPass : public ir::Pass {
 public:
  TestPass() : ir::Pass("TestPass", 1) {}
  void Run(ir::Operation *op) override {
    ir::RewritePatternSet ps(op->ir_context());
Y
Yuanle Liu 已提交
961
    ps.Add<RedundantTransposeFusePattern>(op->ir_context());
962
    ps.Add<Conv2dBnFusePattern>(op->ir_context());
963
    ps.Add<Conv2dAddFusePattern>(op->ir_context());
964

965 966 967
    ir::FrozenRewritePatternSet frozen_ps(std::move(ps));
    ir::GreedyRewriteConfig cfg;
    cfg.use_top_down_traversal = true;
968
    cfg.max_iterations = 10;
969 970 971 972 973 974 975 976 977
    ir::ApplyPatternsGreedily(op->region(0), frozen_ps, cfg);
  }

  bool CanApplyOn(ir::Operation *op) const override {
    return op->name() == "builtin.module" && op->num_regions() > 0;
  }
};

void BuildProgram(ir::Builder &builder) {  // NOLINT
978
  paddle::dialect::FullOp full_input_op =
979 980 981 982
      builder.Build<paddle::dialect::FullOp>(std::vector<int64_t>{1, 3, 16, 16},
                                             1.5,
                                             phi::DataType::FLOAT32,
                                             phi::CPUPlace());
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

  paddle::dialect::FullOp full_filter_op =
      builder.Build<paddle::dialect::FullOp>(std::vector<int64_t>{64, 3, 3, 3},
                                             1.5,
                                             phi::DataType::FLOAT32,
                                             phi::CPUPlace());

  paddle::dialect::FullOp full_mean_op = builder.Build<paddle::dialect::FullOp>(
      std::vector<int64_t>{64}, 1.5, phi::DataType::FLOAT32, phi::CPUPlace());

  paddle::dialect::FullOp full_variance_op =
      builder.Build<paddle::dialect::FullOp>(std::vector<int64_t>{64},
                                             1.5,
                                             phi::DataType::FLOAT32,
                                             phi::CPUPlace());

  paddle::dialect::FullOp full_scale_op =
      builder.Build<paddle::dialect::FullOp>(std::vector<int64_t>{64},
                                             1.5,
                                             phi::DataType::FLOAT32,
                                             phi::CPUPlace());

  paddle::dialect::FullOp full_bias_op = builder.Build<paddle::dialect::FullOp>(
      std::vector<int64_t>{64}, 1.5, phi::DataType::FLOAT32, phi::CPUPlace());

  paddle::dialect::Conv2dOp conv2d_op =
      builder.Build<paddle::dialect::Conv2dOp>(full_input_op.out(),
                                               full_filter_op.out());

  paddle::dialect::BatchNormOp batch_norm_op =
      builder.Build<paddle::dialect::BatchNormOp>(conv2d_op.out(),
                                                  full_mean_op.out(),
                                                  full_variance_op.out(),
                                                  full_scale_op.out(),
                                                  full_bias_op.out(),
                                                  true,
                                                  0.9,
                                                  1e-6,
                                                  "NCHW",
                                                  false,
                                                  false);
1024 1025

  auto transpose1_op = builder.Build<paddle::dialect::TransposeOp>(
1026
      batch_norm_op.out(), std::vector<int>{0, 2, 3, 1});
1027

1028 1029
  auto transpose2_op = builder.Build<paddle::dialect::TransposeOp>(
      transpose1_op.out(), std::vector<int>{0, 3, 1, 2});
1030

H
hong 已提交
1031
  builder.Build<paddle::dialect::FetchOp>(transpose2_op.out(), "out", 0);
1032 1033 1034
}

// TODO(wilber): Add a normal test.
1035
TEST(pattern_rewrite, Patterns) {
1036
  ir::IrContext *ctx = ir::IrContext::Instance();
1037 1038
  auto *test_dialect = ctx->GetOrRegisterDialect<Conv2dFusionTestDialect>();
  test_dialect->RegisterOp<paddle::dialect::Conv2dFusionOpTest>();
1039 1040 1041 1042
  ctx->GetOrRegisterDialect<paddle::dialect::PaddleDialect>();
  ir::Program program(ctx);
  ir::Builder builder = ir::Builder(ctx, program.block());
  BuildProgram(builder);
1043 1044

  EXPECT_EQ(program.block()->size(), 11u);
1045 1046 1047

  ir::PassManager pm(ctx);
  pm.AddPass(std::make_unique<TestPass>());
W
Wilber 已提交
1048
  pm.AddPass(ir::CreateDcePass());
1049 1050
  program.Print(std::cout);
  std::cout << std::endl;
1051 1052
  pm.Run(&program);
  LOG(INFO) << "After Pass.";
1053 1054
  program.Print(std::cout);
  std::cout << std::endl;
1055
}