graph_pattern_detector.cc 142.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2018 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/framework/ir/graph_pattern_detector.h"
16

17
#include "paddle/fluid/framework/ir/graph_traits.h"
18
#include "paddle/fluid/framework/ir/graph_viz_pass.h"
C
chengduo 已提交
19
#include "paddle/fluid/framework/operator.h"
20
#include "paddle/fluid/platform/enforce.h"
Y
Yan Chunwei 已提交
21
#include "paddle/fluid/string/pretty_log.h"
22

23 24 25 26
namespace paddle {
namespace framework {
namespace ir {

Y
Yan Chunwei 已提交
27 28 29
using string::PrettyLog;
using string::Style;

30 31
size_t PDPattern::id_ = 0UL;

32 33 34 35 36 37
#ifdef PADDLE_WITH_TENSORRT
namespace patterns {
thread_local std::unordered_map<std::string, size_t> KeyCounter::dic_;
}
#endif

C
chengduo 已提交
38
PDNode *PDPattern::NewNode(const std::string &name) {
Y
Yan Chunwei 已提交
39
  if (!name.empty()) {
40
    PADDLE_ENFORCE_EQ(
41 42
        node_map_.count(name),
        0UL,
43 44
        platform::errors::PreconditionNotMet(
            "PDNode's name should be unique, get duplicate [%s]", name));
Y
Yan Chunwei 已提交
45 46 47
  }

  nodes_.emplace_back(new PDNode(this, name));
C
chengduo 已提交
48
  auto *cur = nodes_.back().get();
Y
Yan Chunwei 已提交
49 50 51 52
  node_map_[name] = cur;
  return cur;
}

C
chengduo 已提交
53
PDNode *PDPattern::NewNode(PDNode::teller_t &&teller, const std::string &name) {
54
  if (!name.empty()) {
55
    PADDLE_ENFORCE_EQ(
56 57
        node_map_.count(name),
        0UL,
58 59
        platform::errors::PreconditionNotMet(
            "PDNode's name should be unique, get duplicate [%s]", name));
60 61
  }

62
  nodes_.emplace_back(new PDNode(std::move(teller), this, name));
C
chengduo 已提交
63
  auto *cur = nodes_.back().get();
64
  node_map_[name] = cur;
65 66 67
  return cur;
}

C
chengduo 已提交
68
PDNode *PDPattern::RetrieveNode(const std::string &id) const {
69 70 71 72 73 74 75 76
  auto it = node_map_.find(id);
  if (it == node_map_.end()) {
    return nullptr;
  }

  return it->second;
}

C
chengduo 已提交
77
void PDPattern::AddEdge(PDNode *a, PDNode *b) {
78 79 80 81
  PADDLE_ENFORCE_NOT_NULL(
      a, platform::errors::NotFound("PDNode %s is not found.", a->name()));
  PADDLE_ENFORCE_NOT_NULL(
      b, platform::errors::NotFound("PDNode %s is not found.", b->name()));
82 83
  PADDLE_ENFORCE_NE(a,
                    b,
84 85
                    platform::errors::PermissionDenied(
                        "Cannot connect the same node in the graph."));
86 87 88
  edges_.emplace_back(a, b);
}

C
chengduo 已提交
89
void GraphPatternDetector::operator()(Graph *graph,
90
                                      GraphPatternDetector::handle_t handler) {
91 92 93 94
  if (!MarkPDNodesInGraph(*graph)) {
    return;
  }

95 96
  auto subgraphs = DetectPatterns();
  UniquePatterns(&subgraphs);
Z
Zhang Ting 已提交
97
  SortSubgraphs(&subgraphs);
98
  RemoveOverlappedMatch(&subgraphs);
Y
Yan Chunwei 已提交
99
  ValidateByNodeRole(&subgraphs);
100

Y
Yan Chunwei 已提交
101
  if (subgraphs.empty()) return;
102

103
  int id = 0;
C
chengduo 已提交
104
  for (auto &g : subgraphs) {
M
minqiyang 已提交
105
    VLOG(3) << "optimizing #" << id++ << " subgraph";
106 107 108 109
    handler(g, graph);
  }
}

C
chengduo 已提交
110
bool GraphPatternDetector::MarkPDNodesInGraph(const ir::Graph &graph) {
M
minqiyang 已提交
111
  VLOG(3) << "mark pdnodes in graph";
112 113
  if (graph.Nodes().empty()) return false;

C
chengduo 已提交
114
  for (auto &node : GraphTraits::DFS(graph)) {
115
    if (node.Name().rfind("__control_var") == 0) continue;
C
chengduo 已提交
116
    for (const auto &pdnode : pattern_.nodes()) {
117
      if (pdnode->Tell(&node)) {
118
        VLOG(4) << "Node " << node.Name() << " marked as " << pdnode->name();
119 120 121 122
        pdnodes2nodes_[pdnode.get()].insert(&node);
      }
    }
  }
Y
Yan Chunwei 已提交
123
  // Check to early stop if some PDNode can't find matched Node.
C
chengduo 已提交
124
  for (auto &pdnode : pattern_.nodes()) {
Y
Yan Chunwei 已提交
125
    if (!pdnodes2nodes_.count(pdnode.get())) {
M
minqiyang 已提交
126
      VLOG(4) << pdnode->name() << " can't find matched Node, early stop";
Y
Yan Chunwei 已提交
127
      // return false;
Y
Yan Chunwei 已提交
128 129
    }
  }
M
minqiyang 已提交
130
  VLOG(3) << pdnodes2nodes_.size() << " nodes marked";
131

132 133 134
  return !pdnodes2nodes_.empty();
}

Y
Yan Chunwei 已提交
135
// The intermediate Nodes can only link to the nodes inside the pattern, or this
T
tianshuo78520a 已提交
136
// subgraph will be dropped.
Y
Yan Chunwei 已提交
137
void GraphPatternDetector::ValidateByNodeRole(
C
chengduo 已提交
138
    std::vector<GraphPatternDetector::subgraph_t> *subgraphs) {
Y
Yan Chunwei 已提交
139 140 141 142
  std::vector<GraphPatternDetector::subgraph_t> result;

  subgraphs->erase(
      std::remove_if(
143 144
          subgraphs->begin(),
          subgraphs->end(),
C
chengduo 已提交
145
          [](const GraphPatternDetector::subgraph_t &subgraph) -> bool {
Y
Yan Chunwei 已提交
146
            // Collect the inputs and outputs.
147
            std::set<Node *> ios;
C
chengduo 已提交
148
            for (auto &item : subgraph) {
Y
Yan Chunwei 已提交
149 150 151 152
              if (!item.first->IsIntermediate()) {
                ios.insert(item.second);
              }
            }
C
chengduo 已提交
153
            for (auto &item : subgraph) {
Y
Yan Chunwei 已提交
154
              if (item.first->IsIntermediate()) {
C
chengduo 已提交
155
                for (auto *x : item.second->inputs) {
Y
Yan Chunwei 已提交
156 157 158 159
                  if (!ios.count(x)) {
                    return true;
                  }
                }
C
chengduo 已提交
160
                for (auto *x : item.second->outputs) {
Y
Yan Chunwei 已提交
161 162 163 164 165 166 167 168 169 170 171
                  if (!ios.count(x)) {
                    return true;
                  }
                }
              }
            }
            return false;
          }),
      subgraphs->end());
}

172
struct HitGroup {
173
  std::map<PDNode *, Node *> roles;
174

C
chengduo 已提交
175
  bool Match(Node *node, PDNode *pat) {
176
    if (nodes_.count(node)) {
T
Tao Luo 已提交
177 178 179 180 181
      if (roles.count(pat) && roles[pat] == node) return true;
      return false;
    } else {
      if (roles.count(pat) && roles[pat] != node) return false;
      return true;
182
    }
183 184
  }

C
chengduo 已提交
185
  void Register(Node *node, PDNode *pat) {
186 187 188 189 190
    roles[pat] = node;
    nodes_.insert(node);
  }

 private:
191
  std::set<Node *> nodes_;
192 193 194
};

// Tell whether Node a links to b.
C
chengduo 已提交
195 196
bool IsNodesLink(Node *a, Node *b) {
  for (auto *node : a->outputs) {
197 198 199 200 201 202 203
    if (b == node) {
      return true;
    }
  }
  return false;
}

204 205
std::vector<GraphPatternDetector::subgraph_t>
GraphPatternDetector::DetectPatterns() {
206
  // Init empty subgraphs.
207
  std::vector<GraphPatternDetector::subgraph_t> result;
208
  std::vector<HitGroup> init_groups;
209
  std::array<std::vector<HitGroup>, 2> bi_records;
C
chengduo 已提交
210
  auto *first_pnode = pattern_.edges().empty() ? pattern().nodes().front().get()
211
                                               : pattern_.edges().front().first;
212
  if (!pdnodes2nodes_.count(first_pnode)) return result;
C
chengduo 已提交
213
  for (auto *node : pdnodes2nodes_[first_pnode]) {
214 215 216 217 218 219 220 221 222 223
    HitGroup group;
    group.roles[first_pnode] = node;
    init_groups.emplace_back(group);
  }

  int step = 0;
  bi_records[0] = std::move(init_groups);

  // Extend a PDNode to subgraphs by deducing the connection relations defined
  // in edges of PDNodes.
C
chengduo 已提交
224
  for (const auto &edge : pattern_.edges()) {
M
minqiyang 已提交
225
    VLOG(4) << "check " << edge.first->name() << " -> " << edge.second->name();
Y
Yan Chunwei 已提交
226
    // TODO(Superjomn) Fix bug here, the groups might be duplicate here.
227 228
    // Each role has two PDNodes, which indicates two roles.
    // Detect two Nodes that can match these two roles and they are connected.
C
chengduo 已提交
229 230
    auto &pre_groups = bi_records[step % 2];
    auto &cur_groups = bi_records[1 - (step++ % 2)];
231
    cur_groups.clear();
232
    if (pre_groups.empty()) break;
233
    // source -> target
C
chengduo 已提交
234 235
    for (Node *source : pdnodes2nodes_[edge.first]) {
      for (Node *target : pdnodes2nodes_[edge.second]) {
M
minqiyang 已提交
236
        VLOG(8) << "check " << source->id() << " -- " << target->id();
237
        // TODO(Superjomn) add some prune strategies.
C
chengduo 已提交
238
        for (const auto &group : pre_groups) {
T
Tao Luo 已提交
239 240 241 242 243 244
          if (IsNodesLink(source, target)) {
            HitGroup new_group = group;
            bool flag = new_group.Match(source, edge.first) &&
                        new_group.Match(target, edge.second);
            if (flag) {
              new_group.Register(source, edge.first);
245 246 247 248 249 250 251 252
              new_group.Register(target, edge.second);
              cur_groups.push_back(new_group);
              // TODO(Superjomn) need to unique
            }
          }
        }
      }
    }
M
minqiyang 已提交
253
    VLOG(3) << "step " << step << " get records: " << cur_groups.size();
C
chengduo 已提交
254 255
    for (auto &group : cur_groups) {
      for (auto &item : group.roles) {
M
minqiyang 已提交
256
        VLOG(4) << "node " << item.second->id() << " as " << item.first->name();
Y
Yan Chunwei 已提交
257
      }
M
minqiyang 已提交
258
      VLOG(4) << "=========================================================";
Y
Yan Chunwei 已提交
259
    }
260 261
  }

C
chengduo 已提交
262
  for (auto &group : bi_records[step % 2]) {
263
    GraphPatternDetector::subgraph_t subgraph;
C
chengduo 已提交
264
    for (auto &role : group.roles) {
265 266 267 268 269 270 271
      subgraph.emplace(role.first, role.second);
    }
    result.emplace_back(subgraph);
  }
  return result;
}

Y
Yan Chunwei 已提交
272 273
struct GraphItemLessThan {
  bool operator()(const std::pair<PDNode *, Node *> &a,
Y
Yan Chunwei 已提交
274
                  const std::pair<PDNode *, Node *> &b) {
Y
Yan Chunwei 已提交
275 276 277 278 279
    if (a.first != b.first) {
      return a.first < b.first;
    } else {
      return a.second < b.second;
    }
Y
Yan Chunwei 已提交
280
  }
Y
Yan Chunwei 已提交
281
};
Y
Yan Chunwei 已提交
282

283 284
// TODO(Superjomn) enhance the function as it marks unique unique as duplicates
// see https://github.com/PaddlePaddle/Paddle/issues/13550
285
void GraphPatternDetector::UniquePatterns(
C
chengduo 已提交
286
    std::vector<GraphPatternDetector::subgraph_t> *subgraphs) {
287
  if (subgraphs->empty()) return;
288
  std::vector<GraphPatternDetector::subgraph_t> result;
289

290
  std::set<size_t> set;
Y
Yan Chunwei 已提交
291
  std::hash<std::string> hasher;
C
chengduo 已提交
292
  for (auto &g : *subgraphs) {
Y
Yan Chunwei 已提交
293 294
    // Sort the items in the sub-graph, and transform to a string key.
    std::vector<std::pair<PDNode *, Node *>> sorted_keys(g.begin(), g.end());
Y
Yan Chunwei 已提交
295
    std::sort(sorted_keys.begin(), sorted_keys.end(), GraphItemLessThan());
Y
Yan Chunwei 已提交
296 297 298
    std::stringstream ss;
    for (auto &item : sorted_keys) {
      ss << item.first << ":" << item.second;
299
    }
Y
Yan Chunwei 已提交
300
    auto key = hasher(ss.str());
301 302 303 304 305 306 307 308
    if (!set.count(key)) {
      result.emplace_back(g);
      set.insert(key);
    }
  }
  *subgraphs = result;
}

Z
Zhang Ting 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
void GraphPatternDetector::SortSubgraphs(
    std::vector<GraphPatternDetector::subgraph_t> *subgraphs) {
  if (subgraphs->empty()) return;
  bool has_bn_add_act = false;
  for (auto &subgraph : *subgraphs) {
    for (auto &item : subgraph) {
      if (item.first->name().find("bn_add_act") != std::string::npos) {
        has_bn_add_act = true;
        break;
      }
    }
  }
  if (!has_bn_add_act) {
    return;
  }

  std::sort(
326 327
      subgraphs->begin(),
      subgraphs->end(),
Z
Zhang Ting 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
      [](const GraphPatternDetector::subgraph_t &a,
         const GraphPatternDetector::subgraph_t &b) {
        for (auto &item : a) {
          if (item.first->name().find("bn_add_act") != std::string::npos &&
              item.first->name().find("bn_reserve_space") !=
                  std::string::npos) {
            auto it_b = b.find(item.first);
            if (it_b != b.end()) {
              if (item.second->Name() != it_b->second->Name()) {
                return item.second->Name() < it_b->second->Name();
              } else {
                return false;
              }
            } else {
              return false;
            }
          }
        }
        return false;
      });
}

350
void GraphPatternDetector::RemoveOverlappedMatch(
C
chengduo 已提交
351
    std::vector<subgraph_t> *subgraphs) {
352
  std::vector<subgraph_t> result;
353
  std::set<Node *> node_set;
354

C
chengduo 已提交
355
  for (const auto &subgraph : *subgraphs) {
356
    bool valid = true;
C
chengduo 已提交
357
    for (auto &item : subgraph) {
Y
Yan Chunwei 已提交
358
      if (item.first->IsIntermediate() && node_set.count(item.second)) {
359 360 361 362 363
        valid = false;
        break;
      }
    }
    if (valid) {
C
chengduo 已提交
364
      for (auto &item : subgraph) {
365 366 367 368 369 370 371 372
        node_set.insert(item.second);
      }
      result.push_back(subgraph);
    }
  }
  *subgraphs = result;
}

373 374 375 376 377
std::string PDPattern::DotString() const {
  using inference::analysis::Dot;
  Dot dot;
  int id = 0;
  // Create Nodes
C
chengduo 已提交
378 379
  std::unordered_map<PDNode *, std::string> node2dot;
  for (const auto &node : nodes()) {
380 381 382 383 384
    std::string node_id = "Node" + std::to_string(id++);
    dot.AddNode(node_id, {}, node->name());
    node2dot[node.get()] = node_id;
  }
  // Create Edges
C
chengduo 已提交
385
  for (const auto &edge : edges()) {
386 387 388
    if (!node2dot.count(edge.first) || !node2dot.count(edge.second)) {
      continue;
    }
C
chengduo 已提交
389 390
    auto &src = node2dot.at(edge.first);
    auto &trg = node2dot.at(edge.second);
391 392 393 394 395
    dot.AddEdge(src, trg, {});
  }
  return dot.Build();
}

C
chengduo 已提交
396
PDNode &PDNode::LinksTo(const std::vector<PDNode *> &others) {
397
  // extend outlinks.
C
chengduo 已提交
398
  for (PDNode *x : others) {
399 400 401 402 403
    pattern_->AddEdge(this, x);
  }
  return *this;
}

C
chengduo 已提交
404
PDNode &PDNode::LinksFrom(const std::vector<PDNode *> &others) {
405
  // extend outlinks.
C
chengduo 已提交
406
  for (PDNode *x : others) {
407 408 409 410 411
    pattern_->AddEdge(x, this);
  }
  return *this;
}

C
chengduo 已提交
412 413
PDNode *PDNode::assert_is_op() {
  asserts_.emplace_back([](Node *x) { return x && x->IsOp(); });
Y
Yan Chunwei 已提交
414 415
  return this;
}
C
chengduo 已提交
416 417 418

PDNode *PDNode::assert_is_op(const std::string &op_type) {
  asserts_.emplace_back([op_type](Node *x) {
Y
Yan Chunwei 已提交
419 420 421 422
    return x && x->IsOp() && x->Op()->Type() == op_type;
  });
  return this;
}
C
chengduo 已提交
423

S
shentanyue 已提交
424 425 426 427 428 429 430
PDNode *PDNode::assert_is_not_op_type(const std::string &op_type) {
  asserts_.emplace_back([op_type](Node *x) {
    return x && x->IsOp() && x->Op()->Type() != op_type;
  });
  return this;
}

C
chengduo 已提交
431 432 433 434 435
PDNode *PDNode::assert_is_var() {
  asserts_.emplace_back([](Node *x) { return x && x->IsVar(); });
  return this;
}

Z
Zhen Wang 已提交
436 437 438 439 440 441 442
PDNode *PDNode::assert_var_dtype(proto::VarType::Type dtype) {
  assert_is_var();
  asserts_.emplace_back(
      [dtype](Node *x) { return x->Var()->GetDataType() == dtype; });
  return this;
}

C
chengduo 已提交
443 444
PDNode *PDNode::assert_is_not_ctrl_var() {
  asserts_.emplace_back([](Node *x) { return x && !x->IsCtrlVar(); });
Y
Yan Chunwei 已提交
445 446
  return this;
}
C
chengduo 已提交
447 448

PDNode *PDNode::assert_var_not_persistable() {
Y
Yan Chunwei 已提交
449
  assert_is_var();
C
chengduo 已提交
450
  asserts_.emplace_back([](Node *x) { return !x->Var()->Persistable(); });
Y
Yan Chunwei 已提交
451 452
  return this;
}
C
chengduo 已提交
453 454

PDNode *PDNode::assert_is_persistable_var() {
Y
Yan Chunwei 已提交
455
  assert_is_var();
456 457
  asserts_.emplace_back(
      [=](Node *x) { return x->Var() && x->Var()->Persistable(); });
Y
Yan Chunwei 已提交
458 459
  return this;
}
C
chengduo 已提交
460 461

PDNode *PDNode::assert_is_op_nth_input(const std::string &op_type,
462 463
                                       const std::string &argument,
                                       int nth) {
Y
Yan Chunwei 已提交
464 465
  assert_is_var();
  assert_is_op_input(op_type);
C
chengduo 已提交
466 467
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
468 469 470
      if (op->IsOp() && op->Op()->Type() == op_type &&
          IsNthInput(x, op, argument, nth))
        return true;
Y
Yan Chunwei 已提交
471 472 473 474 475
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
476 477

PDNode *PDNode::assert_is_op_nth_output(const std::string &op_type,
478 479
                                        const std::string &argument,
                                        int nth) {
Y
Yan Chunwei 已提交
480
  assert_is_var();
C
chengduo 已提交
481 482
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
483 484 485
      if (op->IsOp() && op->Op()->Type() == op_type &&
          IsNthOutput(x, op, argument, nth))
        return true;
Y
Yan Chunwei 已提交
486 487 488 489 490
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
491 492

PDNode *PDNode::assert_is_only_input_of_op(const std::string &op_type) {
Y
Yan Chunwei 已提交
493
  assert_is_var();
C
chengduo 已提交
494 495
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
Y
Yan Chunwei 已提交
496 497 498 499 500 501 502 503 504
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->inputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
505 506

PDNode *PDNode::assert_is_only_output_of_op(const std::string &op_type) {
Y
Yan Chunwei 已提交
507
  assert_is_var();
C
chengduo 已提交
508 509
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
Y
Yan Chunwei 已提交
510 511 512 513 514 515 516 517 518
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->outputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
519 520

PDNode *PDNode::assert_is_op_output(const std::string &op_type) {
Y
Yan Chunwei 已提交
521
  assert_is_var();
C
chengduo 已提交
522 523
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
Y
Yan Chunwei 已提交
524 525 526 527 528 529 530 531
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
532 533 534

PDNode *PDNode::assert_is_op_output(const std::string &op_type,
                                    const std::string &argument) {
535 536 537 538
  assert_is_var();
  assert_is_op_nth_output(op_type, argument, 0);
  return this;
}
Z
Zhen Wang 已提交
539

C
chengduo 已提交
540
PDNode *PDNode::assert_is_op_input(const std::string &op_type) {
Y
Yan Chunwei 已提交
541
  assert_is_var();
C
chengduo 已提交
542 543
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
Y
Yan Chunwei 已提交
544 545 546 547 548 549 550 551
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
552

Z
Zhen Wang 已提交
553 554 555 556 557 558 559 560 561 562
PDNode *PDNode::assert_is_not_op_input(const std::string &argument) {
  assert_is_op();
  asserts_.emplace_back([=](Node *x) {
    auto &ins = x->Op()->Inputs();
    auto iter = ins.find(argument);
    return iter == ins.end() || iter->second.empty();
  });
  return this;
}

C
chengduo 已提交
563 564
PDNode *PDNode::assert_is_op_input(const std::string &op_type,
                                   const std::string &argument) {
565 566 567 568
  assert_is_var();
  assert_is_op_nth_input(op_type, argument, 0);
  return this;
}
C
chengduo 已提交
569 570

PDNode *PDNode::assert_op_has_n_inputs(const std::string &op_type, size_t n) {
Y
Yan Chunwei 已提交
571
  assert_is_op(op_type);
C
chengduo 已提交
572
  asserts_.emplace_back([=](Node *x) { return x->inputs.size() == n; });
Y
Yan Chunwei 已提交
573 574
  return this;
}
C
chengduo 已提交
575 576

PDNode *PDNode::assert_op_has_n_outputs(const std::string &op_type, size_t n) {
Y
Yan Chunwei 已提交
577
  assert_is_op(op_type);
C
chengduo 已提交
578
  asserts_.emplace_back([=](Node *x) { return x->outputs.size() == n; });
Y
Yan Chunwei 已提交
579 580
  return this;
}
C
chengduo 已提交
581

582 583 584 585 586 587 588 589 590 591
PDNode *PDNode::assert_has_n_inputs(size_t n) {
  asserts_.emplace_back([=](Node *x) { return x->inputs.size() == n; });
  return this;
}

PDNode *PDNode::assert_has_n_outputs(size_t n) {
  asserts_.emplace_back([=](Node *x) { return x->outputs.size() == n; });
  return this;
}

C
chengduo 已提交
592
PDNode *PDNode::assert_more(PDNode::teller_t &&teller) {
Y
Yan Chunwei 已提交
593 594 595 596
  asserts_.emplace_back(std::move(teller));
  return this;
}

C
chengduo 已提交
597 598 599 600 601 602 603 604 605
PDNode *PDNode::assert_is_ops(const std::unordered_set<std::string> &op_types) {
  asserts_.emplace_back([op_types](Node *x) {
    return x && x->IsOp() && op_types.count(x->Op()->Type());
  });
  return this;
}

PDNode *PDNode::assert_is_ops_nth_input(
    const std::unordered_set<std::string> &op_types,
606 607
    const std::string &argument,
    int nth) {
C
chengduo 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
  assert_is_var();
  assert_is_ops_input(op_types);
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
      if (op->IsOp() && op_types.count(op->Op()->Type()) &&
          IsNthInput(x, op, argument, nth))
        return true;
    }
    return false;
  });
  return this;
}

PDNode *PDNode::assert_is_ops_nth_output(
    const std::unordered_set<std::string> &op_types,
623 624
    const std::string &argument,
    int nth) {
C
chengduo 已提交
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
  assert_is_var();
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
      if (op->IsOp() && op_types.count(op->Op()->Type()) &&
          IsNthOutput(x, op, argument, nth))
        return true;
    }
    return false;
  });
  return this;
}
PDNode *PDNode::assert_is_ops_output(
    const std::unordered_set<std::string> &op_types) {
  assert_is_var();
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
      if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type())) {
        return true;
      }
    }
    return false;
  });
  return this;
}

PDNode *PDNode::assert_is_ops_output(
    const std::unordered_set<std::string> &op_types,
    const std::string &argument) {
  assert_is_var();
  assert_is_ops_nth_output(op_types, argument, 0);
  return this;
}

PDNode *PDNode::assert_is_ops_input(
    const std::unordered_set<std::string> &op_types) {
  assert_is_var();
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
      if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type())) {
        return true;
      }
    }
    return false;
  });
  return this;
}

PDNode *PDNode::assert_is_ops_input(
    const std::unordered_set<std::string> &op_types,
    const std::string &argument) {
  assert_is_var();
  assert_is_ops_nth_input(op_types, argument, 0);
  return this;
}

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
PDNode *PDNode::assert_is_only_input_of_ops(
    const std::unordered_set<std::string> &op_types) {
  assert_is_var();
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
      if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type()) &&
          op->inputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}

PDNode *PDNode::assert_is_only_output_of_ops(
    const std::unordered_set<std::string> &op_types) {
  assert_is_var();
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
      if (op && op->IsOp() && op->Op() && op_types.count(op->Op()->Type()) &&
          op->outputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}

C
chengduo 已提交
710 711
bool VarLinksToOp(Node *node, const std::string &op_type) {
  for (auto *out : node->outputs) {
712 713 714 715 716 717
    if (out->IsOp() && out->Op()->Type() == op_type) {
      return true;
    }
  }
  return false;
}
C
chengduo 已提交
718 719

bool IsNthInput(Node *var, Node *op, const std::string &argument, size_t nth) {
720
  PADDLE_ENFORCE_EQ(
721 722
      var->IsVar(),
      true,
723 724 725
      platform::errors::InvalidArgument(
          "First parameter of function IsNthInput must be Node::Var"));
  PADDLE_ENFORCE_EQ(
726 727
      op->IsOp(),
      true,
728 729
      platform::errors::InvalidArgument(
          "Second parameter of function IsNthInput must be Node::Op"));
730 731
  if (!HasInput(op, argument) || op->Op()->Input(argument).size() <= nth)
    return false;
732 733
  return var->Name() == op->Op()->Input(argument)[nth];
}
C
chengduo 已提交
734

735
bool HasInput(Node *op, const std::string &argument) {
736
  PADDLE_ENFORCE_EQ(
737 738
      op->IsOp(),
      true,
739 740
      platform::errors::InvalidArgument(
          "First parameter of function HasInput must be Node::Op"));
741 742 743 744 745 746
  auto const &names = op->Op()->InputNames();
  if (std::find(names.begin(), names.end(), argument) == names.end())
    return false;
  return true;
}

747 748
bool HasOutput(Node *op, const std::string &argument) {
  PADDLE_ENFORCE_EQ(
749 750
      op->IsOp(),
      true,
751
      platform::errors::InvalidArgument(
752
          "First parameter of function HasOutput must be Node::Op"));
753 754 755 756 757 758
  auto const &names = op->Op()->OutputNames();
  if (std::find(names.begin(), names.end(), argument) == names.end())
    return false;
  return true;
}

C
chengduo 已提交
759
bool IsNthOutput(Node *var, Node *op, const std::string &argument, size_t nth) {
760
  PADDLE_ENFORCE_EQ(
761 762
      var->IsVar(),
      true,
763 764 765
      platform::errors::InvalidArgument(
          "First parameter of function IsNthOutput must be Node::Var"));
  PADDLE_ENFORCE_EQ(
766 767
      op->IsOp(),
      true,
768 769
      platform::errors::InvalidArgument(
          "Second parameter of function IsNthOutput must be Node::Op"));
770 771
  if (!HasOutput(op, argument) || op->Op()->Output(argument).size() <= nth)
    return false;
772 773
  return var->Name() == op->Op()->Output(argument)[nth];
}
C
chengduo 已提交
774

775 776 777 778
void GraphSafeRemoveNodes(
    Graph *graph,
    const std::unordered_set<const Node *> &nodes,
    std::unordered_set<std::shared_ptr<Node>> *saved_nodes) {
C
chengduo 已提交
779
  for (auto *node : nodes) {
780 781 782 783 784 785 786
    if (saved_nodes != nullptr) {
      // prevent unique_ptr node from being released
      saved_nodes->insert(
          std::move(graph->RemoveNode(const_cast<Node *>(node))));
    } else {
      graph->RemoveNode(const_cast<Node *>(node));
    }
787 788
  }

C
chengduo 已提交
789
  for (auto *node : graph->Nodes()) {
790 791
    for (auto it = node->inputs.begin(); it != node->inputs.end();) {
      if (nodes.count(*it)) {
C
chengduo 已提交
792
        it = const_cast<Node *>(node)->inputs.erase(it);
793
      } else {
794
        it++;
795
      }
796 797 798
    }
    for (auto it = node->outputs.begin(); it != node->outputs.end();) {
      if (nodes.count(*it)) {
C
chengduo 已提交
799
        it = const_cast<Node *>(node)->outputs.erase(it);
800
      } else {
801
        it++;
802
      }
803 804 805
    }
  }
}
C
chengduo 已提交
806 807 808

bool VarLinksFromOp(Node *node, const std::string &op_type) {
  for (auto *out : node->inputs) {
809 810 811 812 813 814 815
    if (out->IsOp() && out->Op()->Type() == op_type) {
      return true;
    }
  }
  return false;
}

S
Sylwester Fraczek 已提交
816
PDNode *patterns::ConvBN::operator()(paddle::framework::ir::PDNode *conv_input,
817
                                     const std::string &conv_type,
S
Sylwester Fraczek 已提交
818 819
                                     bool with_eltwise_add) {
  // Create Operators
820 821
  conv_input->assert_is_op_input(conv_type, "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
S
Sylwester Fraczek 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834

  PDNode *eltwise_op = nullptr;
  if (with_eltwise_add) {
    eltwise_op =
        pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
  }
  auto *batch_norm_op =
      pattern->NewNode(batch_norm_repr())->assert_is_op("batch_norm");
  // Create variables
  // Conv Filter
  auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
835
                              ->assert_is_op_input(conv_type, "Filter");
S
Sylwester Fraczek 已提交
836 837 838

  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
839
                           ->assert_is_only_output_of_op(conv_type);
S
Sylwester Fraczek 已提交
840 841 842 843 844 845 846 847 848

  PDNode *eltwise_y_in_var = nullptr;
  PDNode *eltwise_out_var = nullptr;
  if (with_eltwise_add) {
    // Conv output as Bias input
    conv_out_var->assert_is_op_input("elementwise_add", "X");
    // Bias
    eltwise_y_in_var = pattern->NewNode(eltwise_y_in_repr())
                           ->assert_is_op_input("elementwise_add", "Y")
849
                           ->assert_is_persistable_var()
S
Sylwester Fraczek 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862
                           ->AsInput();
    eltwise_out_var = pattern->NewNode(eltwise_out_repr())
                          ->AsIntermediate()
                          ->assert_is_only_output_of_op("elementwise_add");
  } else {
    // Conv output as BN input
    conv_out_var->assert_is_op_input("batch_norm", "X");
  }

  // BN Scale
  auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
                           ->AsInput()
                           ->assert_is_persistable_var()
863 864
                           ->assert_is_op_input("batch_norm", "Scale")
                           ->assert_has_n_outputs(1);
S
Sylwester Fraczek 已提交
865 866 867 868
  // BN Bias
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
869 870
                          ->assert_is_op_input("batch_norm", "Bias")
                          ->assert_has_n_outputs(1);
S
Sylwester Fraczek 已提交
871 872 873 874
  // BN Mean
  auto *bn_mean_var = pattern->NewNode(bn_mean_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
875 876
                          ->assert_is_op_input("batch_norm", "Mean")
                          ->assert_has_n_outputs(1);
S
Sylwester Fraczek 已提交
877 878 879 880
  // BN Variance
  auto *bn_variance_var = pattern->NewNode(bn_variance_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
881 882
                              ->assert_is_op_input("batch_norm", "Variance")
                              ->assert_has_n_outputs(1);
S
Sylwester Fraczek 已提交
883 884 885 886

  // BN output
  auto *bn_out_var = pattern->NewNode(bn_out_repr())
                         ->AsOutput()
887
                         ->assert_is_op_output("batch_norm", "Y");
S
Sylwester Fraczek 已提交
888 889 890

  auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
                              ->AsOutput()
891 892
                              ->assert_is_op_output("batch_norm", "MeanOut")
                              ->assert_has_n_outputs(0);
S
Sylwester Fraczek 已提交
893 894 895 896

  auto *bn_variance_out_var =
      pattern->NewNode(bn_variance_out_repr())
          ->AsOutput()
897 898
          ->assert_is_op_output("batch_norm", "VarianceOut")
          ->assert_has_n_outputs(0);
S
Sylwester Fraczek 已提交
899

900 901 902 903
  auto *bn_saved_mean_var = pattern->NewNode(bn_saved_mean_repr())
                                ->AsOutput()
                                ->assert_is_op_output("batch_norm", "SavedMean")
                                ->assert_has_n_outputs(0);
S
Sylwester Fraczek 已提交
904 905 906 907

  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->AsOutput()
908 909
          ->assert_is_op_output("batch_norm", "SavedVariance")
          ->assert_has_n_outputs(0);
S
Sylwester Fraczek 已提交
910 911 912 913 914 915 916

  conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});

  if (with_eltwise_add) {
    eltwise_op->LinksFrom({conv_out_var, eltwise_y_in_var})
        .LinksTo({eltwise_out_var});
    batch_norm_op
917 918 919 920
        ->LinksFrom({eltwise_out_var,
                     bn_scale_var,
                     bn_bias_var,
                     bn_mean_var,
S
Sylwester Fraczek 已提交
921
                     bn_variance_var})
922 923 924 925 926
        .LinksTo({bn_out_var,
                  bn_mean_out_var,
                  bn_variance_out_var,
                  bn_saved_mean_var,
                  bn_saved_variance_var});
S
Sylwester Fraczek 已提交
927 928
  } else {
    batch_norm_op
929 930 931 932
        ->LinksFrom({conv_out_var,
                     bn_scale_var,
                     bn_bias_var,
                     bn_mean_var,
S
Sylwester Fraczek 已提交
933
                     bn_variance_var})
934 935 936 937 938
        .LinksTo({bn_out_var,
                  bn_mean_out_var,
                  bn_variance_out_var,
                  bn_saved_mean_var,
                  bn_saved_variance_var});
S
Sylwester Fraczek 已提交
939 940 941 942
  }
  return bn_out_var;
}

943 944 945 946 947 948 949 950
PDNode *patterns::OperatorActivation::operator()(
    const std::string &operator_type, const std::string &activation_type) {
  auto *preceding_op =
      pattern->NewNode(preceding_op_repr())->assert_is_op(operator_type);
  auto *preceding_op_out = pattern->NewNode(preceding_op_out_repr())
                               ->AsIntermediate()
                               ->assert_is_only_output_of_op(operator_type)
                               ->assert_is_op_input(activation_type);
951 952
  auto *activation_op =
      pattern->NewNode(activation_repr())->assert_is_op(activation_type);
953 954 955 956 957 958
  auto *activation_out = pattern->NewNode(activation_out_repr())
                             ->AsOutput()
                             ->assert_is_op_output(activation_type);
  preceding_op->LinksTo({preceding_op_out});
  activation_op->LinksFrom({preceding_op_out}).LinksTo({activation_out});
  return activation_out;
959 960
}

T
tensor-tang 已提交
961 962 963 964
PDNode *patterns::SeqConvEltAddRelu::operator()(
    paddle::framework::ir::PDNode *seqconv_input) {
  // Create Operators
  seqconv_input->assert_is_op_input("sequence_conv", "X");
T
tensor-tang 已提交
965 966
  auto *seqconv_op = pattern->NewNode(seqconv_repr())
                         ->assert_is_op("sequence_conv")
967
                         ->assert_has_n_inputs(2)
T
tensor-tang 已提交
968 969
                         ->assert_op_attr<bool>("paddingTrainable", false)
                         ->assert_op_attr<int>("contextStride", 1);
T
tensor-tang 已提交
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

  auto *eltadd_op =
      pattern->NewNode(eltadd_repr())->assert_is_op("elementwise_add");
  auto *relu_op = pattern->NewNode(relu_repr())->assert_is_op("relu");
  // Create variables
  // Filter
  auto *seqconv_weight_var =
      pattern->NewNode(seqconv_weight_repr())
          ->AsInput()
          ->assert_is_persistable_var()
          ->assert_is_op_input("sequence_conv", "Filter");
  // Bias
  auto *eltadd_bias_var = pattern->NewNode(eltadd_bias_repr())
                              ->AsInput()
                              ->assert_is_op_input("elementwise_add");
  // intermediate variable, will be removed in the IR after fuse.
  auto *seqconv_out_var = pattern->NewNode(seqconv_out_repr())
                              ->AsIntermediate()
                              ->assert_is_only_output_of_op("sequence_conv")
                              ->assert_is_op_input("elementwise_add");
  auto *eltadd_out_var = pattern->NewNode(eltadd_out_repr())
                             ->AsIntermediate()
                             ->assert_is_only_output_of_op("elementwise_add")
                             ->assert_is_only_input_of_op("relu");
  // output
  auto *relu_out_var = pattern->NewNode(relu_out_repr())
                           ->AsOutput()
                           ->assert_is_op_output("relu");

  seqconv_op->LinksFrom({seqconv_input, seqconv_weight_var})
      .LinksTo({seqconv_out_var});
  eltadd_op->LinksFrom({seqconv_out_var, eltadd_bias_var})
      .LinksTo({eltadd_out_var});
  relu_op->LinksFrom({eltadd_out_var}).LinksTo({relu_out_var});
  return relu_out_var;
}

C
chengduo 已提交
1007
PDNode *patterns::FC::operator()(paddle::framework::ir::PDNode *x,
1008 1009
                                 bool with_bias,
                                 bool with_relu) {
Y
Yan Chunwei 已提交
1010 1011
  // Create shared nodes.
  x->assert_is_op_input("mul", "X");
C
chengduo 已提交
1012
  auto *mul = pattern->NewNode(mul_repr())->assert_is_op("mul");
Y
Yan Chunwei 已提交
1013

C
chengduo 已提交
1014
  auto *mul_w_var = pattern->NewNode(w_repr())
Y
Yan Chunwei 已提交
1015 1016 1017 1018
                        ->AsInput()
                        ->assert_is_persistable_var()
                        ->assert_is_op_input("mul", "Y");

C
chengduo 已提交
1019
  auto *mul_out_var =
Y
Yan Chunwei 已提交
1020 1021
      pattern->NewNode(mul_out_repr())->assert_is_op_output("mul");

1022 1023
  // Add links.
  mul->LinksFrom({x, mul_w_var}).LinksTo({mul_out_var});
Y
Yan Chunwei 已提交
1024 1025 1026 1027 1028
  if (!with_bias) {  // not with bias
    return mul_out_var;
  } else {  // with bias
    mul_out_var->AsIntermediate()->assert_is_op_input("elementwise_add");
    // Create operators.
C
chengduo 已提交
1029
    auto *elementwise_add = pattern->NewNode(elementwise_add_repr())
Y
Yan Chunwei 已提交
1030 1031
                                ->assert_is_op("elementwise_add");
    // Create variables.
C
chengduo 已提交
1032
    auto *bias = pattern->NewNode(bias_repr())
Y
Yan Chunwei 已提交
1033
                     ->assert_is_op_input("elementwise_add")
1034
                     ->assert_is_persistable_var()
Y
Yan Chunwei 已提交
1035 1036
                     ->AsInput();

1037 1038 1039 1040
    auto *elementwise_add_out_var =
        pattern->NewNode(elementwise_add_out_repr())
            ->AsOutput()
            ->assert_is_op_output("elementwise_add");
Y
Yan Chunwei 已提交
1041

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    elementwise_add->LinksFrom({mul_out_var, bias})
        .LinksTo({elementwise_add_out_var});
    if (!with_relu) {
      return elementwise_add_out_var;
    } else {
      elementwise_add_out_var->AsIntermediate()->assert_is_op_input("relu");
      // Create operators.
      auto *relu = pattern->NewNode(relu_repr())->assert_is_op("relu");
      auto *relu_out_var = pattern->NewNode(relu_out_repr())
                               ->AsOutput()
                               ->assert_is_op_output("relu");

      relu->LinksFrom({elementwise_add_out_var}).LinksTo({relu_out_var});
      return relu_out_var;
    }
1057 1058
  }
}
T
tensor-tang 已提交
1059

1060
PDNode *patterns::FCMKLDNN::operator()(bool with_residual_data) {
1061 1062
  auto *fc_op = pattern->NewNode(fc_repr())->assert_is_op("fc");
  // Create variables
M
Michał Gallus 已提交
1063 1064 1065 1066
  // Input
  auto *input_var = pattern->NewNode(input_repr())
                        ->AsInput()
                        ->assert_is_op_input("fc", "Input");
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  // Filter
  auto *fc_weight_var = pattern->NewNode(weights_repr())
                            ->AsInput()
                            ->assert_is_op_input("fc", "W");
  // Bias
  auto *fc_bias_var = pattern->NewNode(bias_repr())
                          ->AsInput()
                          ->assert_is_op_input("fc", "Bias");
  // Output
  auto *fc_out_var = pattern->NewNode(output_repr())
                         ->AsOutput()
                         ->assert_is_op_output("fc", "Out")
                         ->assert_is_only_output_of_op("fc");

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  std::vector<PDNode *> links_from{input_var, fc_weight_var, fc_bias_var};
  if (with_residual_data) {
    auto res_fc_var = pattern->NewNode(residual_data_repr())
                          ->AsInput()
                          ->assert_is_op_input("fc")
                          // assert_is_op_input with two arguments doesn't work
                          // because ResidualData in FC is set as output with
                          // SetOutput so we do custom assert output
                          ->assert_more([&](Node *x) {
                            for (auto *op : x->outputs)
                              if (IsNthOutput(x, op, "ResidualData", 0))
                                return true;
                            return false;
                          });
    links_from.push_back(res_fc_var);
  } else {
    fc_op->assert_more([&](Node *x) {
      if (!HasOutput(x, "ResidualData") ||
          x->Op()->Output("ResidualData").size() == 0)
        return true;
      return false;
    });
  }

  fc_op->LinksFrom(links_from).LinksTo({fc_out_var});
1106 1107 1108
  return fc_out_var;
}

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
PDNode *patterns::Embedding::operator()(PDNode *x) {
  x->assert_is_op_input("lookup_table", "Ids");
  auto *lookup_table_op =
      pattern->NewNode(lookup_table_repr())->assert_is_op("lookup_table");
#define NEW_NODE(arg__, io__)                    \
  auto *arg__ = pattern->NewNode(arg__##_repr()) \
                    ->assert_is_op_##io__("lookup_table", #arg__);

  NEW_NODE(W, input);

  NEW_NODE(Out, output);
#undef NEW_NODE

  lookup_table_op->LinksFrom({x, W});
  lookup_table_op->LinksTo({Out});
  return Out;
}

C
chengduo 已提交
1127
PDNode *patterns::LSTM::operator()(PDNode *x) {
1128
  x->assert_is_op_input("lstm", "Input");
C
chengduo 已提交
1129
  auto *lstm_op = pattern->NewNode(lstm_repr())->assert_is_op("lstm");
Y
Yan Chunwei 已提交
1130
#define NEW_NODE(arg__, io__) \
C
chengduo 已提交
1131
  auto *arg__ =               \
Y
Yan Chunwei 已提交
1132
      pattern->NewNode(arg__##_repr())->assert_is_op_##io__("lstm", #arg__);
1133 1134 1135 1136 1137

  // Currently, the H0 and C0 are optional
  // TODO(Superjomn) upgrade the fuse framework to support optional.
  // NEW_NODE(H0, input);
  // NEW_NODE(C0, input);
Y
Yan Chunwei 已提交
1138 1139
  NEW_NODE(Weight, input);
  NEW_NODE(Bias, input);
1140

Y
Yan Chunwei 已提交
1141 1142 1143 1144 1145
  NEW_NODE(Hidden, output);
  NEW_NODE(Cell, output);
  NEW_NODE(BatchGate, output);
  NEW_NODE(BatchCellPreAct, output);
#undef NEW_NODE
1146 1147 1148 1149 1150

  lstm_op->LinksFrom({x, Weight, Bias});
  lstm_op->LinksTo({Hidden, Cell, BatchGate, BatchCellPreAct});
  return Hidden;
}
T
tensor-tang 已提交
1151

C
chengduo 已提交
1152
PDNode *patterns::GRU::operator()(PDNode *x) {
T
tensor-tang 已提交
1153
  x->assert_is_op_input("gru", "Input");
C
chengduo 已提交
1154
  auto *gru_op = pattern->NewNode(gru_repr())->assert_is_op("gru");
Y
Yan Chunwei 已提交
1155
#define NEW_NODE(arg__, io__) \
C
chengduo 已提交
1156
  auto *arg__ =               \
Y
Yan Chunwei 已提交
1157
      pattern->NewNode(arg__##_repr())->assert_is_op_##io__("gru", #arg__);
T
tensor-tang 已提交
1158

Y
Yan Chunwei 已提交
1159
  NEW_NODE(Weight, input);
T
tensor-tang 已提交
1160 1161
  // TODO(Superjomn): upgrade the fuse framework to support optional.
  // H0 and bias are optional
Y
Yan Chunwei 已提交
1162
  NEW_NODE(Bias, input);  // also optional
T
tensor-tang 已提交
1163 1164
  // NEW_NODE(H0, input);

Y
Yan Chunwei 已提交
1165
  NEW_NODE(Hidden, output);
T
tensor-tang 已提交
1166
  // below are intermediate
Y
Yan Chunwei 已提交
1167 1168 1169 1170
  NEW_NODE(BatchGate, output);
  NEW_NODE(BatchResetHiddenPrev, output);
  NEW_NODE(BatchHidden, output);
#undef NEW_NODE
T
tensor-tang 已提交
1171

T
tensor-tang 已提交
1172 1173 1174 1175
  BatchGate->AsIntermediate();
  BatchResetHiddenPrev->AsIntermediate();
  BatchHidden->AsIntermediate();

T
tensor-tang 已提交
1176 1177 1178 1179 1180
  gru_op->LinksFrom({x, Weight, Bias});
  gru_op->LinksTo({Hidden, BatchGate, BatchResetHiddenPrev, BatchHidden});
  return Hidden;
}

C
chengduo 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
PDNode *patterns::ActElewiseAdd::operator()(
    paddle::framework::ir::PDNode *in_var,
    std::unordered_set<std::string> act_types) {
  in_var->assert_is_ops_input(act_types, "X");

  auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);
  auto *act_out_var = pattern->NewNode(act_out_repr())
                          ->assert_is_not_ctrl_var()
                          ->assert_is_ops_output(act_types);
  act_out_var->AsIntermediate()->assert_is_op_input("elementwise_add");

  auto *ele_x_var = pattern->NewNode(ele_x_repr())
                        ->assert_is_not_ctrl_var()
                        ->assert_is_op_input("elementwise_add")
                        ->AsInput();
  auto *elementwise_add =
      pattern->NewNode(ele_add_repr())->assert_is_op("elementwise_add");

  auto *elewise_add_out = pattern->NewNode(elewise_add_out_repr())
                              ->AsOutput()
                              ->assert_is_op_output("elementwise_add", "Out");

  act->LinksFrom({in_var}).LinksTo({act_out_var});
  elementwise_add->LinksFrom({act_out_var, ele_x_var})
      .LinksTo({elewise_add_out});

  return elewise_add_out;
}

Z
Zhen Wang 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
PDNode *patterns::BatchNormAct::operator()(
    paddle::framework::ir::PDNode *bn_x_var,
    std::unordered_set<std::string> act_types) {
  auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
                           ->assert_is_op_input("batch_norm", "Scale");
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->assert_is_op_input("batch_norm", "Bias");
  auto *bn_variance_var = pattern->NewNode(bn_variance_repr())
                              ->assert_is_op_input("batch_norm", "Variance");
  auto *bn_mean_var = pattern->NewNode(bn_mean_repr())
                          ->assert_is_op_input("batch_norm", "Mean");

  auto *bn = pattern->NewNode(batch_norm_repr())
                 ->assert_is_op("batch_norm")
                 ->assert_is_not_op_input("MomentumTensor")
                 ->assert_op_attr<bool>("is_test", false)
                 ->assert_op_attr<bool>("use_global_stats", false)
                 ->assert_op_attr<std::string>("data_layout", "NHWC");

  auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
                              ->assert_is_op_output("batch_norm", "MeanOut");
  auto *bn_variance_out_var =
      pattern->NewNode(bn_variance_out_repr())
          ->assert_is_op_output("batch_norm", "VarianceOut");
  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->assert_is_op_output("batch_norm", "SavedVariance");
  auto *bn_saved_mean_var =
      pattern->NewNode(bn_saved_mean_repr())
          ->assert_is_op_output("batch_norm", "SavedMean");
  auto *bn_reserve_space =
      pattern->NewNode(bn_reserve_space_repr())
          ->assert_is_op_output("batch_norm", "ReserveSpace");
  auto *bn_out_var = pattern->NewNode(bn_out_repr())
                         ->assert_is_op_output("batch_norm", "Y")
                         ->assert_has_n_outputs(1);

  bn_out_var->AsIntermediate()->assert_is_ops_input(act_types);

  auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);

  auto *act_out_var =
      pattern->NewNode(act_out_repr())->assert_is_ops_output(act_types, "Out");

  bn->LinksFrom(
        {bn_x_var, bn_scale_var, bn_bias_var, bn_variance_var, bn_mean_var})
1256 1257 1258 1259 1260 1261
      .LinksTo({bn_mean_out_var,
                bn_variance_out_var,
                bn_saved_variance_var,
                bn_saved_mean_var,
                bn_reserve_space,
                bn_out_var});
Z
Zhen Wang 已提交
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
  act->LinksFrom({bn_out_var}).LinksTo({act_out_var});

  return act_out_var;
}

PDNode *patterns::BatchNormActGrad::operator()(
    paddle::framework::ir::PDNode *d_act_out_var,
    std::unordered_set<std::string> act_grad_types) {
  auto *act_grad =
      pattern->NewNode(act_grad_repr())->assert_is_ops(act_grad_types);
  auto *bn_grad = pattern->NewNode(batch_norm_grad_repr())
                      ->assert_is_op("batch_norm_grad")
                      ->assert_op_attr<bool>("use_global_stats", false)
                      ->assert_op_attr<std::string>("data_layout", "NHWC");

  auto *act_out_var = pattern->NewNode(act_out_repr())
                          ->assert_is_ops_input(act_grad_types, "Out");
  auto *d_intermediate_var =
      pattern->NewNode(d_itermediate_out_repr())
          ->assert_is_ops_output(act_grad_types, GradVarName("X"))
          ->assert_has_n_outputs(1);
  auto *bn_x_var = pattern->NewNode(bn_x_repr())
                       ->assert_is_op_input("batch_norm_grad", "X")
                       ->assert_var_dtype(proto::VarType::FP16);
  auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
                           ->assert_is_op_input("batch_norm_grad", "Scale");
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->assert_is_op_input("batch_norm_grad", "Bias");
  auto *bn_saved_mean_var =
      pattern->NewNode(bn_saved_mean_repr())
          ->assert_is_op_input("batch_norm_grad", "SavedMean");
  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->assert_is_op_input("batch_norm_grad", "SavedVariance");
  // ReserveSpace as the output is equal to:
  // data_layout == 'NHWC' && FLAGS_cudnn_batchnorm_spatial_persistent == true
  auto *bn_reserve_space =
      pattern->NewNode(bn_reserve_space_repr())
          ->assert_is_op_input("batch_norm_grad", "ReserveSpace");
  auto *d_bn_x_var =
      pattern->NewNode(d_bn_x_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("X"));
  auto *d_bn_scale_var =
      pattern->NewNode(d_bn_scale_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("Scale"));
  auto *d_bn_bias_var =
      pattern->NewNode(d_bn_bias_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("Bias"));

  act_grad->LinksFrom({d_act_out_var, act_out_var})
      .LinksTo({d_intermediate_var});

  bn_grad
1318 1319 1320 1321 1322 1323 1324
      ->LinksFrom({bn_x_var,
                   d_intermediate_var,
                   bn_scale_var,
                   bn_bias_var,
                   bn_saved_mean_var,
                   bn_saved_variance_var,
                   bn_reserve_space})
Z
Zhen Wang 已提交
1325 1326 1327 1328 1329
      .LinksTo({d_bn_x_var, d_bn_scale_var, d_bn_bias_var});

  return bn_grad;
}

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
PDNode *patterns::BatchNormActOneDNN::operator()(const std::string &act_type) {
  auto *bn_x = pattern->NewNode(bn_in_repr())
                   ->AsInput()
                   ->assert_is_op_input("batch_norm", "X");
  auto *bn = pattern->NewNode(batch_norm_repr())->assert_is_op("batch_norm");
  auto *bn_out = pattern->NewNode(bn_out_repr())
                     ->assert_is_op_output("batch_norm", "Y")
                     ->assert_is_op_input(act_type);
  auto *act =
      pattern->NewNode(act_repr())->assert_is_op(act_type)->AsIntermediate();
  auto *act_out = pattern->NewNode(act_out_repr())
                      ->assert_is_op_output(act_type, "Out")
                      ->AsOutput();

  bn->LinksFrom({bn_x}).LinksTo({bn_out});
  act->LinksFrom({bn_out}).LinksTo({act_out});

  return act_out;
}

Z
Zhang Ting 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
PDNode *patterns::BatchNormAddAct::operator()(
    paddle::framework::ir::PDNode *bn_x_var,
    std::unordered_set<std::string> act_types) {
  bn_x_var->assert_is_op_input("batch_norm", "X")
      ->assert_var_dtype(proto::VarType::FP16);
  auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
                           ->assert_is_op_input("batch_norm", "Scale");
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->assert_is_op_input("batch_norm", "Bias");

  auto *bn = pattern->NewNode(batch_norm_repr())
                 ->assert_is_op("batch_norm")
                 ->assert_is_not_op_input("MomentumTensor")
                 ->assert_op_attr<bool>("is_test", false)
                 ->assert_op_attr<bool>("use_global_stats", false)
                 ->assert_op_attr<std::string>("data_layout", "NHWC");

  auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
                              ->assert_is_op_output("batch_norm", "MeanOut");
  auto *bn_variance_out_var =
      pattern->NewNode(bn_variance_out_repr())
          ->assert_is_op_output("batch_norm", "VarianceOut");
  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->assert_is_op_output("batch_norm", "SavedVariance");
  auto *bn_saved_mean_var =
      pattern->NewNode(bn_saved_mean_repr())
          ->assert_is_op_output("batch_norm", "SavedMean");
  auto *bn_reserve_space =
      pattern->NewNode(bn_reserve_space_repr())
          ->assert_is_op_output("batch_norm", "ReserveSpace");
  auto *bn_out_var = pattern->NewNode(bn_out_repr())
                         ->assert_is_op_output("batch_norm", "Y")
                         ->assert_var_dtype(proto::VarType::FP16);

  bn_out_var->assert_is_op_input("elementwise_add");

  auto *elewise_add =
      pattern->NewNode(elewise_add_repr())->assert_is_op("elementwise_add");

  auto *elewise_add_in_var = pattern->NewNode(elewise_add_in_repr())
                                 ->assert_is_not_ctrl_var()
                                 ->assert_is_op_input("elementwise_add")
                                 ->assert_var_dtype(proto::VarType::FP16);

  auto *elewise_add_out_var =
      pattern->NewNode(elewise_add_out_repr())
          ->assert_is_op_output("elementwise_add", "Out")
          ->assert_has_n_outputs(1);

  elewise_add_out_var->AsIntermediate()->assert_is_ops_input(act_types);

  auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);

  auto *act_out_var =
      pattern->NewNode(act_out_repr())->assert_is_ops_output(act_types, "Out");

  bn->LinksFrom({bn_x_var, bn_scale_var, bn_bias_var})
1408 1409 1410 1411 1412 1413
      .LinksTo({bn_mean_out_var,
                bn_variance_out_var,
                bn_saved_variance_var,
                bn_saved_mean_var,
                bn_reserve_space,
                bn_out_var});
Z
Zhang Ting 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  elewise_add->LinksFrom({elewise_add_in_var, bn_out_var})
      .LinksTo({elewise_add_out_var});
  act->LinksFrom({elewise_add_out_var}).LinksTo({act_out_var});

  return act_out_var;
}

PDNode *patterns::BatchNormAddActGrad::operator()(
    paddle::framework::ir::PDNode *d_act_out_var,
    std::unordered_set<std::string> act_grad_types) {
  auto *act_grad =
      pattern->NewNode(act_grad_repr())->assert_is_ops(act_grad_types);
  auto *elewise_add_grad = pattern->NewNode(elewise_add_grad_repr())
                               ->assert_is_op("elementwise_add_grad");
  auto *bn_grad = pattern->NewNode(batch_norm_grad_repr())
                      ->assert_is_op("batch_norm_grad")
                      ->assert_op_attr<bool>("use_global_stats", false)
                      ->assert_op_attr<std::string>("data_layout", "NHWC");

  auto *act_out_var = pattern->NewNode(act_out_repr())
                          ->assert_is_ops_input(act_grad_types, "Out");
  auto *d_act_x_var =
      pattern->NewNode(d_act_x_repr())
          ->assert_is_ops_output(act_grad_types, GradVarName("X"))
          ->assert_has_n_outputs(1);  // d_act_x

  d_act_x_var->AsIntermediate()->assert_is_op_input("elementwise_add_grad");

  auto *d_elewise_add_in_var =
      pattern->NewNode(d_elewise_add_in_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("elementwise_add_grad")
          ->assert_var_dtype(proto::VarType::FP16);  // d_add_in_1
  auto *d_bn_out_var =
      pattern->NewNode(d_bn_out_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("elementwise_add_grad")
          ->assert_var_dtype(proto::VarType::FP16);  // d_add_in_2

  d_bn_out_var->assert_is_op_input("batch_norm_grad", GradVarName("Y"));

  auto *bn_x_var = pattern->NewNode(bn_x_repr())
                       ->assert_is_op_input("batch_norm_grad", "X")
                       ->assert_var_dtype(proto::VarType::FP16);
  auto *bn_scale_var = pattern->NewNode(bn_scale_repr())
                           ->assert_is_op_input("batch_norm_grad", "Scale");
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->assert_is_op_input("batch_norm_grad", "Bias");
  auto *bn_saved_mean_var =
      pattern->NewNode(bn_saved_mean_repr())
          ->assert_is_op_input("batch_norm_grad", "SavedMean");
  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->assert_is_op_input("batch_norm_grad", "SavedVariance");

  auto *bn_reserve_space =
      pattern->NewNode(bn_reserve_space_repr())
          ->assert_is_op_input("batch_norm_grad", "ReserveSpace");
  auto *d_bn_x_var =
      pattern->NewNode(d_bn_x_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("X"))
          ->assert_var_dtype(proto::VarType::FP16);
  auto *d_bn_scale_var =
      pattern->NewNode(d_bn_scale_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("Scale"));
  auto *d_bn_bias_var =
      pattern->NewNode(d_bn_bias_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("batch_norm_grad", GradVarName("Bias"));

  act_grad->LinksFrom({d_act_out_var, act_out_var}).LinksTo({d_act_x_var});

  elewise_add_grad->LinksFrom({d_act_x_var})
      .LinksTo({d_elewise_add_in_var, d_bn_out_var});

  bn_grad
1492 1493 1494 1495 1496 1497 1498
      ->LinksFrom({bn_x_var,
                   d_bn_out_var,
                   bn_scale_var,
                   bn_bias_var,
                   bn_saved_mean_var,
                   bn_saved_variance_var,
                   bn_reserve_space})
Z
Zhang Ting 已提交
1499 1500 1501 1502 1503
      .LinksTo({d_bn_x_var, d_bn_scale_var, d_bn_bias_var});

  return bn_grad;
}

C
chengduo 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
PDNode *patterns::ElewiseAddActInplaceGrad::operator()(
    paddle::framework::ir::PDNode *d_act_out_var,
    std::unordered_set<std::string> act_types) {
  // act_grad: in["Out", "Out@GRAD"], out["X@GRAD"]
  // ele_add_grad: in["Y", "Out@GRAD"], out["X@GRAD", "Y@GRAD"]
  auto *act_grad = pattern->NewNode(act_grad_repr())->assert_is_ops(act_types);

  auto *act_out_var =
      pattern->NewNode(act_out_repr())->assert_is_ops_input(act_types, "Out");

  auto *d_intermediate_var =
      pattern->NewNode(d_itermediate_out_repr())
          ->assert_is_ops_output(act_types, GradVarName("X"));

  act_grad->LinksFrom({d_act_out_var, act_out_var})
      .LinksTo({d_intermediate_var});

  auto *ele_y_var = pattern->NewNode(ele_y_repr())
                        ->assert_is_not_ctrl_var()
                        ->assert_is_op_input("elementwise_add_grad", "Y");

  auto *ele_add_grad = pattern->NewNode(ele_add_grad_repr())
                           ->assert_is_op("elementwise_add_grad");

  auto *d_ele_x_var =
      pattern->NewNode(d_ele_x_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("elementwise_add_grad", GradVarName("X"));

  auto *d_ele_y_var =
      pattern->NewNode(d_ele_y_repr())
          ->assert_is_not_ctrl_var()
          ->assert_is_op_output("elementwise_add_grad", GradVarName("Y"));

  ele_add_grad->LinksFrom({d_intermediate_var, ele_y_var})
      .LinksTo({d_ele_x_var, d_ele_y_var});

  return ele_add_grad;
}

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
PDNode *patterns::ElewiseAddAct::operator()(
    paddle::framework::ir::PDNode *ele_x_var,
    std::unordered_set<std::string> act_types) {
  auto *ele_y_var = pattern->NewNode(ele_y_repr())
                        ->assert_is_op_input("elementwise_add", "Y");

  auto *ele_add =
      pattern->NewNode(ele_add_repr())->assert_is_op("elementwise_add");

  auto *ele_out_var = pattern->NewNode(elewise_add_out_repr())
                          ->assert_is_op_output("elementwise_add", "Out");

  ele_out_var->AsIntermediate()->assert_is_ops_input(act_types);

  auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);

  auto *act_out_var =
      pattern->NewNode(act_out_repr())->assert_is_ops_output(act_types, "Out");

  ele_add->LinksFrom({ele_x_var, ele_y_var}).LinksTo({ele_out_var});
  act->LinksFrom({ele_out_var}).LinksTo({act_out_var});

  return act_out_var;
}

PDNode *patterns::LinearAct::operator()(
    paddle::framework::ir::PDNode *linear_x_var,
1571 1572
    const std::unordered_set<std::string> &act_types,
    bool with_grad_link,
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    bool is_act_grad_x_from_act) {
  auto *matmul_w_var =
      pattern->NewNode(matmul_w_repr())->assert_is_op_input("matmul_v2", "Y");

  auto *matmul = pattern->NewNode(matmul_repr())->assert_is_op("matmul_v2");

  auto *matmul_out_var = pattern->NewNode(matmul_out_repr())
                             ->assert_is_op_output("matmul_v2", "Out");

  matmul_out_var->AsIntermediate()->assert_is_op_input("elementwise_add", "X");

  auto *ele_bias_var = pattern->NewNode(ele_bias_repr())
                           ->assert_is_op_input("elementwise_add", "Y");

  auto *ele_add =
      pattern->NewNode(ele_add_repr())->assert_is_op("elementwise_add");

  auto *ele_out_var = pattern->NewNode(elewise_add_out_repr())
                          ->assert_is_op_output("elementwise_add", "Out");

  matmul->LinksFrom({linear_x_var, matmul_w_var}).LinksTo({matmul_out_var});
  ele_add->LinksFrom({matmul_out_var, ele_bias_var}).LinksTo({ele_out_var});

  if (with_grad_link) {
    matmul_out_var->assert_is_op_input("elementwise_add_grad", "X");
    auto *elementwise_add_grad_op = pattern->NewNode("elementwise_add_grad")
                                        ->assert_is_op("elementwise_add_grad");
    elementwise_add_grad_op->LinksFrom({matmul_out_var});
  }

  if (act_types.size() > 0) {
    ele_out_var->AsIntermediate()->assert_is_ops_input(act_types);

    auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types);
    auto *act_out_var = pattern->NewNode(act_out_repr())
                            ->assert_is_ops_output(act_types, "Out");

    act->LinksFrom({ele_out_var}).LinksTo({act_out_var});

    if (with_grad_link && !is_act_grad_x_from_act) {
      std::unordered_set<std::string> act_grad_types;
      for (const auto &act : act_types) {
        std::string act_grad(act);
        act_grad.append("_grad");
        act_grad_types.insert(act_grad);
      }

      ele_out_var->assert_is_ops_input(act_grad_types, "X");
      auto *act_grad_op =
          pattern->NewNode(act_grad_repr())->assert_is_ops(act_grad_types);
      act_grad_op->LinksFrom({ele_out_var});
    }

    return act_out_var;
  }

  return ele_out_var;
}

PDNode *patterns::ElewiseAddMatmulAct::operator()(
    paddle::framework::ir::PDNode *dout_var,
    const std::unordered_set<std::string> &act_grad_types,
1635 1636
    bool without_x_gradient,
    bool is_act_grad_x_from_act) {
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
  auto *ele_grad_bias_var =
      pattern->NewNode(ele_grad_bias_repr())
          ->assert_is_op_input("elementwise_add_grad", "Y");
  auto *ele_add_grad = pattern->NewNode(ele_add_grad_repr())
                           ->assert_is_op("elementwise_add_grad");
  auto *ele_grad_dx_var =
      pattern->NewNode(ele_grad_dx_repr())
          ->assert_is_op_output("elementwise_add_grad", GradVarName("X"));
  auto *ele_grad_dbias_var =
      pattern->NewNode(ele_grad_dbias_repr())
          ->assert_is_op_output("elementwise_add_grad", GradVarName("Y"));
  ele_add_grad->LinksFrom({dout_var, ele_grad_bias_var})
      .LinksTo({ele_grad_dx_var, ele_grad_dbias_var});

  ele_grad_dx_var->AsIntermediate()->assert_is_op_input("matmul_v2_grad",
                                                        GradVarName("Out"));

  auto *matmul_grad_x_var = pattern->NewNode(matmul_grad_x_repr())
                                ->assert_is_op_input("matmul_v2_grad", "X");
  auto *matmul_grad_w_var = pattern->NewNode(matmul_grad_w_repr())
                                ->assert_is_op_input("matmul_v2_grad", "Y");
  auto *matmul_grad =
      pattern->NewNode(matmul_grad_repr())->assert_is_op("matmul_v2_grad");
  auto *matmul_grad_dx_var =
      pattern->NewNode(matmul_grad_dx_repr())
          ->assert_is_op_output("matmul_v2_grad", GradVarName("X"));
  auto *matmul_grad_dw_var =
      pattern->NewNode(matmul_grad_dw_repr())
          ->assert_is_op_output("matmul_v2_grad", GradVarName("Y"));
  matmul_grad->LinksFrom(
      {ele_grad_dx_var, matmul_grad_x_var, matmul_grad_w_var});
  if (without_x_gradient) {
    matmul_grad->LinksTo({matmul_grad_dw_var});
  } else {
    matmul_grad->LinksTo({matmul_grad_dx_var, matmul_grad_dw_var});
  }

  if (!without_x_gradient && act_grad_types.size() > 0) {
    matmul_grad_dx_var->AsIntermediate()->assert_is_ops_input(
        act_grad_types, GradVarName("Out"));

    auto *act_grad =
        pattern->NewNode(act_grad_repr())->assert_is_ops(act_grad_types);
    auto *act_grad_dx_var =
        pattern->NewNode(act_grad_dx_repr())
            ->assert_is_ops_output(act_grad_types, GradVarName("X"));

    auto *act_grad_x_var = matmul_grad_x_var;
    if (!is_act_grad_x_from_act) {
      auto *ele_out_var = pattern->NewNode(ele_out_repr())
                              ->assert_is_ops_input(act_grad_types, "X");
      act_grad_x_var = ele_out_var;
    }

    act_grad->LinksFrom({matmul_grad_dx_var, act_grad_x_var})
        .LinksTo({act_grad_dx_var});
    return act_grad;
  }

  return matmul_grad;
}

1699
// conv_type: conv2d, conv3d, conv2d_transpose
M
Michal Gallus 已提交
1700
PDNode *patterns::ConvBias::operator()(
1701
    paddle::framework::ir::PDNode *conv_input, std::string conv_type) {
M
Michal Gallus 已提交
1702
  // Create Operators
1703 1704
  conv_input->assert_is_op_input(conv_type, "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
M
Michal Gallus 已提交
1705 1706 1707 1708
  auto *eltiwse_op =
      pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
  // Create variables
  // Filter
Y
Yihua Xu 已提交
1709 1710
  auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
                              ->AsInput()
1711
                              ->assert_is_op_input(conv_type, "Filter");
M
Michal Gallus 已提交
1712
  // intermediate variable, will be removed in the IR after fuse.
Y
Yihua Xu 已提交
1713 1714
  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
1715
                           ->assert_is_only_output_of_op(conv_type)
Y
Yihua Xu 已提交
1716
                           ->assert_is_op_input("elementwise_add");
M
Michal Gallus 已提交
1717 1718 1719
  // Bias stored in elementwise_add
  auto *eltwise_bias_var = pattern->NewNode(eltwise_bias_repr())
                               ->AsInput()
M
Michal Gallus 已提交
1720
                               ->assert_is_persistable_var()
M
Michal Gallus 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
                               ->assert_is_op_input("elementwise_add", "Y");
  // output
  auto *eltwise_out_var = pattern->NewNode(eltwise_out_repr())
                              ->AsOutput()
                              ->assert_is_op_output("elementwise_add");
  conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});
  eltiwse_op->LinksFrom({conv_out_var, eltwise_bias_var})
      .LinksTo({eltwise_out_var});
  return eltwise_out_var;
}

1732 1733 1734 1735
PDNode *patterns::Conv::operator()() {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");

  auto input_var = pattern->NewNode(conv_input_repr())
1736
                       ->AsInput()
1737 1738 1739
                       ->assert_is_op_input("conv2d", "Input");

  auto filter_var = pattern->NewNode(conv_filter_repr())
1740
                        ->AsInput()
1741 1742 1743
                        ->assert_is_op_input("conv2d", "Filter");

  auto output_var = pattern->NewNode(conv_output_repr())
1744
                        ->AsOutput()
1745 1746
                        ->assert_is_op_output("conv2d", "Output");

1747 1748 1749 1750
  conv_op->LinksFrom({input_var, filter_var}).LinksTo({output_var});
  return output_var;
}

1751 1752
PDNode *patterns::Immutable::operator()(const std::string &immutable_type,
                                        const std::string &input_name) {
1753 1754
  auto prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();

1755 1756
  auto immutable_op =
      pattern->NewNode(immutable_op_repr())->assert_is_op(immutable_type);
1757

1758
  auto immutable_in = pattern->NewNode(immutable_in_repr())
1759
                          ->AsInput()
1760 1761
                          ->assert_is_op_input(immutable_type, input_name);
  auto immutable_out = pattern->NewNode(immutable_out_repr())
1762
                           ->AsOutput()
1763
                           ->assert_is_op_output(immutable_type, "Out");
1764

1765 1766 1767
  prev_op->LinksTo({immutable_in});
  immutable_op->LinksFrom({immutable_in}).LinksTo({immutable_out});
  return immutable_out;
1768 1769
}

1770
PDNode *patterns::Matmul::operator()() {
1771 1772 1773 1774 1775 1776 1777
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");

  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->AsInput()
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y = pattern->NewNode(matmul_in_y_repr())
                         ->AsInput()
1778
                         ->assert_is_persistable_var()
1779 1780 1781 1782 1783 1784 1785 1786 1787
                         ->assert_is_op_input("matmul", "Y");
  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("matmul", "Out");

  matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({matmul_out});
  return matmul_out;
}

1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
// MatmulV2: tensor * weight
PDNode *patterns::MatmulV2Weight::operator()() {
  auto matmul_v2_op =
      pattern->NewNode(matmul_v2_op_repr())->assert_is_op("matmul_v2");

  auto matmul_v2_in_x = pattern->NewNode(matmul_v2_in_x_repr())
                            ->AsInput()
                            ->assert_is_op_input("matmul_v2", "X");
  auto matmul_v2_in_y = pattern->NewNode(matmul_v2_in_y_repr())
                            ->AsInput()
                            ->assert_is_persistable_var()  // Y is weight
                            ->assert_is_op_input("matmul_v2", "Y");
  auto matmul_v2_out = pattern->NewNode(matmul_v2_out_repr())
                           ->AsOutput()
                           ->assert_is_op_output("matmul_v2", "Out");

  matmul_v2_op->LinksFrom({matmul_v2_in_x, matmul_v2_in_y})
      .LinksTo({matmul_v2_out});
  return matmul_v2_out;
}

// MatmulV2: tensor * tensor or tensor * weight
1810
PDNode *patterns::MatmulV2::operator()() {
1811 1812
  auto matmul_v2_op =
      pattern->NewNode(matmul_v2_op_repr())->assert_is_op("matmul_v2");
1813

1814 1815 1816 1817 1818 1819 1820 1821 1822
  auto matmul_v2_in_x = pattern->NewNode(matmul_v2_in_x_repr())
                            ->AsInput()
                            ->assert_is_op_input("matmul_v2", "X");
  auto matmul_v2_in_y = pattern->NewNode(matmul_v2_in_y_repr())
                            ->AsInput()
                            ->assert_is_op_input("matmul_v2", "Y");
  auto matmul_v2_out = pattern->NewNode(matmul_v2_out_repr())
                           ->AsOutput()
                           ->assert_is_op_output("matmul_v2", "Out");
1823

1824 1825 1826
  matmul_v2_op->LinksFrom({matmul_v2_in_x, matmul_v2_in_y})
      .LinksTo({matmul_v2_out});
  return matmul_v2_out;
1827 1828
}

H
heliqi 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
PDNode *patterns::MatmulScale::operator()() {
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->AsInput()
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y = pattern->NewNode(matmul_in_y_repr())
                         ->AsInput()
                         ->assert_is_op_input("matmul", "Y");
  auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");
  auto scale_in_x = pattern->NewNode(scale_in_x_repr())
                        ->assert_is_op_output("matmul", "Out")
                        ->assert_is_op_input("scale", "X");
  auto scale_out = pattern->NewNode(scale_out_repr())
                       ->AsOutput()
                       ->assert_is_op_output("scale", "Out");
  matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({scale_in_x});
  scale_op->LinksFrom({scale_in_x}).LinksTo({scale_out});
  return scale_out;
}

PDNode *patterns::MatmulV2Scale::operator()() {
  auto matmul_v2_op =
      pattern->NewNode(matmul_v2_op_repr())->assert_is_op("matmul_v2");
  auto matmul_v2_in_x = pattern->NewNode(matmul_v2_in_x_repr())
                            ->AsInput()
                            ->assert_is_op_input("matmul_v2", "X");
  auto matmul_v2_in_y = pattern->NewNode(matmul_v2_in_y_repr())
                            ->AsInput()
                            ->assert_is_persistable_var()  // Y is weight
                            ->assert_is_op_input("matmul_v2", "Y");
  auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");
  auto scale_in_x = pattern->NewNode(scale_in_x_repr())
                        ->assert_is_op_output("matmul_v2", "Out")
                        ->assert_is_op_input("scale", "X");
  auto scale_out = pattern->NewNode(scale_out_repr())
                       ->AsOutput()
                       ->assert_is_op_output("scale", "Out");
  matmul_v2_op->LinksFrom({matmul_v2_in_x, matmul_v2_in_y})
      .LinksTo({scale_in_x});
  scale_op->LinksFrom({scale_in_x}).LinksTo({scale_out});
  return scale_out;
}

1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
PDNode *patterns::Squeeze2Matmul::operator()() {
  auto squeeze2_in_x = pattern->NewNode(squeeze2_in_x_repr())
                           ->assert_is_op_input("squeeze2", "X")
                           ->AsInput();
  auto squeeze2_op =
      pattern->NewNode(squeeze2_op_repr())->assert_is_op("squeeze2");
  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->assert_is_op_output("squeeze2", "Out")
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y =
      pattern->NewNode(matmul_in_y_repr())->assert_is_op_input("matmul", "Y");
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("matmul", "Out");

  squeeze2_op->LinksFrom({squeeze2_in_x}).LinksTo({matmul_in_x});
  matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({matmul_out});
  return matmul_out;
}

PDNode *patterns::Reshape2Matmul::operator()() {
  auto reshape2_in_x = pattern->NewNode(reshape2_in_x_repr())
                           ->assert_is_op_input("reshape2", "X")
                           ->AsInput();
  auto reshape2_op =
      pattern->NewNode(reshape2_op_repr())->assert_is_op("reshape2");
  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->assert_is_op_output("reshape2", "Out")
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y =
      pattern->NewNode(matmul_in_y_repr())->assert_is_op_input("matmul", "Y");
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("matmul", "Out");

  reshape2_op->LinksFrom({reshape2_in_x}).LinksTo({matmul_in_x});
  matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({matmul_out});
  return matmul_out;
}

1914
PDNode *patterns::MatmulWithInputOps::operator()(bool with_residual) {
1915 1916 1917 1918
  auto prev_op_x = pattern->NewNode(prev_op_x_repr())->assert_is_op();
  auto prev_op_y = pattern->NewNode(prev_op_y_repr())->assert_is_op();

  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
1919 1920 1921 1922 1923 1924 1925 1926

  if (!with_residual) {
    matmul_op->assert_more([&](Node *x) {
      return (!HasInput(x, "ResidualData") ||
              x->Op()->Input("ResidualData").size() == 0);
    });
  }

1927 1928 1929 1930 1931 1932 1933 1934
  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->AsInput()
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y = pattern->NewNode(matmul_in_y_repr())
                         ->AsInput()
                         ->assert_is_op_input("matmul", "Y");
  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
                        ->assert_is_op_output("matmul", "Out")
                        ->assert_is_only_output_of_op("matmul");
  std::vector<PDNode *> links_from{matmul_in_x, matmul_in_y};

  if (with_residual) {
    auto matmul_residual_data =
        pattern->NewNode(matmul_residual_data_repr())
            ->AsInput()
            ->assert_is_op_input("matmul", "ResidualData");
    links_from.push_back(matmul_residual_data);
  }
1946 1947 1948

  prev_op_x->LinksTo({matmul_in_x});
  prev_op_y->LinksTo({matmul_in_y});
1949
  matmul_op->LinksFrom(links_from).LinksTo({matmul_out});
1950 1951 1952
  return matmul_out;
}

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
PDNode *patterns::Flatten2Matmul::operator()() {
  auto flatten2_in_x = pattern->NewNode(flatten2_in_x_repr())
                           ->assert_is_op_input("flatten2", "X")
                           ->AsInput();
  auto flatten2_op =
      pattern->NewNode(flatten2_op_repr())->assert_is_op("flatten2");
  auto matmul_in_x = pattern->NewNode(matmul_in_x_repr())
                         ->assert_is_op_output("flatten2", "Out")
                         ->assert_is_op_input("matmul", "X");
  auto matmul_in_y =
      pattern->NewNode(matmul_in_y_repr())->assert_is_op_input("matmul", "Y");
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");
  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("matmul", "Out");

  flatten2_op->LinksFrom({flatten2_in_x}).LinksTo({matmul_in_x});
  matmul_op->LinksFrom({matmul_in_x, matmul_in_y}).LinksTo({matmul_out});
  return matmul_out;
}

1974 1975 1976
PDNode *patterns::ConvResidual::operator()(bool with_residual_data) {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");

1977 1978 1979 1980 1981 1982 1983 1984
  if (!with_residual_data) {
    conv_op->assert_more([&](Node *x) {
      if (!HasInput(x, "ResidualData") ||
          x->Op()->Input("ResidualData").size() == 0)
        return true;
      return false;
    });
  }
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

  auto input_var = pattern->NewNode(conv_input_repr())
                       ->AsInput()
                       ->assert_is_op_input("conv2d", "Input");

  auto filter_var = pattern->NewNode(conv_filter_repr())
                        ->AsInput()
                        ->assert_is_op_input("conv2d", "Filter");

  auto output_var = pattern->NewNode(conv_output_repr())
                        ->AsOutput()
                        ->assert_is_op_output("conv2d", "Output");

  std::vector<PDNode *> links_from{input_var, filter_var};

  if (with_residual_data) {
    auto res_conn_var = pattern->NewNode(conv_residual_data_repr())
                            ->AsInput()
                            ->assert_is_op_input("conv2d", "ResidualData");
    links_from.push_back(res_conn_var);
  }

  conv_op->LinksFrom(links_from).LinksTo({output_var});
  return output_var;
}

PDNode *patterns::Pool::operator()() {
  auto pool_op = pattern->NewNode(pool_op_repr())->assert_is_op("pool2d");

  auto input_var = pattern->NewNode(pool_input_repr())
                       ->AsInput()
                       ->assert_is_op_input("pool2d", "X");

  auto output_var = pattern->NewNode(pool_output_repr())
                        ->AsOutput()
                        ->assert_is_op_output("pool2d", "Out");
2021

2022
  pool_op->LinksFrom({input_var}).LinksTo({output_var});
2023 2024 2025
  return output_var;
}

2026 2027
PDNode *patterns::Elementwise::operator()(PDNode *x_var,
                                          PDNode *y_var,
2028
                                          const std::string &elementwise_type) {
Z
Zuza 已提交
2029 2030 2031 2032 2033 2034
  auto elementwise_op =
      pattern->NewNode(elementwise_op_repr())->assert_is_op(elementwise_type);

  x_var->AsInput()->assert_is_op_input(elementwise_type, "X");
  y_var->AsInput()->assert_is_op_input(elementwise_type, "Y");
  auto out_var = pattern->NewNode(elementwise_out_repr())
2035
                     ->AsOutput()
Z
Zuza 已提交
2036
                     ->assert_is_op_output(elementwise_type, "Out");
2037

Z
Zuza 已提交
2038 2039
  elementwise_op->LinksFrom({x_var, y_var});
  elementwise_op->LinksTo({out_var});
2040 2041 2042

  return out_var;
}
2043

2044
PDNode *patterns::ElementwiseOp::operator()(
2045
    const std::string &elementwise_type) {
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
  auto elementwise_op =
      pattern->NewNode(elementwise_op_repr())->assert_is_op(elementwise_type);

  auto out_var = pattern->NewNode(elementwise_out_repr())
                     ->AsOutput()
                     ->assert_is_op_output(elementwise_type, "Out");

  elementwise_op->LinksTo({out_var});

  return out_var;
}

2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
PDNode *patterns::MatmulElementwiseAdd::operator()(
    const std::string &matmul_type, bool as_x) {
  auto matmul_op =
      pattern->NewNode(matmul_op_repr())->assert_is_op(matmul_type);
  auto matmul_out =
      pattern->NewNode(matmul_out_repr())
          ->AsIntermediate()
          ->assert_is_op_output(matmul_type, "Out")
          ->assert_is_only_output_of_op(matmul_type)
          ->assert_is_op_input("elementwise_add", as_x ? "X" : "Y");
  auto elementwise_addend =
      pattern->NewNode(elementwise_addend_repr())
          ->AsInput()
          ->assert_is_op_input("elementwise_add", as_x ? "Y" : "X");
  auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
                                ->assert_is_op("elementwise_add");
  auto elementwise_add_out =
      pattern->NewNode(elementwise_add_out_repr())
          ->AsOutput()
          ->assert_is_op_output("elementwise_add", "Out");

  matmul_op->LinksTo({matmul_out});
  elementwise_add_op->LinksFrom({matmul_out, elementwise_addend})
      .LinksTo({elementwise_add_out});
  return elementwise_add_out;
}

2085
PDNode *patterns::ResidualElementwise::operator()(
2086 2087
    PDNode *op_var,
    PDNode *residual_var,
2088
    const std::string &elementwise_type,
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
    bool as_x) {
  auto elementwise_op =
      pattern->NewNode(elementwise_op_repr())->assert_is_op(elementwise_type);

  if (as_x) {
    op_var->AsInput()->assert_is_op_input(elementwise_type, "X");
    residual_var->AsInput()->assert_is_op_input(elementwise_type, "Y");
  } else {
    op_var->AsInput()->assert_is_op_input(elementwise_type, "Y");
    residual_var->AsInput()->assert_is_op_input(elementwise_type, "X");
  }
  auto out_var = pattern->NewNode(elementwise_out_repr())
                     ->AsOutput()
                     ->assert_is_op_output(elementwise_type, "Out");

  elementwise_op->LinksFrom({op_var, residual_var});
  elementwise_op->LinksTo({out_var});

  return out_var;
}

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
PDNode *patterns::Concat::operator()() {
  auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");

  auto output_var = pattern->NewNode(concat_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("concat", "Out");

  concat_op->LinksTo({output_var});
  return output_var;
}

J
joanna.wozna.intel 已提交
2121 2122 2123 2124 2125 2126 2127 2128
PDNode *patterns::OpRequant::operator()() {
  auto any_op = pattern->NewNode(any_op_repr())
                    ->assert_is_op()
                    ->assert_more([&](Node *node) {
                      return node->Op()->HasAttr("Scale_out") ? true : false;
                    });
  auto requant_in = pattern->NewNode(requant_in_repr())
                        ->assert_is_op_input("requantize", "Input");
2129 2130 2131 2132 2133 2134
  auto requant_op =
      pattern->NewNode(requant_op_repr())->assert_is_op("requantize");
  auto requant_out = pattern->NewNode(requant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("requantize", "Output");

J
joanna.wozna.intel 已提交
2135 2136
  any_op->LinksTo({requant_in});
  requant_op->LinksFrom({requant_in}).LinksTo({requant_out});
2137 2138 2139
  return requant_out;
}

2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
PDNode *patterns::RequantOp::operator()() {
  auto requant_in = pattern->NewNode(requant_in_repr())
                        ->assert_is_op_input("requantize", "Input");
  auto requant_op =
      pattern->NewNode(requant_op_repr())->assert_is_op("requantize");
  auto requant_out = pattern->NewNode(requant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("requantize", "Output");
  auto any_op = pattern->NewNode(any_op_repr())
                    ->assert_is_op()
                    ->assert_more([&](Node *node) {
                      return (node->Op()->HasAttr("Scale_in") ||
                              node->Op()->HasAttr("Scale_x") ||
                              node->Op()->HasAttr("Scale_y"));
                    });

  requant_op->LinksFrom({requant_in}).LinksTo({requant_out});
  any_op->LinksFrom({requant_out});
  return any_op;
}

2161 2162 2163 2164
PDNode *patterns::OpDequant::operator()() {
  auto any_op = pattern->NewNode(any_op_repr())
                    ->assert_is_op()
                    ->assert_more([&](Node *node) {
2165 2166
                      return (node->Op()->HasAttr("force_fp32_output") ||
                              node->Op()->HasProtoAttr("force_fp32_output"));
2167 2168 2169
                    });
  auto dequant_in = pattern->NewNode(dequant_in_repr())
                        ->assert_is_op_input("dequantize", "Input");
2170 2171 2172 2173 2174 2175
  auto dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
  auto dequant_out = pattern->NewNode(dequant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("dequantize", "Output");

2176 2177
  any_op->LinksTo({dequant_in});
  dequant_op->LinksFrom({dequant_in}).LinksTo({dequant_out});
2178 2179 2180
  return dequant_out;
}

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
PDNode *patterns::DequantScale::operator()() {
  // Create Operators
  auto dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");
  auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");

  auto dequant_out = pattern->NewNode(dequant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("dequantize", "Output");
  auto scale_out = pattern->NewNode(scale_out_repr())
                       ->AsOutput()
                       ->assert_is_op_output("scale", "Out");

  dequant_op->LinksTo({dequant_out});
  scale_op->LinksFrom({dequant_out}).LinksTo({scale_out});

  return scale_out;
}

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
PDNode *patterns::ScaleQuant::operator()() {
  auto scale_in = pattern->NewNode(scale_in_repr())
                      ->AsInput()
                      ->assert_is_op_input("scale", "X");
  auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");

  auto quant_in = pattern->NewNode(quant_in_repr())
                      ->AsInput()
                      ->assert_is_op_input("quantize", "Input");
  auto quant_op = pattern->NewNode(quant_op_repr())->assert_is_op("quantize");

  scale_op->LinksFrom({scale_in}).LinksTo({quant_in});
  quant_op->LinksFrom({quant_in});

  return quant_op;
}

PDNode *patterns::QuantConv::operator()() {
  auto quant_in = pattern->NewNode(quant_in_repr())
                      ->AsInput()
                      ->assert_is_op_input("quantize", "Input");
  auto quant_op = pattern->NewNode(quant_op_repr())->assert_is_op("quantize");

  auto conv_in = pattern->NewNode(conv_in_repr())
                     ->AsInput()
                     ->assert_is_op_input("conv2d", "Input");
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  conv_op->assert_more([&](Node *node) {
    return node->Op()->GetAttrIfExists<std::string>("mkldnn_data_type") ==
           "bfloat16";
  });

  quant_op->LinksFrom({quant_in}).LinksTo({conv_in});
  conv_op->LinksFrom({conv_in});

  return quant_op;
}

2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
PDNode *patterns::ScaleMatmul::operator()() {
  auto scale_in = pattern->NewNode(scale_in_repr())
                      ->AsInput()
                      ->assert_is_op_input("scale", "X");
  auto scale_op = pattern->NewNode(scale_op_repr())->assert_is_op("scale");
  auto scale_out = pattern->NewNode(scale_out_repr())
                       ->AsOutput()
                       ->assert_is_op_output("scale", "Out");
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op("matmul");

  scale_op->LinksFrom({scale_in}).LinksTo({scale_out});
  matmul_op->LinksFrom({scale_out});
  return matmul_op;
}

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
PDNode *patterns::PriorBox::operator()() {
  auto prior_box_op =
      pattern->NewNode(prior_box_op_repr())->assert_is_op("prior_box");

  auto input_var = pattern->NewNode(prior_box_input_repr())
                       ->AsInput()
                       ->assert_is_op_input("prior_box", "Input");

  auto image_var = pattern->NewNode(prior_box_image_repr())
                       ->AsInput()
                       ->assert_is_op_input("prior_box", "Image");

  auto boxes_var = pattern->NewNode(prior_box_boxes_repr())
                       ->AsOutput()
                       ->assert_is_op_output("prior_box", "Boxes");

  auto variances_var = pattern->NewNode(prior_box_variances_repr())
                           ->AsOutput()
                           ->assert_is_op_output("prior_box", "Variances");

  prior_box_op->LinksFrom({input_var, image_var})
      .LinksTo({boxes_var, variances_var});
  return boxes_var;
}

X
xiaoxiaohehe001 已提交
2278
#if CUDNN_VERSION >= 8000
2279 2280
std::unordered_set<std::string> conv_act_set(
    {"identity", "relu", "sigmoid", "tanh"});
X
xiaoxiaohehe001 已提交
2281 2282 2283
#else
std::unordered_set<std::string> conv_act_set({"identity", "relu"});
#endif
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

PDNode *patterns::ConvElementwiseaddAct::operator()(PDNode *conv_in) {
  conv_in->AsInput();
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto conv_out = pattern->NewNode(conv_out_repr())
                      ->assert_is_op_output("conv2d")
                      ->assert_is_op_input("elementwise_add", "X")
                      ->AsIntermediate();
  auto conv_filter = pattern->NewNode(conv_filter_repr())
                         ->assert_is_op_input("conv2d", "Filter")
                         ->AsInput();
  auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
                                ->assert_is_op("elementwise_add");
  auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
2298
                                  ->assert_is_persistable_var()
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
                                  ->assert_is_op_input("elementwise_add", "Y")
                                  ->AsInput();
  auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
                                 ->assert_is_op_output("elementwise_add")
                                 ->AsIntermediate();

  auto act_op = pattern->NewNode(act_op_repr())
                    ->assert_is_op()
                    ->assert_more([&](Node *node) {
                      auto op_type = node->Name();
                      return conv_act_set.count(op_type);
                    });

  auto act_out = pattern->NewNode(act_out_repr())
                     ->assert_is_var()
                     // is activation op's output.
                     ->assert_more([&](Node *node) {
                       for (auto *in_op : node->inputs) {
                         if (conv_act_set.count(in_op->Name())) {
                           return true;
                         }
                       }
                       return false;
                     })
                     ->AsOutput();

  conv_op->LinksFrom({conv_in, conv_filter});
  conv_out->LinksFrom({conv_op});
  elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
      .LinksTo({elementwise_add_out});
  act_op->LinksFrom({elementwise_add_out}).LinksTo({act_out});

  return act_out;
}

F
feng_shuai 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
PDNode *patterns::VitAttention::operator()(PDNode *in) {
  in->AsInput();
  std::unordered_set<std::string> matmul_ops{"matmul", "matmul_v2"};

  auto matmul0_op =
      pattern->NewNode(matmul0_op_repr())->assert_is_ops(matmul_ops);
  auto matmul0_in_y = pattern->NewNode(matmul0_in_y_repr())
                          ->AsInput()
                          ->assert_is_ops_input(matmul_ops, "Y");
  auto matmul0_out = pattern->NewNode(matmul0_out_repr())
                         ->assert_is_ops_output(matmul_ops, "Out")
                         ->assert_is_op_input("elementwise_add", "X")
                         ->AsIntermediate();

  auto elementwise0_op =
      pattern->NewNode(elementwise0_op_repr())->assert_is_op("elementwise_add");
  auto elementwise0_in_y = pattern->NewNode(elementwise0_in_y_repr())
                               ->AsInput()
                               ->assert_is_op_input("elementwise_add", "Y");
  auto elementwise0_out = pattern->NewNode(elementwise0_out_repr())
                              ->assert_is_op_output("elementwise_add", "Out")
                              ->assert_is_op_input("reshape2", "X")
                              ->AsIntermediate();

  auto reshape1_op =
      pattern->NewNode(reshape1_op_repr())->assert_is_op("reshape2");
  auto reshape1_out = pattern->NewNode(reshape1_out_repr())
                          ->assert_is_op_output("reshape2", "Out")
                          ->assert_is_op_input("transpose2", "X")
                          ->AsIntermediate();

  auto transpose1_op =
      pattern->NewNode(transpose1_op_repr())->assert_is_op("transpose2");
  auto transpose1_out = pattern->NewNode(transpose1_out_repr())
                            ->assert_is_op_output("transpose2", "Out")
                            ->assert_is_op_input("slice", "Input")
                            ->AsIntermediate();

  auto slice1_op = pattern->NewNode(slice1_op_repr())->assert_is_op("slice");
  auto slice1_out = pattern->NewNode(slice1_out_repr())
                        ->assert_is_op_output("slice", "Out")
                        ->assert_is_op_input("matmul_v2", "Y")
                        ->AsIntermediate();

  auto slice2_op = pattern->NewNode(slice2_op_repr())->assert_is_op("slice");
  auto slice2_out = pattern->NewNode(slice2_out_repr())
                        ->assert_is_op_output("slice", "Out")
                        ->assert_is_op_input("matmul_v2", "X")
                        ->AsIntermediate();

  auto slice3_op = pattern->NewNode(slice3_op_repr())->assert_is_op("slice");
  auto slice3_out = pattern->NewNode(slice3_out_repr())
                        ->assert_is_op_output("slice", "Out")
                        ->assert_is_op_input("transpose2", "X")
                        ->AsIntermediate();

  auto transpose2_op =
      pattern->NewNode(transpose2_op_repr())->assert_is_op("transpose2");
  auto transpose2_out = pattern->NewNode(transpose2_out_repr())
                            ->assert_is_op_output("transpose2", "Out")
                            ->assert_is_op_input("matmul_v2", "Y")
                            ->AsIntermediate();

  auto matmul1_op =
      pattern->NewNode(matmul1_op_repr())->assert_is_op("matmul_v2");
  auto matmul1_out = pattern->NewNode(matmul1_out_repr())
                         ->assert_is_op_output("matmul_v2", "Out")
                         ->assert_is_op_input("scale", "X")
                         ->AsIntermediate();

  auto scale1_op = pattern->NewNode(scale1_op_repr())->assert_is_op("scale");
  auto scale1_out = pattern->NewNode(scale1_out_repr())
                        ->assert_is_op_output("scale", "Out")
                        ->assert_is_op_input("softmax", "X")
                        ->AsIntermediate();

  auto softmax1_op =
      pattern->NewNode(softmax1_op_repr())->assert_is_op("softmax");
  auto softmax1_out = pattern->NewNode(softmax1_out_repr())
                          ->assert_is_op_output("softmax", "Out")
                          ->assert_is_op_input("matmul_v2", "X")
                          ->AsIntermediate();

  auto matmul2_op =
      pattern->NewNode(matmul2_op_repr())->assert_is_op("matmul_v2");
  auto matmul2_out = pattern->NewNode(matmul2_out_repr())
                         ->assert_is_op_output("matmul_v2", "Out")
                         ->assert_is_op_input("transpose2", "X")
                         ->AsIntermediate();

  auto transpose3_op =
      pattern->NewNode(transpose3_op_repr())->assert_is_op("transpose2");
  auto transpose3_out = pattern->NewNode(transpose3_out_repr())
                            ->assert_is_op_output("transpose2", "Out")
                            ->assert_is_op_input("reshape2", "X")
                            ->AsIntermediate();

  auto reshape2_op =
      pattern->NewNode(reshape2_op_repr())->assert_is_op("reshape2");
  auto reshape2_out = pattern->NewNode(reshape2_out_repr())
                          ->assert_is_op_output("reshape2", "Out")
                          ->AsOutput();

  matmul0_op->LinksFrom({in, matmul0_in_y});
  matmul0_out->LinksFrom({matmul0_op});

  elementwise0_op->LinksFrom({matmul0_out, elementwise0_in_y});
  elementwise0_out->LinksFrom({elementwise0_op});

  reshape1_op->LinksFrom({elementwise0_out});
  reshape1_out->LinksFrom({reshape1_op});

  transpose1_op->LinksFrom({reshape1_out});
  transpose1_out->LinksFrom({transpose1_op});

  slice1_op->LinksFrom({transpose1_out});
  slice1_out->LinksFrom({slice1_op});

  slice2_op->LinksFrom({transpose1_out});
  slice2_out->LinksFrom({slice2_op});

  slice3_op->LinksFrom({transpose1_out});
  slice3_out->LinksFrom({slice3_op});

  transpose2_op->LinksFrom({slice3_out});
  transpose2_out->LinksFrom({transpose2_op});

  matmul1_op->LinksFrom({slice2_out, transpose2_out});
  matmul1_out->LinksFrom({matmul1_op});

  scale1_op->LinksFrom({matmul1_out});
  scale1_out->LinksFrom({scale1_op});

  softmax1_op->LinksFrom({scale1_out});
  softmax1_out->LinksFrom({softmax1_op});

  matmul2_op->LinksFrom({slice1_out, softmax1_out});
  matmul2_out->LinksFrom({matmul2_op});

  transpose3_op->LinksFrom({matmul2_out});
  transpose3_out->LinksFrom({transpose3_op});

  reshape2_op->LinksFrom({transpose3_out});
  reshape2_out->LinksFrom({reshape2_op});

  return reshape2_out;
}

2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
PDNode *patterns::ConvElementwiseadd2Act::operator()(PDNode *conv_in) {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto conv_filter = pattern->NewNode(conv_filter_repr())
                         ->assert_is_op_input("conv2d", "Filter")
                         ->AsInput();
  auto conv_out = pattern->NewNode(conv_out_repr())
                      ->assert_is_op_output("conv2d")
                      ->assert_is_op_input("elementwise_add", "X")
                      ->AsIntermediate();
  auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
                                ->assert_is_op("elementwise_add");
  auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
2494
                                  ->assert_is_persistable_var()
2495 2496 2497 2498
                                  ->assert_is_op_input("elementwise_add", "Y")
                                  ->AsInput();
  auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
                                 ->assert_is_op_output("elementwise_add")
H
hjchen2 已提交
2499
                                 ->assert_is_op_input("elementwise_add", "Y")
2500 2501 2502 2503 2504
                                 ->AsIntermediate();

  auto elementwise_add_op_1 = pattern->NewNode(elementwise_add_op_1_repr())
                                  ->assert_is_op("elementwise_add");
  auto elementwise_add_in_y_1 = pattern->NewNode(elementwise_add_in_y_1_repr())
H
hjchen2 已提交
2505
                                    ->assert_is_op_input("elementwise_add", "X")
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
                                    ->AsInput();
  auto elementwise_add_out_1 = pattern->NewNode(elementwise_add_out_1_repr())
                                   ->assert_is_op_output("elementwise_add")
                                   ->AsIntermediate();

  auto act_op = pattern->NewNode(act_op_repr())
                    ->assert_is_op()
                    ->assert_more([&](Node *node) {
                      auto op_type = node->Name();
                      return conv_act_set.count(op_type);
                    });
  auto act_out = pattern->NewNode(act_out_repr())
                     ->assert_is_var()
                     // is activation op's output.
                     ->assert_more([&](Node *node) {
                       for (auto *in_op : node->inputs) {
                         if (conv_act_set.count(in_op->Name())) {
                           return true;
                         }
                       }
                       return false;
                     })
                     ->AsOutput();

  conv_op->LinksFrom({conv_in, conv_filter}).LinksTo({conv_out});
  elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
      .LinksTo({elementwise_add_out});
H
hjchen2 已提交
2533 2534
  elementwise_add_op_1->LinksFrom({elementwise_add_out, elementwise_add_in_y_1})
      .LinksTo({elementwise_add_out_1});
2535 2536 2537 2538
  act_op->LinksFrom({elementwise_add_out_1}).LinksTo({act_out});
  return act_out;
}

N
nhzlx 已提交
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
PDNode *patterns::ConvElementwiseadd::operator()(PDNode *conv_in) {
  conv_in->AsInput();
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto conv_out = pattern->NewNode(conv_out_repr())
                      ->assert_is_op_output("conv2d")
                      ->assert_is_op_input("elementwise_add", "X")
                      ->AsIntermediate();
  auto conv_filter = pattern->NewNode(conv_filter_repr())
                         ->assert_is_op_input("conv2d", "Filter")
                         ->AsInput();
  auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
                                ->assert_is_op("elementwise_add");
  auto elementwise_add_in_y = pattern->NewNode(elementwise_add_in_y_repr())
2552
                                  ->assert_is_persistable_var()
N
nhzlx 已提交
2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
                                  ->assert_is_op_input("elementwise_add", "Y")
                                  ->AsInput();
  auto elementwise_add_out = pattern->NewNode(elementwise_add_out_repr())
                                 ->assert_is_op_output("elementwise_add")
                                 ->AsOutput();

  conv_op->LinksFrom({conv_in, conv_filter});
  conv_out->LinksFrom({conv_op});
  elementwise_add_op->LinksFrom({conv_out, elementwise_add_in_y})
      .LinksTo({elementwise_add_out});

  return elementwise_add_out;
}

N
nhzlx 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
PDNode *patterns::ConvAffineChannel::operator()(
    paddle::framework::ir::PDNode *conv_input, bool with_eltwise_add) {
  // Create Operators
  conv_input->assert_is_op_input("conv2d", "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op("conv2d");

  PDNode *eltwise_op = nullptr;
  if (with_eltwise_add) {
    eltwise_op =
        pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
  }

  auto *affine_channel_op =
      pattern->NewNode(affine_channel_repr())->assert_is_op("affine_channel");
  // Create variables
  // Conv Filter
  auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
                              ->assert_is_op_input("conv2d", "Filter");

  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
                           ->assert_is_only_output_of_op("conv2d");

  PDNode *eltwise_y_in_var = nullptr;
  PDNode *eltwise_out_var = nullptr;
  if (with_eltwise_add) {
    // Conv output as Bias input
    conv_out_var->assert_is_op_input("elementwise_add", "X");
    // Bias
    eltwise_y_in_var = pattern->NewNode(eltwise_y_in_repr())
                           ->assert_is_op_input("elementwise_add", "Y")
                           ->AsInput();
    eltwise_out_var = pattern->NewNode(eltwise_out_repr())
                          ->AsIntermediate()
                          ->assert_is_only_output_of_op("elementwise_add");
  } else {
    // Conv output as AffineChannel input
    conv_out_var->assert_is_op_input("affine_channel", "X");
  }

  // AC Scale
  auto *ac_scale_var = pattern->NewNode(ac_scale_repr())
                           ->AsInput()
                           ->assert_is_persistable_var()
2613
                           ->assert_has_n_outputs(1)
N
nhzlx 已提交
2614 2615 2616 2617 2618
                           ->assert_is_op_input("affine_channel", "Scale");
  // AC Bias
  auto *ac_bias_var = pattern->NewNode(ac_bias_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
2619
                          ->assert_has_n_outputs(1)
N
nhzlx 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
                          ->assert_is_op_input("affine_channel", "Bias");

  // AC output
  auto *ac_out_var = pattern->NewNode(ac_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("affine_channel");

  conv_op->LinksFrom({conv_input, conv_weight_var}).LinksTo({conv_out_var});

  if (with_eltwise_add) {
    eltwise_op->LinksFrom({conv_out_var, eltwise_y_in_var})
        .LinksTo({eltwise_out_var});
    affine_channel_op->LinksFrom({eltwise_out_var, ac_scale_var, ac_bias_var})
        .LinksTo({ac_out_var});
  } else {
    affine_channel_op->LinksFrom({conv_out_var, ac_scale_var, ac_bias_var})
        .LinksTo({ac_out_var});
  }
  return ac_out_var;
}

2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
PDNode *patterns::DequantQuantAny::operator()() {
  auto *dequant_in = pattern->NewNode(dequant_in_repr())
                         ->AsInput()
                         ->assert_is_op_input("dequantize", "Input");

  auto *dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");

  auto *dequant_out = pattern->NewNode(dequant_out_repr())
                          ->AsOutput()
                          ->assert_is_op_output("dequantize", "Output");

  auto *quant_op = pattern->NewNode(quant_op_repr())
                       ->assert_is_op("quantize")
                       ->AsIntermediate();

  auto *quant_out = pattern->NewNode(quant_out_repr())
                        ->AsOutput()
                        ->assert_is_op_output("quantize");

  auto *next_op = pattern->NewNode(next_op_repr())->assert_is_op();

  dequant_op->LinksFrom({dequant_in}).LinksTo({dequant_out});
  quant_op->LinksFrom({dequant_out}).LinksTo({quant_out});
  next_op->LinksFrom({quant_out});

  return quant_out;
}

PDNode *patterns::DequantAny::operator()() {
  auto *dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");

  auto *dequant_out = pattern->NewNode(dequant_out_repr())
                          ->AsOutput()
                          ->assert_is_op_output("dequantize", "Output");

  auto *next_op = pattern->NewNode(next_op_repr())->assert_is_op();

  dequant_op->LinksTo({dequant_out});
  next_op->LinksFrom({dequant_out});

  return dequant_out;
}

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
PDNode *patterns::MultipleQuantize::operator()() {
  auto *prev_out = pattern->NewNode(prev_out_repr())->AsOutput();

  // find nodes that are inputs to quantize operators
  prev_out->assert_more([&](Node *node) {
    int counter = std::count_if(
        node->outputs.begin(), node->outputs.end(), [&](Node const *iter) {
          return iter && iter->IsOp() && iter->Op()->Type() == "quantize";
        });
    return (counter > 1);
  });

  return prev_out;
}

2701 2702
PDNode *patterns::QuantizePlacement::operator()(
    const std::unordered_set<std::string> &quantize_enabled_op_types) {
2703 2704
  auto *op =
      pattern->NewNode(op_repr())->assert_is_ops(quantize_enabled_op_types);
2705 2706 2707
  return op;
}

2708 2709
PDNode *patterns::Bfloat16Placement::operator()(
    const std::unordered_set<std::string> &bfloat16_enabled_op_types) {
J
Jacek Czaja 已提交
2710
  std::unordered_set<std::string> supported_op_types =
J
jakpiase 已提交
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
      std::unordered_set<std::string>({"cast",
                                       "clip",
                                       "concat",
                                       "conv2d",
                                       "conv2d_transpose",
                                       "elementwise_add",
                                       "elementwise_mul",
                                       "expand_v2",
                                       "fc",
                                       "fusion_gru",
                                       "fusion_lstm",
                                       "gelu",
                                       "layer_norm",
                                       "matmul",
                                       "matmul_v2",
                                       "pool2d",
                                       "prelu",
                                       "relu",
                                       "reshape2",
                                       "scale",
                                       "sigmoid",
                                       "slice",
                                       "softmax",
                                       "split",
                                       "squeeze",
                                       "squeeze2",
                                       "sum",
                                       "transpose2"});
2739 2740 2741
  if (!bfloat16_enabled_op_types.empty()) {
    supported_op_types = bfloat16_enabled_op_types;
  }
2742
  auto *op_in = pattern->NewNode(op_in_repr())->AsInput();
2743
  auto *op = pattern->NewNode(op_repr())->assert_is_ops(supported_op_types);
2744 2745 2746 2747
  op->assert_more([&](Node *node) {
    return node->Op()->GetAttrIfExists<bool>("use_mkldnn") ||
           node->Op()->Type() == "reshape2";
  });
2748
  op->LinksFrom({op_in});
2749 2750 2751 2752 2753 2754
  return op;
}

PDNode *patterns::OrphanedBfloat16::operator()() {
  auto *prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();
  prev_op->assert_more([&](Node *node) {
2755 2756 2757 2758
    bool data_type_is_missing = !node->Op()->HasAttr("mkldnn_data_type");
    bool data_type_is_fp32 = node->Op()->GetAttrIfExists<std::string>(
                                 "mkldnn_data_type") == "float32";
    return data_type_is_missing || data_type_is_fp32;
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
  });
  auto *prev_out = pattern->NewNode(prev_out_repr())->AsOutput();

  auto *op = pattern->NewNode(op_repr())->assert_is_op();
  op->assert_more([&](Node *node) {
    return node->Op()->GetAttrIfExists<std::string>("mkldnn_data_type") ==
           "bfloat16";
  });
  auto *op_out = pattern->NewNode(op_out_repr())->AsOutput();

  auto *next_op = pattern->NewNode(next_op_repr())->assert_is_op();
  next_op->assert_more([&](Node *node) {
2771 2772 2773 2774
    bool data_type_is_missing = !node->Op()->HasAttr("mkldnn_data_type");
    bool data_type_is_fp32 = node->Op()->GetAttrIfExists<std::string>(
                                 "mkldnn_data_type") == "float32";
    return data_type_is_missing || data_type_is_fp32;
2775 2776 2777 2778 2779 2780 2781 2782
  });

  prev_op->LinksTo({prev_out});
  op->LinksFrom({prev_out}).LinksTo({op_out});
  next_op->LinksFrom({op_out});
  return next_op;
}

W
wenbin 已提交
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
PDNode *patterns::UnsupportedBfloat16::operator()() {
  auto *prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();
  prev_op->assert_more([&](Node *node) {
    return node->Op()->HasAttr("mkldnn_data_type") == false;
  });
  auto *prev_out = pattern->NewNode(prev_out_repr())->AsOutput();

  auto *op = pattern->NewNode(op_repr())->assert_is_op();
  op->assert_more([&](Node *node) {
    return node->Op()->GetAttrIfExists<std::string>("mkldnn_data_type") ==
           "bfloat16";
  });
  prev_op->LinksTo({prev_out});
  op->LinksFrom({prev_out});
  return op;
}

T
Tomasz Socha 已提交
2800 2801
PDNode *patterns::Bloat16Ops::operator()() {
  auto op = pattern->NewNode(op_repr())->assert_is_op();
2802 2803 2804 2805 2806 2807 2808
  op->assert_more([&](Node *node) {
    return node->Op()->GetAttrIfExists<std::string>("mkldnn_data_type") ==
           "bfloat16";
  });
  return op;
}

2809
PDNode *patterns::MKLDNNInPlace::operator()() {
2810
  const std::unordered_set<std::string> &supported_op_types = {
2811
      "abs", "gelu", "leaky_relu", "relu", "softmax", "sqrt", "swish", "tanh"};
2812 2813 2814

  auto possible_inplace_op = pattern->NewNode(inplace_to_be_op_repr())
                                 ->assert_is_ops(supported_op_types);
2815 2816

  auto input = pattern->NewNode(inplace_to_be_op_in_repr())
2817
                   ->assert_is_ops_input(supported_op_types)
2818 2819
                   ->AsInput();
  auto output = pattern->NewNode(inplace_to_be_op_out_repr())
2820
                    ->assert_is_ops_output(supported_op_types)
2821
                    ->AsOutput();
2822 2823

  auto next_op = pattern->NewNode(next_op_repr())->assert_is_op();
2824
  auto next_output = pattern->NewNode(next_op_out_repr())->AsOutput();
2825 2826 2827 2828

  // Check if op is MKL-DNN enabled
  possible_inplace_op->assert_op_attr("use_mkldnn", true);

2829
  // linked structure
2830 2831 2832
  possible_inplace_op->LinksTo({output});
  possible_inplace_op->LinksFrom({input});
  next_op->LinksFrom({output});
2833
  next_op->LinksTo({next_output});
2834 2835 2836 2837

  return possible_inplace_op;
}

2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
// a -> transpose_op(1) -> transpose_out_a -> flatten_op(1) -> flatten_out_a
// b -> transpose_op(2) -> transpose_out_b -> flatten_op(2) -> flatten_out_b
// ...
// z -> transpose_op(n) -> transpose_out_z -> flatten_op(n) -> flatten_out_z
// flatten_out_a -> concat_op  flatten_out_b -> concat_op ... flatten_out_z ->
// concat_op
PDNode *patterns::TransposeFlattenConcat::operator()(
    std::vector<PDNode *> conv_in, int times) {
  // The times represents the repeat times of the
  // {trans, trans_out, flatten, flatten_out}
  const int kNumFields = 4;
  const int kTransOutOffset = 1;
  const int kFlattenOffset = 2;
  const int kFlattenOutOffset = 3;

  std::vector<PDNode *> nodes;

  for (int i = 0; i < times; i++) {
    nodes.push_back(
        pattern->NewNode(GetNodeName("transpose" + std::to_string(i)))
            ->assert_is_op("transpose2"));
    nodes.push_back(
        pattern->NewNode(GetNodeName("transpose_out" + std::to_string(i)))
            ->assert_is_op_output("transpose2")
            ->assert_is_op_input("flatten2", "X")
            ->AsIntermediate());
    nodes.push_back(pattern->NewNode(GetNodeName("flatten" + std::to_string(i)))
                        ->assert_is_op("flatten2"));

    nodes.push_back(
        pattern->NewNode(GetNodeName("flatten_out" + std::to_string(i)))
            ->assert_is_op_output("flatten2")
            ->assert_is_op_nth_input("concat", "X", i)
            ->AsIntermediate());
  }

  auto concat_op = pattern->NewNode(GetNodeName("concat"))
                       ->assert_is_op("concat")
                       ->assert_op_has_n_inputs("concat", times);
  auto concat_out = pattern->NewNode(GetNodeName("concat_out"))
                        ->assert_is_op_output("concat")
                        ->AsOutput();

  std::vector<PDNode *> flatten_outs;
  for (int i = 0; i < times; i++) {
    conv_in[i]->AsInput();
    // trans
    nodes[i * kNumFields]->LinksFrom({conv_in[i]});
    // trans_out
    nodes[i * kNumFields + kTransOutOffset]->LinksFrom({nodes[i * kNumFields]});
    // flatten
    nodes[i * kNumFields + kFlattenOffset]->LinksFrom(
        {nodes[i * kNumFields + kTransOutOffset]});
    // flatten_out
    nodes[i * kNumFields + kFlattenOutOffset]->LinksFrom(
        {nodes[i * kNumFields + kFlattenOffset]});
    flatten_outs.push_back(nodes[i * kNumFields + kFlattenOutOffset]);
  }

  concat_op->LinksFrom(flatten_outs).LinksTo({concat_out});
  return concat_out;
}

D
denglin-github 已提交
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
void patterns::DeleteDropoutOpPattern::operator()() {
  auto any_op_out = pattern->NewNode(any_op_out_repr())
                        ->assert_is_op_input("dropout", "X")
                        ->AsInput();

  auto dropout_op =
      pattern->NewNode(dropout_op_repr())->assert_is_op("dropout");

  auto dropout_op_out = pattern->NewNode(dropout_op_out_repr())
                            ->assert_is_op_output("dropout", "Out")
                            ->AsIntermediate();

  auto dropout_op_outmask = pattern->NewNode(dropout_op_outmask_repr())
                                ->assert_is_op_output("dropout", "Mask")
                                ->AsOutput();
  auto any_op2 = pattern->NewNode(any_op2_repr())->assert_is_op()->AsOutput();

  dropout_op->LinksFrom({any_op_out});
  dropout_op_out->LinksFrom({dropout_op});
  dropout_op_outmask->LinksFrom({dropout_op});
  any_op2->LinksFrom({dropout_op_out});
}

2924 2925 2926
void patterns::DeleteQuantOpFuse::operator()(PDNode *input_act_node,
                                             const std::string &quant_type) {
  auto *input_scale_node = pattern->NewNode(GetNodeName("input_scale_node"))
2927 2928
                               ->assert_is_op_input(quant_type, "InScale")
                               ->AsInput();
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
  auto *quant_node =
      pattern->NewNode(GetNodeName("quant_node"))->assert_is_op(quant_type);
  auto *output_scale_node = pattern->NewNode(GetNodeName("output_scale_node"))
                                ->assert_is_op_output(quant_type, "OutScale")
                                ->AsOutput();
  auto *output_act_node = pattern->NewNode(GetNodeName("output_act_node"))
                              ->assert_is_op_output(quant_type, "Out")
                              ->AsOutput();
  quant_node->LinksFrom({input_scale_node, input_act_node});
  output_scale_node->LinksFrom({quant_node});
  output_act_node->LinksFrom({quant_node});
}

void patterns::DequantOpFuse::operator()(PDNode *quantized_op_input,
                                         const std::string &quantized_op_type,
                                         const std::string &dequant_type,
                                         const std::string &weight_name) {
  auto *quantized_op_weight =
      pattern->NewNode(GetNodeName("quantized_op_weight"))
          ->assert_is_op_input(quantized_op_type, weight_name)
          ->AsInput();
  auto *quantized_op = pattern->NewNode(GetNodeName("quantized_op"))
                           ->assert_is_op(quantized_op_type);
  auto *quantized_op_out = pattern->NewNode(GetNodeName("quantized_op_out"))
                               ->assert_is_op_output(quantized_op_type)
                               ->assert_is_op_input(dequant_type, "X");
  auto *dequant_op =
      pattern->NewNode(GetNodeName("dequant_op"))->assert_is_op(dequant_type);
  auto *dequant_op_out = pattern->NewNode(GetNodeName("dequant_op_out"))
                             ->assert_is_op_output(dequant_type, "Out")
                             ->AsOutput();
  PDNode *dequant_channel_scale = nullptr;
2961
  if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
2962 2963 2964 2965
    dequant_channel_scale =
        pattern->NewNode(GetNodeName("dequant_channel_scale"))
            ->assert_is_op_nth_input(dequant_type, "Scales", 0)
            ->AsInput();
N
nhzlx 已提交
2966
  }
2967 2968
  quantized_op->LinksFrom({quantized_op_input, quantized_op_weight});
  quantized_op_out->LinksFrom({quantized_op});
N
nhzlx 已提交
2969

2970 2971 2972 2973
  if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
    dequant_op->LinksFrom({quantized_op_out, dequant_channel_scale});
  } else {
    dequant_op->LinksFrom({quantized_op_out});
N
nhzlx 已提交
2974
  }
2975
  dequant_op_out->LinksFrom({dequant_op});
N
nhzlx 已提交
2976 2977
}

2978 2979 2980
void patterns::ShuffleChannelPattern::operator()(PDNode *reshape1_in) {
  auto reshape1_op =
      pattern->NewNode(reshape1_op_repr())->assert_is_op("reshape2");
2981
  reshape1_op->assert_more([&](Node *x) {
R
Ruibiao Chen 已提交
2982
    return PADDLE_GET_CONST(std::vector<int>, x->Op()->GetAttr("shape"))
2983
               .size() == 5;
2984
  });
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012

  auto reshape1_out = pattern->NewNode(reshape1_out_repr())
                          ->assert_is_op_output("reshape2", "Out")
                          ->assert_is_op_input("transpose2")
                          ->AsIntermediate();

  auto transpose_op =
      pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");

  auto transpose_out = pattern->NewNode(transpose_out_repr())
                           ->assert_is_op_output("transpose2", "Out")
                           ->assert_is_op_input("reshape2")
                           ->AsIntermediate();

  auto reshape2_op =
      pattern->NewNode(reshape2_op_repr())->assert_is_op("reshape2");
  auto reshape2_out = pattern->NewNode(reshape2_out_repr())
                          ->assert_is_op_output("reshape2", "Out")
                          ->AsOutput();

  reshape1_op->LinksFrom({reshape1_in});
  reshape1_out->LinksFrom({reshape1_op});
  transpose_op->LinksFrom({reshape1_out});
  transpose_out->LinksFrom({transpose_op});
  reshape2_op->LinksFrom({transpose_out});
  reshape2_out->LinksFrom({reshape2_op});
}

3013 3014
void patterns::DeleteQuantDequantOpPattern::operator()(
    PDNode *input_node, const std::string &quantdequant_types) {
3015 3016
  auto quant_dequant_op_inscale =
      pattern->NewNode(quant_dequant_op_inscale_repr())
3017
          ->assert_is_op_input(quantdequant_types, "InScale")
3018
          ->AsInput();
3019 3020
  auto quant_dequant_op = pattern->NewNode(quant_dequant_op_repr())
                              ->assert_is_op(quantdequant_types);
3021

3022
  auto quant_dequant_op_out =
3023
      pattern->NewNode(quant_dequant_op_out_repr())
3024 3025
          ->assert_is_op_output(quantdequant_types, "Out")
          ->AsOutput();
3026 3027 3028

  auto quant_dequant_op_outscale =
      pattern->NewNode(quant_dequant_op_outscale_repr())
3029
          ->assert_is_op_output(quantdequant_types, "OutScale")
3030 3031
          ->AsOutput();

3032
  quant_dequant_op->LinksFrom({quant_dequant_op_inscale, input_node});
3033
  quant_dequant_op_outscale->LinksFrom({quant_dequant_op});
3034
  quant_dequant_op_out->LinksFrom({quant_dequant_op});
3035 3036
}

3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
void patterns::DeleteQuantDequantFilterOpPattern::operator()() {
  auto quant_dequant_op_x =
      pattern->NewNode(quant_dequant_op_x_repr())
          ->assert_is_ops_input(
              {"fake_channel_wise_quantize_dequantize_abs_max",
               "fake_quantize_dequantize_abs_max"},
              "X")
          ->AsInput();

  auto quant_dequant_op =
      pattern->NewNode(quant_dequant_op_repr())
          ->assert_is_ops({"fake_channel_wise_quantize_dequantize_abs_max",
                           "fake_quantize_dequantize_abs_max"});

  auto quant_dequant_out =
      pattern->NewNode(quant_dequant_op_out_repr())
          ->assert_is_ops_output(
              {"fake_channel_wise_quantize_dequantize_abs_max",
               "fake_quantize_dequantize_abs_max"},
              "Out")
          ->AsIntermediate();

  auto quant_dequant_op_outscale =
      pattern->NewNode(quant_dequant_op_outscale_repr())
          ->assert_is_ops_output(
              {"fake_channel_wise_quantize_dequantize_abs_max",
               "fake_quantize_dequantize_abs_max"},
              "OutScale")
          ->AsOutput();
  auto any_op2 = pattern->NewNode(any_op2_repr())->assert_is_op()->AsOutput();

  quant_dequant_op->LinksFrom({quant_dequant_op_x});
  quant_dequant_op_outscale->LinksFrom({quant_dequant_op});
  quant_dequant_out->LinksFrom({quant_dequant_op});
  any_op2->LinksFrom({quant_dequant_out});
}

3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139
void patterns::DeleteWeightQuantDequantLinearOpPattern::operator()() {
  auto weight_dequantize_linear_op_x =
      pattern->NewNode(weight_dequantize_linear_op_x_repr())
          ->AsInput()
          ->assert_is_op_input("dequantize_linear", "X")
          ->assert_is_persistable_var();

  auto weight_dequantize_linear_op_scale =
      pattern->NewNode(weight_dequantize_linear_op_scale_repr())
          ->AsInput()
          ->assert_is_op_input("dequantize_linear", "Scale")
          ->assert_is_persistable_var();

  auto weight_dequantize_linear_op =
      pattern->NewNode(weight_dequantize_linear_op_repr())
          ->assert_is_op("dequantize_linear");

  auto weight_dequantize_linear_op_out =
      pattern->NewNode(weight_dequantize_linear_op_out_repr())
          ->AsIntermediate()
          ->assert_is_op_output("dequantize_linear", "Y");

  auto any_op2 = pattern->NewNode(any_op2_repr())->assert_is_op()->AsOutput();

  weight_dequantize_linear_op
      ->LinksFrom(
          {weight_dequantize_linear_op_x, weight_dequantize_linear_op_scale})
      .LinksTo({weight_dequantize_linear_op_out});
  any_op2->LinksFrom({weight_dequantize_linear_op_out});
}

void patterns::DeleteQuantDequantLinearOpPattern::operator()() {
  auto quantize_linear_op_x = pattern->NewNode(quantize_linear_op_x_repr())
                                  ->AsInput()
                                  ->assert_is_op_input("quantize_linear", "X");

  auto quantize_linear_op_scale =
      pattern->NewNode(quantize_linear_op_scale_repr())
          ->AsInput()
          ->assert_is_op_input("quantize_linear", "Scale")
          ->assert_is_persistable_var();

  auto quantize_linear_op = pattern->NewNode(quantize_linear_op_repr())
                                ->assert_is_op("quantize_linear");

  auto quantize_linear_op_out =
      pattern->NewNode(quantize_linear_op_out_repr())
          ->AsIntermediate()
          ->assert_is_op_output("quantize_linear", "Y")
          ->assert_is_op_input("dequantize_linear", "X")
          ->assert_var_not_persistable();

  // Can not add this node. Todo: Wangzheee
  /*
    auto dequantize_linear_op_scale =
        pattern->NewNode(dequantize_linear_op_scale_repr())
            ->assert_is_op_input("dequantize_linear", "Scale")
            ->AsIntermediate();
  */

  auto dequantize_linear_op = pattern->NewNode(dequantize_linear_op_repr())
                                  ->assert_is_op("dequantize_linear");

  auto dequantize_linear_op_out =
      pattern->NewNode(dequantize_linear_op_out_repr())
          ->AsIntermediate()
W
Wangzheee 已提交
3140 3141
          ->assert_is_op_output("dequantize_linear", "Y")
          ->AsOutput();
3142 3143 3144 3145 3146 3147 3148 3149

  quantize_linear_op
      ->LinksFrom({quantize_linear_op_x, quantize_linear_op_scale})
      .LinksTo({quantize_linear_op_out});
  dequantize_linear_op->LinksFrom({quantize_linear_op_out})
      .LinksTo({dequantize_linear_op_out});
}

3150
PDNode *patterns::ReshapeTransposeMatmulPattern::operator()(
3151 3152
    const std::string &op_name,
    bool with_reshape_xshape,
3153
    bool with_transpose_xshape) {
3154 3155 3156 3157
  auto reshape_op =
      pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");
  auto transpose_op =
      pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
3158
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op(op_name);
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178

  auto reshape_in = pattern->NewNode(reshape_in_repr())
                        ->AsInput()
                        ->assert_is_op_input("reshape2", "X");

  auto reshape_out = pattern->NewNode(reshape_out_repr())
                         ->AsIntermediate()
                         ->assert_is_op_input("transpose2", "X")
                         ->assert_is_op_output("reshape2", "Out");
  if (!with_reshape_xshape)
    reshape_out->assert_is_only_output_of_op("reshape2");

  auto reshape_xshape = with_reshape_xshape
                            ? pattern->NewNode(reshape_xshape_repr())
                                  ->AsIntermediate()
                                  ->assert_is_op_output("reshape2", "XShape")
                            : nullptr;

  auto transpose_out = pattern->NewNode(transpose_out_repr())
                           ->AsIntermediate()
3179
                           ->assert_is_op_input(op_name)
3180 3181 3182 3183 3184
                           ->assert_is_op_output("transpose2", "Out");
  if (!with_transpose_xshape)
    transpose_out->assert_is_only_output_of_op("transpose2");

  auto transpose_xshape =
3185 3186 3187 3188
      with_transpose_xshape ? pattern->NewNode(transpose_xshape_repr())
                                  ->AsIntermediate()
                                  ->assert_is_op_output("transpose2", "XShape")
                            : nullptr;
3189 3190 3191

  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsOutput()
3192
                        ->assert_is_op_output(op_name, "Out");
3193 3194 3195 3196 3197 3198 3199 3200 3201

  reshape_op->LinksFrom({reshape_in}).LinksTo({reshape_out});
  if (with_reshape_xshape) reshape_op->LinksTo({reshape_xshape});
  transpose_op->LinksFrom({reshape_out}).LinksTo({transpose_out});
  if (with_transpose_xshape) transpose_op->LinksTo({transpose_xshape});
  matmul_op->LinksFrom({transpose_out}).LinksTo({matmul_out});
  return matmul_out;
}

3202 3203 3204
// shared function for matmul and matmul_v2
PDNode *patterns::MatmulTransposeReshapePattern::operator()(
    const std::string &op_name) {
3205 3206 3207 3208
  auto reshape_op =
      pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");
  auto transpose_op =
      pattern->NewNode(transpose_op_repr())->assert_is_op("transpose2");
3209
  auto matmul_op = pattern->NewNode(matmul_op_repr())->assert_is_op(op_name);
3210 3211 3212

  auto matmul_out = pattern->NewNode(matmul_out_repr())
                        ->AsInput()
3213
                        ->assert_is_op_output(op_name, "Out")
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
                        ->assert_is_op_input("transpose2", "X");

  auto transpose_out = pattern->NewNode(transpose_out_repr())
                           ->AsIntermediate()
                           ->assert_is_op_output("transpose2", "Out")
                           ->assert_is_op_input("reshape2", "X");

  auto transpose_out_xshape = pattern->NewNode(transpose_out_xshape_repr())
                                  ->AsIntermediate()
                                  ->assert_is_op_output("transpose2", "XShape");

  auto reshape_out = pattern->NewNode(reshape_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("reshape2");

  auto reshape_out_xshape = pattern->NewNode(reshape_out_xshape_repr())
                                ->AsIntermediate()
                                ->assert_is_op_output("reshape2", "XShape");

  matmul_op->LinksTo({matmul_out});
  transpose_op->LinksTo({transpose_out_xshape});
  reshape_op->LinksTo({reshape_out_xshape});
  transpose_op->LinksFrom({matmul_out}).LinksTo({transpose_out});
  reshape_op->LinksFrom({transpose_out}).LinksTo({reshape_out});
  return reshape_out;
}

3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
PDNode *patterns::FusionGru::operator()() {
  auto op = pattern->NewNode(op_repr())->assert_is_op("fusion_gru");
  auto x = pattern->NewNode(x_repr())->AsInput()->assert_is_op_input(
      "fusion_gru", "X");
  auto weight_h = pattern->NewNode(weight_h_repr())
                      ->AsInput()
                      ->assert_is_op_input("fusion_gru", "WeightH");
  auto weight_x = pattern->NewNode(weight_x_repr())
                      ->AsInput()
                      ->assert_is_op_input("fusion_gru", "WeightX");
  auto out = pattern->NewNode(out_repr())
                 ->AsOutput()
                 ->assert_is_op_output("fusion_gru", "Hidden");
  op->LinksFrom({x, weight_h, weight_x}).LinksTo({out});
  return out;
}

3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
PDNode *patterns::FusionLSTM::operator()() {
  auto op = pattern->NewNode(op_repr())->assert_is_op("fusion_lstm");
  auto x = pattern->NewNode(x_repr())->AsInput()->assert_is_op_input(
      "fusion_lstm", "X");
  auto weight_h = pattern->NewNode(weight_h_repr())
                      ->AsInput()
                      ->assert_is_op_input("fusion_lstm", "WeightH");
  auto weight_x = pattern->NewNode(weight_x_repr())
                      ->AsInput()
                      ->assert_is_op_input("fusion_lstm", "WeightX");
  auto hidden = pattern->NewNode(hidden_repr())
                    ->AsOutput()
                    ->assert_is_op_output("fusion_lstm", "Hidden");
  auto cell = pattern->NewNode(cell_repr())
                  ->AsOutput()
                  ->assert_is_op_output("fusion_lstm", "Cell");
  op->LinksFrom({x, weight_h, weight_x}).LinksTo({hidden, cell});
  return hidden;
}

3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
PDNode *patterns::TwoFusionGruConcat::operator()() {
  auto x = pattern->NewNode(x_repr())->AsInput()->assert_is_op_input(
      "fusion_gru", "X");
  auto gru1 =
      pattern->NewNode(gru1_repr())
          ->assert_is_op("fusion_gru")
          ->assert_more([&](Node *node) {
            return node->Op()->GetAttrIfExists<bool>("is_reverse") == false;
          });
  auto gru2 =
      pattern->NewNode(gru2_repr())
          ->assert_is_op("fusion_gru")
          ->assert_more([&](Node *node) {
            return node->Op()->GetAttrIfExists<bool>("is_reverse") == true;
          });
  auto wh1 = pattern->NewNode(wh1_repr())
                 ->AsInput()
                 ->assert_is_op_input("fusion_gru", "WeightH");
  auto wh2 = pattern->NewNode(wh2_repr())
                 ->AsInput()
                 ->assert_is_op_input("fusion_gru", "WeightH");
  auto wx1 = pattern->NewNode(wx1_repr())
                 ->AsInput()
                 ->assert_is_op_input("fusion_gru", "WeightX");
  auto wx2 = pattern->NewNode(wx2_repr())
                 ->AsInput()
                 ->assert_is_op_input("fusion_gru", "WeightX");
  auto b1 = pattern->NewNode(b1_repr())->AsInput()->assert_is_op_input(
      "fusion_gru", "Bias");
  auto b2 = pattern->NewNode(b2_repr())->AsInput()->assert_is_op_input(
      "fusion_gru", "Bias");
  auto h1 = pattern->NewNode(h1_repr())
                ->AsOutput()
                ->assert_is_op_output("fusion_gru", "Hidden")
                ->assert_is_op_input("concat")
                ->AsIntermediate();
  auto h2 = pattern->NewNode(h2_repr())
                ->AsOutput()
                ->assert_is_op_output("fusion_gru", "Hidden")
                ->assert_is_op_input("concat")
                ->AsIntermediate();
  auto concat = pattern->NewNode(concat_repr())->assert_is_op("concat");
  auto out = pattern->NewNode(out_repr())
                 ->AsOutput()
                 ->assert_is_op_output("concat", "Out");
  gru1->LinksFrom({x, wh1, wx1, b1}).LinksTo({h1});
  gru2->LinksFrom({x, wh2, wx2, b2}).LinksTo({h2});
  concat->LinksFrom({h1, h2}).LinksTo({out});
  return out;
}

3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
PDNode *patterns::MultiGruSeq::operator()() {
  auto x = pattern->NewNode(x_repr())->AsInput()->assert_is_op_input(
      "multi_gru", "X");
  auto gru1 = pattern->NewNode(gru1_repr())->assert_is_op("multi_gru");
  auto wx11 = pattern->NewNode(wx11_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightX", 0);
  auto wx12 = pattern->NewNode(wx12_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightX", 1);
  auto wh11 = pattern->NewNode(wh11_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightH", 0);
  auto wh12 = pattern->NewNode(wh12_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightH", 1);
  auto b11 = pattern->NewNode(b11_repr())
                 ->AsInput()
                 ->assert_is_op_nth_input("multi_gru", "Bias", 0);
  auto b12 = pattern->NewNode(b12_repr())
                 ->AsInput()
                 ->assert_is_op_nth_input("multi_gru", "Bias", 1);
  auto h1 = pattern->NewNode(h1_repr())
                ->AsOutput()
                ->assert_is_op_output("multi_gru", "Hidden")
                ->assert_is_op_input("multi_gru", "X")
                ->AsIntermediate();
  auto gru2 = pattern->NewNode(gru2_repr())->assert_is_op("multi_gru");
  auto wx21 = pattern->NewNode(wx21_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightX", 0);
  auto wx22 = pattern->NewNode(wx22_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightX", 1);
  auto wh21 = pattern->NewNode(wh21_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightH", 0);
  auto wh22 = pattern->NewNode(wh22_repr())
                  ->AsInput()
                  ->assert_is_op_nth_input("multi_gru", "WeightH", 1);
  auto b21 = pattern->NewNode(b21_repr())
                 ->AsInput()
                 ->assert_is_op_nth_input("multi_gru", "Bias", 0);
  auto b22 = pattern->NewNode(b22_repr())
                 ->AsInput()
                 ->assert_is_op_nth_input("multi_gru", "Bias", 1);
  auto h2 = pattern->NewNode(h2_repr())->AsOutput()->assert_is_op_output(
      "multi_gru", "Hidden");
  gru1->LinksFrom({x, wx11, wx12, wh11, wh12, b11, b12}).LinksTo({h1});
  gru2->LinksFrom({h1, wx21, wx22, wh21, wh22, b21, b22}).LinksTo({h2});
  return h2;
}

3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
PDNode *patterns::MultiGru::operator()() {
  auto x = pattern->NewNode(x_repr())->AsInput()->assert_is_op_input(
      "multi_gru", "X");
  auto gru = pattern->NewNode(gru_repr())->assert_is_op("multi_gru");
  auto wx = pattern->NewNode(wx_repr())->AsInput()->assert_is_op_nth_input(
      "multi_gru", "WeightX", 0);
  auto wh = pattern->NewNode(wh_repr())->AsInput()->assert_is_op_nth_input(
      "multi_gru", "WeightH", 0);
  auto h = pattern->NewNode(h_repr())->AsOutput()->assert_is_op_output(
      "multi_gru", "Hidden");
  gru->LinksFrom({x, wx, wh}).LinksTo({h});
  return h;
}

3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
PDNode *patterns::LayerNorm::operator()() {
  auto *x = pattern->NewNode(x_repr())->AsInput()->assert_is_ops_input(
      {"reduce_mean", "elementwise_sub"});
  auto *x_mean = pattern->NewNode(x_mean_repr())->assert_is_op("reduce_mean");
  auto *x_mean_out = pattern->NewNode(x_mean_out_repr())
                         ->assert_is_op_output("reduce_mean", "Out")
                         ->assert_is_op_input("elementwise_sub", "Y")
                         ->AsIntermediate();
  auto *x_sub_mean =
      pattern->NewNode(x_sub_mean_repr())->assert_is_op("elementwise_sub");
  auto *x_sub_mean_out =
      pattern->NewNode(x_sub_mean_out_repr())
          ->assert_is_op_output("elementwise_sub")
          ->assert_is_ops_input({"elementwise_pow", "elementwise_div"}, "X")
          ->AsIntermediate();
  auto *sqr_pow = pattern->NewNode(sqr_pow_repr())
                      ->assert_is_op_input("elementwise_pow", "Y")
                      ->assert_is_persistable_var()
                      ->AsInput();
  auto *x_sub_mean_sqr =
      pattern->NewNode(x_sub_mean_sqr_repr())->assert_is_op("elementwise_pow");
  auto *x_sub_mean_sqr_out = pattern->NewNode(x_sub_mean_sqr_out_repr())
                                 ->assert_is_op_output("elementwise_pow")
                                 ->assert_is_op_input("reduce_mean")
                                 ->AsIntermediate();
  auto *std_dev = pattern->NewNode(std_dev_repr())->assert_is_op("reduce_mean");
  auto *std_dev_out = pattern->NewNode(std_dev_out_repr())
                          ->assert_is_op_output("reduce_mean")
                          ->assert_is_op_input("elementwise_add")
                          ->AsIntermediate();
  auto *eps = pattern->NewNode(eps_repr())
                  ->assert_is_op_input("elementwise_add", "Y")
                  ->assert_is_persistable_var()
                  ->AsInput();
  auto *std_dev_eps =
      pattern->NewNode(std_dev_eps_repr())->assert_is_op("elementwise_add");
  auto *std_dev_eps_out = pattern->NewNode(std_dev_eps_out_repr())
                              ->assert_is_op_output("elementwise_add")
                              ->assert_is_op_input("sqrt")
                              ->AsIntermediate();
  auto *std_dev_eps_sqrt =
      pattern->NewNode(std_dev_eps_sqrt_repr())->assert_is_op("sqrt");
  auto *std_dev_eps_sqrt_out = pattern->NewNode(std_dev_eps_sqrt_out_repr())
                                   ->assert_is_op_output("sqrt")
                                   ->assert_is_op_input("elementwise_div", "Y")
                                   ->AsIntermediate();
  auto *division =
      pattern->NewNode(division_repr())->assert_is_op("elementwise_div");
  auto *division_out = pattern->NewNode(division_out_repr())
                           ->assert_is_op_output("elementwise_div")
                           ->assert_is_op_input("elementwise_mul")
                           ->AsIntermediate();
  auto *gamma = pattern->NewNode(gamma_repr())
                    ->assert_is_op_input("elementwise_mul", "Y")
                    ->assert_is_persistable_var()
                    ->AsInput();
  auto *scale = pattern->NewNode(scale_repr())->assert_is_op("elementwise_mul");
  auto *scale_out = pattern->NewNode(scale_out_repr())
                        ->assert_is_op_output("elementwise_mul")
                        ->assert_is_op_input("elementwise_add")
                        ->AsIntermediate();
  auto *beta = pattern->NewNode(beta_repr())
                   ->assert_is_op_input("elementwise_add", "Y")
                   ->assert_is_persistable_var()
                   ->AsInput();
  auto *shift = pattern->NewNode(shift_repr())->assert_is_op("elementwise_add");
  auto *shift_out = pattern->NewNode(shift_out_repr())
                        ->assert_is_op_output("elementwise_add")
                        ->AsOutput();

  /*
   *            X
   *           / \
   *          /   reduce_mean "u(x)"
   *          \   /
   *      elementwise_sub     "x - u(x)"
   *      /           \    2
   *      |            \  /
   *      |      elementwise_pow  "(x - u(x))^2"
   *      |             |
   *      |       reduce_mean     "sigma^2 = 1/C*Sum{(x - u(x))^2}"
   *      |             |     eps
   *      |             |     /
   *      |       elementwise_add "sigma^2 + epsilon"
   *      \             |
   *       \           sqrt       "sqrt(sigma^2 + epsilon)"
   *        \          /
   *         \        /
   *       elementwise_div        "lnorm = {x-u(x)}/{sqrt(sigma^2 + epsilon)}"
   *              |
   *       gamma  |
   *          \   |
   *       elementwise_mul        "scale: gamma(C) * lnorm"
   *              |
   *        beta  |
   *          \   |
   *       elementwise_add        "shift: gamma(C) * lnorm + beta(C)"
   */

  x_mean->LinksFrom({x}).LinksTo({x_mean_out});
  x_sub_mean->LinksFrom({x, x_mean_out}).LinksTo({x_sub_mean_out});
  x_sub_mean_sqr->LinksFrom({x_sub_mean_out, sqr_pow})
      .LinksTo({x_sub_mean_sqr_out});
  std_dev->LinksFrom({x_sub_mean_sqr_out}).LinksTo({std_dev_out});
  std_dev_eps->LinksFrom({std_dev_out, eps}).LinksTo({std_dev_eps_out});

  std_dev_eps_sqrt->LinksFrom({std_dev_eps_out})
      .LinksTo({std_dev_eps_sqrt_out});
  division->LinksFrom({x_sub_mean_out, std_dev_eps_sqrt_out})
      .LinksTo({division_out});
  scale->LinksFrom({division_out, gamma}).LinksTo({scale_out});
  shift->LinksFrom({scale_out, beta}).LinksTo({shift_out});

  return shift_out;
}

3512
// Add support int8 flag and out_threshold
3513
PDNode *patterns::AddSupportInt8::operator()() {
3514
  auto quant_op = pattern->NewNode(quant_op_repr())->assert_is_op();
3515
  auto quant_out =
3516 3517 3518 3519
      pattern->NewNode(quant_out_repr())
          ->assert_is_var()
          ->assert_more([&](Node *node) { return node->outputs.size() > 0; })
          ->AsOutput();
3520 3521 3522 3523
  quant_op->LinksTo({quant_out});
  return quant_out;
}

W
wenbin 已提交
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557
PDNode *patterns::LayernormShiftPartitionPattern::operator()() {
  auto layer_norm_op =
      pattern->NewNode(layer_norm_op_repr())
          ->assert_is_op("layer_norm")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("begin_norm_axis") &&
                   (PADDLE_GET_CONST(
                        int, node->Op()->GetAttr("begin_norm_axis")) == 2);
          });
  auto layer_norm_in = pattern->NewNode(layer_norm_in_repr())
                           ->AsInput()
                           ->assert_is_op_input("layer_norm", "X");
  auto layer_norm_bias = pattern->NewNode(layer_norm_bias_repr())
                             ->AsInput()
                             ->assert_is_op_input("layer_norm", "Bias");
  auto layer_norm_scale = pattern->NewNode(layer_norm_scale_repr())
                              ->AsInput()
                              ->assert_is_op_input("layer_norm", "Scale");
  auto layer_norm_out = pattern->NewNode(layer_norm_out_repr())
                            ->AsIntermediate()
                            ->assert_is_op_input("reshape2", "X")
                            ->assert_is_op_output("layer_norm", "Y");
  auto reshape1_op =
      pattern->NewNode(reshape1_op_repr())
          ->assert_is_op("reshape2")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("shape") &&
                   (PADDLE_GET_CONST(std::vector<int>,
                                     node->Op()->GetAttr("shape"))
                        .size() == 4);
          });
  auto reshape1_out = pattern->NewNode(reshape1_out_repr())
                          ->AsIntermediate()
                          ->assert_is_op_output("reshape2", "Out");
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
  PDNode *roll1_op = nullptr;
  PDNode *roll1_out = nullptr;

  if (!with_roll_) {
    reshape1_out->assert_is_op_input("reshape2", "X");
  } else {
    reshape1_out->assert_is_op_input("roll", "X");
    roll1_op = pattern->NewNode(roll1_op_repr())->assert_is_op("roll");
    roll1_out = pattern->NewNode(roll1_out_repr())
                    ->AsIntermediate()
                    ->assert_is_op_output("roll", "Out")
                    ->assert_is_op_input("reshape2", "X");
  }
W
wenbin 已提交
3571 3572 3573 3574 3575 3576 3577 3578 3579
  auto reshape2_op =
      pattern->NewNode(reshape2_op_repr())
          ->assert_is_op("reshape2")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("shape") &&
                   (PADDLE_GET_CONST(std::vector<int>,
                                     node->Op()->GetAttr("shape"))
                        .size() == 6);
          });
3580

W
wenbin 已提交
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
  auto reshape2_out = pattern->NewNode(reshape2_out_repr())
                          ->AsIntermediate()
                          ->assert_is_op_input("transpose2", "X")
                          ->assert_is_op_output("reshape2", "Out");
  auto transpose_op =
      pattern->NewNode(transpose_op_repr())
          ->assert_is_op("transpose2")
          ->assert_more([&](Node *node) {
            if (!node->Op()->HasAttr("axis")) return false;
            std::vector<int> axis =
                PADDLE_GET_CONST(std::vector<int>, node->Op()->GetAttr("axis"));
            if (axis.size() != 6) return false;
            const std::vector<int> axis_cmp{0, 1, 3, 2, 4, 5};
            return std::equal(axis.begin(), axis.end(), axis_cmp.begin());
          });
  auto transpose_out = pattern->NewNode(transpose_out_repr())
                           ->AsIntermediate()
                           ->assert_is_op_input("reshape2", "X")
                           ->assert_is_op_output("transpose2", "Out");
  auto reshape3_op =
      pattern->NewNode(reshape3_op_repr())
          ->assert_is_op("reshape2")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("shape") &&
                   (PADDLE_GET_CONST(std::vector<int>,
                                     node->Op()->GetAttr("shape"))
                        .size() == 4);
          });
  auto reshape3_out = pattern->NewNode(reshape3_out_repr())
                          ->AsIntermediate()
                          ->assert_is_op_input("reshape2", "X")
                          ->assert_is_op_output("reshape2", "Out");
  auto reshape4_op =
      pattern->NewNode(reshape4_op_repr())
          ->assert_is_op("reshape2")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("shape") &&
                   (PADDLE_GET_CONST(std::vector<int>,
                                     node->Op()->GetAttr("shape"))
                        .size() == 3);
          });
  auto reshape4_out = pattern->NewNode(reshape4_out_repr())
                          ->assert_is_op_output("reshape2", "Out")
                          ->AsOutput();

  layer_norm_op->LinksFrom({layer_norm_in, layer_norm_bias, layer_norm_scale})
      .LinksTo({layer_norm_out});
  reshape1_op->LinksFrom({layer_norm_out}).LinksTo({reshape1_out});
3629 3630 3631 3632 3633 3634
  if (!with_roll_) {
    reshape2_op->LinksFrom({reshape1_out}).LinksTo({reshape2_out});
  } else {
    roll1_op->LinksFrom({reshape1_out}).LinksTo({roll1_out});
    reshape2_op->LinksFrom({roll1_out}).LinksTo({reshape2_out});
  }
W
wenbin 已提交
3635 3636 3637 3638 3639 3640 3641
  transpose_op->LinksFrom({reshape2_out}).LinksTo({transpose_out});
  reshape3_op->LinksFrom({transpose_out}).LinksTo({reshape3_out});
  reshape4_op->LinksFrom({reshape3_out}).LinksTo({reshape4_out});

  return reshape4_out;
}

W
Wang Bojun 已提交
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
PDNode *patterns::MergeLayernormPattern::operator()(PDNode *in) {
  in->AsInput();
  auto reshape2_00_op =
      pattern->NewNode(reshape2_00_op_repr())->assert_is_op("reshape2");
  auto reshape2_00_out = pattern->NewNode(reshape2_00_out_repr())
                             ->assert_is_op_output("reshape2", "Out")
                             ->assert_is_op_input("strided_slice", "Input")
                             ->AsIntermediate();
  auto strided_slice_10_op = pattern->NewNode(strided_slice_10_op_repr())
                                 ->assert_is_op("strided_slice");
  auto strided_slice_10_out = pattern->NewNode(strided_slice_10_out_repr())
                                  ->assert_is_op_output("strided_slice", "Out")
                                  ->assert_is_op_nth_input("concat", "X", 0)
                                  ->AsIntermediate();
  auto strided_slice_11_op = pattern->NewNode(strided_slice_11_op_repr())
                                 ->assert_is_op("strided_slice");
  auto strided_slice_11_out = pattern->NewNode(strided_slice_11_out_repr())
                                  ->assert_is_op_output("strided_slice", "Out")
                                  ->assert_is_op_nth_input("concat", "X", 1)
                                  ->AsIntermediate();
  auto strided_slice_12_op = pattern->NewNode(strided_slice_12_op_repr())
                                 ->assert_is_op("strided_slice");
  auto strided_slice_12_out = pattern->NewNode(strided_slice_12_out_repr())
                                  ->assert_is_op_output("strided_slice", "Out")
                                  ->assert_is_op_nth_input("concat", "X", 2)
                                  ->AsIntermediate();
  auto strided_slice_13_op = pattern->NewNode(strided_slice_13_op_repr())
                                 ->assert_is_op("strided_slice");
  auto strided_slice_13_out = pattern->NewNode(strided_slice_13_out_repr())
                                  ->assert_is_op_output("strided_slice", "Out")
                                  ->assert_is_op_nth_input("concat", "X", 3)
                                  ->AsIntermediate();
  auto concat_20_op = pattern->NewNode(concat_20_op_repr())
                          ->assert_is_op("concat")
                          ->assert_has_n_inputs(4);
  auto concat_20_out = pattern->NewNode(concat_20_out_repr())
                           ->assert_is_op_output("concat", "Out")
                           ->assert_is_op_input("reshape2", "X")
                           ->AsIntermediate();
  auto reshape2_30_op =
      pattern->NewNode(reshape2_30_op_repr())->assert_is_op("reshape2");
  auto reshape2_30_out = pattern->NewNode(reshape2_30_out_repr())
                             ->assert_is_op_output("reshape2", "Out")
                             ->assert_is_op_input("layer_norm", "X")
                             ->AsIntermediate();
  auto layernorm_40_op =
      pattern->NewNode(layernorm_40_op_repr())
          ->assert_is_op("layer_norm")
          ->assert_more([&](Node *node) {
            return node->Op()->HasAttr("begin_norm_axis") &&
                   (PADDLE_GET_CONST(
                        int, node->Op()->GetAttr("begin_norm_axis")) == 2);
          });
  auto layernorm_40_in_bias = pattern->NewNode(layernorm_40_in_bias_repr())
                                  ->assert_is_op_input("layer_norm", "Bias")
                                  ->AsInput();
  auto layernorm_40_in_scale = pattern->NewNode(layernorm_40_in_scale_repr())
                                   ->assert_is_op_input("layer_norm", "Scale")
                                   ->AsInput();
  auto layernorm_40_out = pattern->NewNode(layernorm_40_out_repr())
                              ->assert_is_op_output("layer_norm", "Y")
                              ->AsOutput();

  reshape2_00_op->LinksFrom({in});
  reshape2_00_out->LinksFrom({reshape2_00_op});
  strided_slice_10_op->LinksFrom({reshape2_00_out});
  strided_slice_10_out->LinksFrom({strided_slice_10_op});
  strided_slice_11_op->LinksFrom({reshape2_00_out});
  strided_slice_11_out->LinksFrom({strided_slice_11_op});
  strided_slice_12_op->LinksFrom({reshape2_00_out});
  strided_slice_12_out->LinksFrom({strided_slice_12_op});
  strided_slice_13_op->LinksFrom({reshape2_00_out});
  strided_slice_13_out->LinksFrom({strided_slice_13_op});
  concat_20_op->LinksFrom({strided_slice_10_out,
                           strided_slice_11_out,
                           strided_slice_12_out,
                           strided_slice_13_out});
  concat_20_out->LinksFrom({concat_20_op});
  reshape2_30_op->LinksFrom({concat_20_out});
  reshape2_30_out->LinksFrom({reshape2_30_op});
  layernorm_40_op->LinksFrom(
      {reshape2_30_out, layernorm_40_in_bias, layernorm_40_in_scale});
  layernorm_40_out->LinksFrom({layernorm_40_op});
  return layernorm_40_out;
}

3728 3729 3730
}  // namespace ir
}  // namespace framework
}  // namespace paddle