graph_pattern_detector.cc 73.5 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 <algorithm>
Q
Qiao Longfei 已提交
16
#include <array>
17
#include <memory>
18
#include <string>
19 20
#include <unordered_map>
#include <unordered_set>
21 22 23
#include <vector>

#include "paddle/fluid/framework/ir/graph_helper.h"
24
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
25
#include "paddle/fluid/framework/ir/graph_traits.h"
26
#include "paddle/fluid/framework/ir/graph_viz_pass.h"
C
chengduo 已提交
27
#include "paddle/fluid/framework/operator.h"
28
#include "paddle/fluid/platform/enforce.h"
Y
Yan Chunwei 已提交
29
#include "paddle/fluid/string/pretty_log.h"
Y
Yan Chunwei 已提交
30
#include "paddle/fluid/string/printf.h"
31

32 33 34 35
namespace paddle {
namespace framework {
namespace ir {

Y
Yan Chunwei 已提交
36 37 38 39
using string::PrettyLogEndl;
using string::PrettyLog;
using string::Style;

40 41
size_t PDPattern::id_ = 0UL;

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

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

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

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

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

  return it->second;
}

C
chengduo 已提交
79
void PDPattern::AddEdge(PDNode *a, PDNode *b) {
80 81 82 83
  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()));
84 85
  PADDLE_ENFORCE_NE(a, b, 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 97
  auto subgraphs = DetectPatterns();
  UniquePatterns(&subgraphs);
  RemoveOverlappedMatch(&subgraphs);
Y
Yan Chunwei 已提交
98
  ValidateByNodeRole(&subgraphs);
99

Y
Yan Chunwei 已提交
100
  if (subgraphs.empty()) return;
101
  LOG(INFO) << "---  detected " << subgraphs.size() << " subgraphs";
102
  int id = 0;
C
chengduo 已提交
103
  for (auto &g : subgraphs) {
M
minqiyang 已提交
104
    VLOG(3) << "optimizing #" << id++ << " subgraph";
105 106 107 108
    handler(g, graph);
  }
}

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

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

130 131 132
  return !pdnodes2nodes_.empty();
}

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

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

169
struct HitGroup {
C
chengduo 已提交
170
  std::unordered_map<PDNode *, Node *> roles;
171

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

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

 private:
C
chengduo 已提交
188
  std::unordered_set<Node *> nodes_;
189 190 191
};

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

201 202
std::vector<GraphPatternDetector::subgraph_t>
GraphPatternDetector::DetectPatterns() {
203
  // Init empty subgraphs.
204
  std::vector<GraphPatternDetector::subgraph_t> result;
205
  std::vector<HitGroup> init_groups;
206
  std::array<std::vector<HitGroup>, 2> bi_records;
C
chengduo 已提交
207
  auto *first_pnode = pattern_.edges().empty() ? pattern().nodes().front().get()
208
                                               : pattern_.edges().front().first;
209
  if (!pdnodes2nodes_.count(first_pnode)) return result;
C
chengduo 已提交
210
  for (auto *node : pdnodes2nodes_[first_pnode]) {
211 212 213 214 215 216 217 218 219 220
    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 已提交
221
  for (const auto &edge : pattern_.edges()) {
M
minqiyang 已提交
222
    VLOG(4) << "check " << edge.first->name() << " -> " << edge.second->name();
Y
Yan Chunwei 已提交
223
    // TODO(Superjomn) Fix bug here, the groups might be duplicate here.
224 225
    // Each role has two PDNodes, which indicates two roles.
    // Detect two Nodes that can match these two roles and they are connected.
C
chengduo 已提交
226 227
    auto &pre_groups = bi_records[step % 2];
    auto &cur_groups = bi_records[1 - (step++ % 2)];
228
    cur_groups.clear();
229
    if (pre_groups.empty()) break;
230
    // source -> target
C
chengduo 已提交
231 232
    for (Node *source : pdnodes2nodes_[edge.first]) {
      for (Node *target : pdnodes2nodes_[edge.second]) {
M
minqiyang 已提交
233
        VLOG(8) << "check " << source->id() << " -- " << target->id();
234
        // TODO(Superjomn) add some prune strategies.
C
chengduo 已提交
235
        for (const auto &group : pre_groups) {
T
Tao Luo 已提交
236 237 238 239 240 241
          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);
242 243 244 245 246 247 248 249
              new_group.Register(target, edge.second);
              cur_groups.push_back(new_group);
              // TODO(Superjomn) need to unique
            }
          }
        }
      }
    }
M
minqiyang 已提交
250
    VLOG(3) << "step " << step << " get records: " << cur_groups.size();
C
chengduo 已提交
251 252
    for (auto &group : cur_groups) {
      for (auto &item : group.roles) {
M
minqiyang 已提交
253
        VLOG(4) << "node " << item.second->id() << " as " << item.first->name();
Y
Yan Chunwei 已提交
254
      }
M
minqiyang 已提交
255
      VLOG(4) << "=========================================================";
Y
Yan Chunwei 已提交
256
    }
257 258
  }

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

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

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

  std::unordered_set<size_t> set;
Y
Yan Chunwei 已提交
288
  std::hash<std::string> hasher;
C
chengduo 已提交
289
  for (auto &g : *subgraphs) {
Y
Yan Chunwei 已提交
290 291
    // 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 已提交
292
    std::sort(sorted_keys.begin(), sorted_keys.end(), GraphItemLessThan());
Y
Yan Chunwei 已提交
293 294 295
    std::stringstream ss;
    for (auto &item : sorted_keys) {
      ss << item.first << ":" << item.second;
296
    }
Y
Yan Chunwei 已提交
297
    auto key = hasher(ss.str());
298 299 300 301 302 303 304 305
    if (!set.count(key)) {
      result.emplace_back(g);
      set.insert(key);
    }
  }
  *subgraphs = result;
}

306
void GraphPatternDetector::RemoveOverlappedMatch(
C
chengduo 已提交
307
    std::vector<subgraph_t> *subgraphs) {
308
  std::vector<subgraph_t> result;
C
chengduo 已提交
309
  std::unordered_set<Node *> node_set;
310

C
chengduo 已提交
311
  for (const auto &subgraph : *subgraphs) {
312
    bool valid = true;
C
chengduo 已提交
313
    for (auto &item : subgraph) {
Y
Yan Chunwei 已提交
314
      if (item.first->IsIntermediate() && node_set.count(item.second)) {
315 316 317 318 319
        valid = false;
        break;
      }
    }
    if (valid) {
C
chengduo 已提交
320
      for (auto &item : subgraph) {
321 322 323 324 325 326 327 328
        node_set.insert(item.second);
      }
      result.push_back(subgraph);
    }
  }
  *subgraphs = result;
}

329 330 331 332 333
std::string PDPattern::DotString() const {
  using inference::analysis::Dot;
  Dot dot;
  int id = 0;
  // Create Nodes
C
chengduo 已提交
334 335
  std::unordered_map<PDNode *, std::string> node2dot;
  for (const auto &node : nodes()) {
336 337 338 339 340
    std::string node_id = "Node" + std::to_string(id++);
    dot.AddNode(node_id, {}, node->name());
    node2dot[node.get()] = node_id;
  }
  // Create Edges
C
chengduo 已提交
341
  for (const auto &edge : edges()) {
342 343 344 345
    if (!node2dot.count(edge.first) || !node2dot.count(edge.second)) {
      LOG(ERROR) << "no node " << edge.first << " " << edge.second;
      continue;
    }
C
chengduo 已提交
346 347
    auto &src = node2dot.at(edge.first);
    auto &trg = node2dot.at(edge.second);
348 349 350 351 352
    dot.AddEdge(src, trg, {});
  }
  return dot.Build();
}

C
chengduo 已提交
353
PDNode &PDNode::LinksTo(const std::vector<PDNode *> &others) {
354
  // extend outlinks.
C
chengduo 已提交
355
  for (PDNode *x : others) {
356 357 358 359 360
    pattern_->AddEdge(this, x);
  }
  return *this;
}

C
chengduo 已提交
361
PDNode &PDNode::LinksFrom(const std::vector<PDNode *> &others) {
362
  // extend outlinks.
C
chengduo 已提交
363
  for (PDNode *x : others) {
364 365 366 367 368
    pattern_->AddEdge(x, this);
  }
  return *this;
}

C
chengduo 已提交
369 370
PDNode *PDNode::assert_is_op() {
  asserts_.emplace_back([](Node *x) { return x && x->IsOp(); });
Y
Yan Chunwei 已提交
371 372
  return this;
}
C
chengduo 已提交
373 374 375

PDNode *PDNode::assert_is_op(const std::string &op_type) {
  asserts_.emplace_back([op_type](Node *x) {
Y
Yan Chunwei 已提交
376 377 378 379
    return x && x->IsOp() && x->Op()->Type() == op_type;
  });
  return this;
}
C
chengduo 已提交
380 381 382 383 384 385 386 387

PDNode *PDNode::assert_is_var() {
  asserts_.emplace_back([](Node *x) { return x && x->IsVar(); });
  return this;
}

PDNode *PDNode::assert_is_not_ctrl_var() {
  asserts_.emplace_back([](Node *x) { return x && !x->IsCtrlVar(); });
Y
Yan Chunwei 已提交
388 389
  return this;
}
C
chengduo 已提交
390 391

PDNode *PDNode::assert_var_not_persistable() {
Y
Yan Chunwei 已提交
392
  assert_is_var();
C
chengduo 已提交
393
  asserts_.emplace_back([](Node *x) { return !x->Var()->Persistable(); });
Y
Yan Chunwei 已提交
394 395
  return this;
}
C
chengduo 已提交
396 397

PDNode *PDNode::assert_is_persistable_var() {
Y
Yan Chunwei 已提交
398
  assert_is_var();
C
chengduo 已提交
399
  asserts_.emplace_back([=](Node *x) { return x->Var()->Persistable(); });
Y
Yan Chunwei 已提交
400 401
  return this;
}
C
chengduo 已提交
402 403 404

PDNode *PDNode::assert_is_op_nth_input(const std::string &op_type,
                                       const std::string &argument, int nth) {
Y
Yan Chunwei 已提交
405 406
  assert_is_var();
  assert_is_op_input(op_type);
C
chengduo 已提交
407 408
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
409 410 411
      if (op->IsOp() && op->Op()->Type() == op_type &&
          IsNthInput(x, op, argument, nth))
        return true;
Y
Yan Chunwei 已提交
412 413 414 415 416
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
417 418 419

PDNode *PDNode::assert_is_op_nth_output(const std::string &op_type,
                                        const std::string &argument, int nth) {
Y
Yan Chunwei 已提交
420
  assert_is_var();
C
chengduo 已提交
421 422
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
423 424 425
      if (op->IsOp() && op->Op()->Type() == op_type &&
          IsNthOutput(x, op, argument, nth))
        return true;
Y
Yan Chunwei 已提交
426 427 428 429 430
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
431 432

PDNode *PDNode::assert_is_only_input_of_op(const std::string &op_type) {
Y
Yan Chunwei 已提交
433
  assert_is_var();
C
chengduo 已提交
434 435
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->outputs) {
Y
Yan Chunwei 已提交
436 437 438 439 440 441 442 443 444
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->inputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
445 446

PDNode *PDNode::assert_is_only_output_of_op(const std::string &op_type) {
Y
Yan Chunwei 已提交
447
  assert_is_var();
C
chengduo 已提交
448 449
  asserts_.emplace_back([=](Node *x) {
    for (auto *op : x->inputs) {
Y
Yan Chunwei 已提交
450 451 452 453 454 455 456 457 458
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->outputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
C
chengduo 已提交
459 460

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

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

PDNode *PDNode::assert_is_op_input(const std::string &op_type,
                                   const std::string &argument) {
494 495 496 497
  assert_is_var();
  assert_is_op_nth_input(op_type, argument, 0);
  return this;
}
C
chengduo 已提交
498 499

PDNode *PDNode::assert_op_has_n_inputs(const std::string &op_type, size_t n) {
Y
Yan Chunwei 已提交
500
  assert_is_op(op_type);
C
chengduo 已提交
501
  asserts_.emplace_back([=](Node *x) { return x->inputs.size() == n; });
Y
Yan Chunwei 已提交
502 503
  return this;
}
C
chengduo 已提交
504 505

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

511 512 513 514 515 516 517 518 519 520
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 已提交
521
PDNode *PDNode::assert_more(PDNode::teller_t &&teller) {
Y
Yan Chunwei 已提交
522 523 524 525
  asserts_.emplace_back(std::move(teller));
  return this;
}

C
chengduo 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
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,
    const std::string &argument, int nth) {
  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,
    const std::string &argument, int nth) {
  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;
}

bool VarLinksToOp(Node *node, const std::string &op_type) {
  for (auto *out : node->outputs) {
609 610 611 612 613 614
    if (out->IsOp() && out->Op()->Type() == op_type) {
      return true;
    }
  }
  return false;
}
C
chengduo 已提交
615 616

bool IsNthInput(Node *var, Node *op, const std::string &argument, size_t nth) {
617 618 619 620 621 622 623 624
  PADDLE_ENFORCE_EQ(
      var->IsVar(), true,
      platform::errors::InvalidArgument(
          "First parameter of function IsNthInput must be Node::Var"));
  PADDLE_ENFORCE_EQ(
      op->IsOp(), true,
      platform::errors::InvalidArgument(
          "Second parameter of function IsNthInput must be Node::Op"));
625 626
  if (!HasInput(op, argument) || op->Op()->Input(argument).size() <= nth)
    return false;
627 628
  return var->Name() == op->Op()->Input(argument)[nth];
}
C
chengduo 已提交
629

630
bool HasInput(Node *op, const std::string &argument) {
631 632 633 634
  PADDLE_ENFORCE_EQ(
      op->IsOp(), true,
      platform::errors::InvalidArgument(
          "First parameter of function HasInput must be Node::Op"));
635 636 637 638 639 640
  auto const &names = op->Op()->InputNames();
  if (std::find(names.begin(), names.end(), argument) == names.end())
    return false;
  return true;
}

C
chengduo 已提交
641
bool IsNthOutput(Node *var, Node *op, const std::string &argument, size_t nth) {
642 643 644 645 646 647 648 649
  PADDLE_ENFORCE_EQ(
      var->IsVar(), true,
      platform::errors::InvalidArgument(
          "First parameter of function IsNthOutput must be Node::Var"));
  PADDLE_ENFORCE_EQ(
      op->IsOp(), true,
      platform::errors::InvalidArgument(
          "Second parameter of function IsNthOutput must be Node::Op"));
650 651 652
  if (op->Op()->Output(argument).size() <= nth) return false;
  return var->Name() == op->Op()->Output(argument)[nth];
}
C
chengduo 已提交
653 654 655 656 657

void GraphSafeRemoveNodes(Graph *graph,
                          const std::unordered_set<const Node *> &nodes) {
  for (auto *node : nodes) {
    graph->RemoveNode(const_cast<Node *>(node));
658 659
  }

C
chengduo 已提交
660
  for (auto *node : graph->Nodes()) {
661 662
    for (auto it = node->inputs.begin(); it != node->inputs.end();) {
      if (nodes.count(*it)) {
C
chengduo 已提交
663
        it = const_cast<Node *>(node)->inputs.erase(it);
664
      } else {
665
        it++;
666
      }
667 668 669
    }
    for (auto it = node->outputs.begin(); it != node->outputs.end();) {
      if (nodes.count(*it)) {
C
chengduo 已提交
670
        it = const_cast<Node *>(node)->outputs.erase(it);
671
      } else {
672
        it++;
673
      }
674 675 676
    }
  }
}
C
chengduo 已提交
677 678 679

bool VarLinksFromOp(Node *node, const std::string &op_type) {
  for (auto *out : node->inputs) {
680 681 682 683 684 685 686
    if (out->IsOp() && out->Op()->Type() == op_type) {
      return true;
    }
  }
  return false;
}

S
Sylwester Fraczek 已提交
687
PDNode *patterns::ConvBN::operator()(paddle::framework::ir::PDNode *conv_input,
688
                                     const std::string &conv_type,
S
Sylwester Fraczek 已提交
689 690
                                     bool with_eltwise_add) {
  // Create Operators
691 692
  conv_input->assert_is_op_input(conv_type, "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
S
Sylwester Fraczek 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705

  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()
706
                              ->assert_is_op_input(conv_type, "Filter");
S
Sylwester Fraczek 已提交
707 708 709

  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
710
                           ->assert_is_only_output_of_op(conv_type);
S
Sylwester Fraczek 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

  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 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()
                           ->assert_is_op_input("batch_norm", "Scale");
  // BN Bias
  auto *bn_bias_var = pattern->NewNode(bn_bias_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
                          ->assert_is_op_input("batch_norm", "Bias");
  // BN Mean
  auto *bn_mean_var = pattern->NewNode(bn_mean_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
                          ->assert_is_op_input("batch_norm", "Mean");
  // BN Variance
  auto *bn_variance_var = pattern->NewNode(bn_variance_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
                              ->assert_is_op_input("batch_norm", "Variance");

  // BN output
  auto *bn_out_var = pattern->NewNode(bn_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("batch_norm");

  auto *bn_mean_out_var = pattern->NewNode(bn_mean_out_repr())
                              ->AsOutput()
                              ->assert_is_op_output("batch_norm", "MeanOut");

  auto *bn_variance_out_var =
      pattern->NewNode(bn_variance_out_repr())
          ->AsOutput()
          ->assert_is_op_output("batch_norm", "VarianceOut");

  auto *bn_saved_mean_var =
      pattern->NewNode(bn_saved_mean_repr())
          ->AsOutput()
          ->assert_is_op_output("batch_norm", "SavedMean");

  auto *bn_saved_variance_var =
      pattern->NewNode(bn_saved_variance_repr())
          ->AsOutput()
          ->assert_is_op_output("batch_norm", "SavedVariance");

  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
        ->LinksFrom({eltwise_out_var, bn_scale_var, bn_bias_var, bn_mean_var,
                     bn_variance_var})
        .LinksTo({bn_out_var, bn_mean_out_var, bn_variance_out_var,
                  bn_saved_mean_var, bn_saved_variance_var});
  } else {
    batch_norm_op
        ->LinksFrom({conv_out_var, bn_scale_var, bn_bias_var, bn_mean_var,
                     bn_variance_var})
        .LinksTo({bn_out_var, bn_mean_out_var, bn_variance_out_var,
                  bn_saved_mean_var, bn_saved_variance_var});
  }
  return bn_out_var;
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
PDNode *patterns::ConvActivation::operator()(
    paddle::framework::ir::PDNode *conv_input, std::string conv_type,
    std::string activation_type) {
  // Create Operators
  conv_input->assert_is_op_input(conv_type, "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
  auto *activation_op =
      pattern->NewNode(activation_repr())->assert_is_op(activation_type);
  // Create variables
  // Filter
  auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
                              ->assert_is_op_input(conv_type, "Filter");
  // intermediate variable, will be removed in the IR after fuse.
  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
                           ->assert_is_only_output_of_op(conv_type)
                           ->assert_is_op_input(activation_type);
  // output
  auto *activation_out_var = pattern->NewNode(activation_out_repr())
                                 ->AsOutput()
                                 ->assert_is_op_output(activation_type);

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

T
tensor-tang 已提交
823 824 825 826
PDNode *patterns::SeqConvEltAddRelu::operator()(
    paddle::framework::ir::PDNode *seqconv_input) {
  // Create Operators
  seqconv_input->assert_is_op_input("sequence_conv", "X");
T
tensor-tang 已提交
827 828 829 830
  auto *seqconv_op = pattern->NewNode(seqconv_repr())
                         ->assert_is_op("sequence_conv")
                         ->assert_op_attr<bool>("paddingTrainable", false)
                         ->assert_op_attr<int>("contextStride", 1);
T
tensor-tang 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867

  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 已提交
868
PDNode *patterns::FC::operator()(paddle::framework::ir::PDNode *x,
869
                                 bool with_bias, bool with_relu) {
Y
Yan Chunwei 已提交
870 871
  // Create shared nodes.
  x->assert_is_op_input("mul", "X");
C
chengduo 已提交
872
  auto *mul = pattern->NewNode(mul_repr())->assert_is_op("mul");
Y
Yan Chunwei 已提交
873

C
chengduo 已提交
874
  auto *mul_w_var = pattern->NewNode(w_repr())
Y
Yan Chunwei 已提交
875 876 877 878
                        ->AsInput()
                        ->assert_is_persistable_var()
                        ->assert_is_op_input("mul", "Y");

C
chengduo 已提交
879
  auto *mul_out_var =
Y
Yan Chunwei 已提交
880 881
      pattern->NewNode(mul_out_repr())->assert_is_op_output("mul");

882 883
  // Add links.
  mul->LinksFrom({x, mul_w_var}).LinksTo({mul_out_var});
Y
Yan Chunwei 已提交
884 885 886 887 888
  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 已提交
889
    auto *elementwise_add = pattern->NewNode(elementwise_add_repr())
Y
Yan Chunwei 已提交
890 891
                                ->assert_is_op("elementwise_add");
    // Create variables.
C
chengduo 已提交
892
    auto *bias = pattern->NewNode(bias_repr())
Y
Yan Chunwei 已提交
893
                     ->assert_is_op_input("elementwise_add")
894
                     ->assert_is_persistable_var()
Y
Yan Chunwei 已提交
895 896
                     ->AsInput();

897 898 899 900
    auto *elementwise_add_out_var =
        pattern->NewNode(elementwise_add_out_repr())
            ->AsOutput()
            ->assert_is_op_output("elementwise_add");
Y
Yan Chunwei 已提交
901

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
    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;
    }
917 918
  }
}
T
tensor-tang 已提交
919

920 921 922 923 924 925 926
PDNode *patterns::FCMKLDNN::operator()(paddle::framework::ir::PDNode *x,
                                       bool with_bias) {
  // Create shared nodes.
  x->assert_is_op_input("fc", "Input");

  auto *fc_op = pattern->NewNode(fc_repr())->assert_is_op("fc");
  // Create variables
M
Michał Gallus 已提交
927 928 929 930
  // Input
  auto *input_var = pattern->NewNode(input_repr())
                        ->AsInput()
                        ->assert_is_op_input("fc", "Input");
931 932 933 934 935 936 937 938 939 940 941 942 943 944
  // 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");

M
Michał Gallus 已提交
945 946
  fc_op->LinksFrom({input_var, fc_weight_var, fc_bias_var})
      .LinksTo({fc_out_var});
947 948 949
  return fc_out_var;
}

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
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 已提交
968
PDNode *patterns::LSTM::operator()(PDNode *x) {
969
  x->assert_is_op_input("lstm", "Input");
C
chengduo 已提交
970
  auto *lstm_op = pattern->NewNode(lstm_repr())->assert_is_op("lstm");
Y
Yan Chunwei 已提交
971
#define NEW_NODE(arg__, io__) \
C
chengduo 已提交
972
  auto *arg__ =               \
Y
Yan Chunwei 已提交
973
      pattern->NewNode(arg__##_repr())->assert_is_op_##io__("lstm", #arg__);
974 975 976 977 978

  // 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 已提交
979 980
  NEW_NODE(Weight, input);
  NEW_NODE(Bias, input);
981

Y
Yan Chunwei 已提交
982 983 984 985 986
  NEW_NODE(Hidden, output);
  NEW_NODE(Cell, output);
  NEW_NODE(BatchGate, output);
  NEW_NODE(BatchCellPreAct, output);
#undef NEW_NODE
987 988 989 990 991

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

C
chengduo 已提交
993
PDNode *patterns::GRU::operator()(PDNode *x) {
T
tensor-tang 已提交
994
  x->assert_is_op_input("gru", "Input");
C
chengduo 已提交
995
  auto *gru_op = pattern->NewNode(gru_repr())->assert_is_op("gru");
Y
Yan Chunwei 已提交
996
#define NEW_NODE(arg__, io__) \
C
chengduo 已提交
997
  auto *arg__ =               \
Y
Yan Chunwei 已提交
998
      pattern->NewNode(arg__##_repr())->assert_is_op_##io__("gru", #arg__);
T
tensor-tang 已提交
999

Y
Yan Chunwei 已提交
1000
  NEW_NODE(Weight, input);
T
tensor-tang 已提交
1001 1002
  // TODO(Superjomn): upgrade the fuse framework to support optional.
  // H0 and bias are optional
Y
Yan Chunwei 已提交
1003
  NEW_NODE(Bias, input);  // also optional
T
tensor-tang 已提交
1004 1005
  // NEW_NODE(H0, input);

Y
Yan Chunwei 已提交
1006
  NEW_NODE(Hidden, output);
T
tensor-tang 已提交
1007
  // below are intermediate
Y
Yan Chunwei 已提交
1008 1009 1010 1011
  NEW_NODE(BatchGate, output);
  NEW_NODE(BatchResetHiddenPrev, output);
  NEW_NODE(BatchHidden, output);
#undef NEW_NODE
T
tensor-tang 已提交
1012

T
tensor-tang 已提交
1013 1014 1015 1016
  BatchGate->AsIntermediate();
  BatchResetHiddenPrev->AsIntermediate();
  BatchHidden->AsIntermediate();

T
tensor-tang 已提交
1017 1018 1019 1020 1021
  gru_op->LinksFrom({x, Weight, Bias});
  gru_op->LinksTo({Hidden, BatchGate, BatchResetHiddenPrev, BatchHidden});
  return Hidden;
}

C
chengduo 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 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 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
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;
}

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::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;
}

1116
// conv_type: conv2d, conv3d, conv2d_transpose
M
Michal Gallus 已提交
1117
PDNode *patterns::ConvBias::operator()(
1118
    paddle::framework::ir::PDNode *conv_input, std::string conv_type) {
M
Michal Gallus 已提交
1119
  // Create Operators
1120 1121
  conv_input->assert_is_op_input(conv_type, "Input");
  auto *conv_op = pattern->NewNode(conv_repr())->assert_is_op(conv_type);
M
Michal Gallus 已提交
1122 1123 1124 1125
  auto *eltiwse_op =
      pattern->NewNode(eltwise_repr())->assert_is_op("elementwise_add");
  // Create variables
  // Filter
Y
Yihua Xu 已提交
1126 1127 1128
  auto *conv_weight_var = pattern->NewNode(conv_weight_repr())
                              ->AsInput()
                              ->assert_is_persistable_var()
1129
                              ->assert_is_op_input(conv_type, "Filter");
M
Michal Gallus 已提交
1130
  // intermediate variable, will be removed in the IR after fuse.
Y
Yihua Xu 已提交
1131 1132
  auto *conv_out_var = pattern->NewNode(conv_out_repr())
                           ->AsIntermediate()
1133
                           ->assert_is_only_output_of_op(conv_type)
Y
Yihua Xu 已提交
1134
                           ->assert_is_op_input("elementwise_add");
M
Michal Gallus 已提交
1135 1136 1137
  // Bias stored in elementwise_add
  auto *eltwise_bias_var = pattern->NewNode(eltwise_bias_repr())
                               ->AsInput()
M
Michal Gallus 已提交
1138
                               ->assert_is_persistable_var()
M
Michal Gallus 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                               ->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;
}

1150 1151 1152 1153
PDNode *patterns::Conv::operator()() {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");

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

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

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

1165 1166 1167 1168
  conv_op->LinksFrom({input_var, filter_var}).LinksTo({output_var});
  return output_var;
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
PDNode *patterns::Transpose::operator()() {
  auto prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();

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

  auto transpose_in = pattern->NewNode(transpose_in_repr())
                          ->AsInput()
                          ->assert_is_op_input("transpose2");
  auto transpose_out = pattern->NewNode(transpose_out_repr())
                           ->AsOutput()
                           ->assert_is_op_output("transpose2", "Out");

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

  prev_op->LinksTo({transpose_in});
  transpose_op->LinksFrom({transpose_in}).LinksTo({transpose_out});
  next_op->LinksFrom({transpose_out});
  return transpose_out;
}

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
PDNode *patterns::Reshape::operator()() {
  auto prev_op = pattern->NewNode(prev_op_repr())->assert_is_op();

  auto reshape_op =
      pattern->NewNode(reshape_op_repr())->assert_is_op("reshape2");

  auto reshape_in = pattern->NewNode(reshape_in_repr())
                        ->AsInput()
                        ->assert_is_op_input("reshape2", "X");
  auto reshape_out = pattern->NewNode(reshape_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("reshape2", "Out");

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

  prev_op->LinksTo({reshape_in});
  reshape_op->LinksFrom({reshape_in}).LinksTo({reshape_out});
  next_op->LinksFrom({reshape_out});
  return reshape_out;
}

1211 1212 1213
PDNode *patterns::ConvResidual::operator()(bool with_residual_data) {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");

1214 1215 1216 1217 1218 1219 1220 1221 1222
  if (!with_residual_data) {
    conv_op->assert_more([&](Node *x) {
      auto node_names = x->Op()->InputNames();
      if (!HasInput(x, "ResidualData") ||
          x->Op()->Input("ResidualData").size() == 0)
        return true;
      return false;
    });
  }
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 1256 1257 1258

  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");
1259

1260
  pool_op->LinksFrom({input_var}).LinksTo({output_var});
1261 1262 1263
  return output_var;
}

1264
PDNode *patterns::ElementwiseAdd::operator()(PDNode *x_var, PDNode *y_var) {
1265 1266 1267
  auto elementwise_add_op = pattern->NewNode(elementwise_add_op_repr())
                                ->assert_is_op("elementwise_add");

1268 1269
  x_var->AsInput()->assert_is_op_input("elementwise_add", "X");
  y_var->AsInput()->assert_is_op_input("elementwise_add", "Y");
1270 1271 1272 1273
  auto out_var = pattern->NewNode(elementwise_add_out_repr())
                     ->AsOutput()
                     ->assert_is_op_output("elementwise_add", "Out");

1274
  elementwise_add_op->LinksFrom({x_var, y_var});
1275 1276 1277 1278
  elementwise_add_op->LinksTo({out_var});

  return out_var;
}
1279

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
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;
}

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 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
PDNode *patterns::ConcatReLU::operator()() {
  auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");
  auto relu_op = pattern->NewNode(relu_op_repr())->assert_is_op("relu");

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

  auto relu_out = pattern->NewNode(relu_out_repr())
                      ->AsOutput()
                      ->assert_is_op_output("relu", "Out");

  concat_op->LinksTo({concat_out});
  relu_op->LinksFrom({concat_out}).LinksTo({relu_out});

  return relu_out;
}

PDNode *patterns::ConvConcatReLU::operator()() {
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto concat_op = pattern->NewNode(concat_op_repr())->assert_is_op("concat");
  auto relu_op = pattern->NewNode(relu_op_repr())->assert_is_op("relu");

  auto conv_out = pattern->NewNode(conv_out_repr())
                      ->assert_is_op_output("conv2d", "Output");

  auto concat_out = pattern->NewNode(concat_out_repr())
                        ->assert_is_op_output("concat", "Out")
                        ->assert_is_op_input("relu", "X");

  auto relu_out = pattern->NewNode(relu_out_repr())
                      ->AsOutput()
                      ->assert_is_op_output("relu", "Out");

  conv_op->LinksTo({conv_out});
  concat_op->LinksFrom({conv_out}).LinksTo({concat_out});
  relu_op->LinksFrom({concat_out}).LinksTo({relu_out});

  return relu_out;
}

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
PDNode *patterns::ConvRequant::operator()() {
  // Create Operators
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto requant_op =
      pattern->NewNode(requant_op_repr())->assert_is_op("requantize");
  auto conv_out = pattern->NewNode(conv_out_repr())
                      ->assert_is_op_output("conv2d", "Output");
  auto requant_out = pattern->NewNode(requant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("requantize", "Output");

  conv_op->LinksTo({conv_out});
  requant_op->LinksFrom({conv_out}).LinksTo({requant_out});

  return requant_out;
}

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
PDNode *patterns::ConvDequant::operator()() {
  // Create Operators
  auto conv_op = pattern->NewNode(conv_op_repr())->assert_is_op("conv2d");
  auto dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");

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

  conv_op->LinksTo({conv_out});
  dequant_op->LinksFrom({conv_out}).LinksTo({dequant_out});

  return dequant_out;
}

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
PDNode *patterns::FcDequant::operator()() {
  // Create Operators
  auto fc_op = pattern->NewNode(fc_op_repr())->assert_is_op("fc");
  auto dequant_op =
      pattern->NewNode(dequant_op_repr())->assert_is_op("dequantize");

  auto fc_out =
      pattern->NewNode(fc_out_repr())->assert_is_op_output("fc", "Out");
  auto dequant_out = pattern->NewNode(dequant_out_repr())
                         ->AsOutput()
                         ->assert_is_op_output("dequantize", "Output");

  fc_op->LinksTo({fc_out});
  dequant_op->LinksFrom({fc_out}).LinksTo({dequant_out});

  return dequant_out;
}

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
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;
}

H
hjchen2 已提交
1409
std::unordered_set<std::string> conv_act_set({"identity", "relu"});
1410 1411 1412 1413 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

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())
                                  ->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;
}

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())
                                  ->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 已提交
1475
                                 ->assert_is_op_input("elementwise_add", "Y")
1476 1477 1478 1479 1480
                                 ->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 已提交
1481
                                    ->assert_is_op_input("elementwise_add", "X")
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
                                    ->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 已提交
1509 1510
  elementwise_add_op_1->LinksFrom({elementwise_add_out, elementwise_add_in_y_1})
      .LinksTo({elementwise_add_out_1});
1511 1512 1513 1514
  act_op->LinksFrom({elementwise_add_out_1}).LinksTo({act_out});
  return act_out;
}

N
nhzlx 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
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())
1528
                                  ->assert_is_persistable_var()
N
nhzlx 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
                                  ->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 已提交
1543 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 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
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()
1589
                           ->assert_has_n_outputs(1)
N
nhzlx 已提交
1590 1591 1592 1593 1594
                           ->assert_is_op_input("affine_channel", "Scale");
  // AC Bias
  auto *ac_bias_var = pattern->NewNode(ac_bias_repr())
                          ->AsInput()
                          ->assert_is_persistable_var()
1595
                          ->assert_has_n_outputs(1)
N
nhzlx 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
                          ->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;
}

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 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
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;
}

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
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;
}

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
// 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;
}

1740
PDNode *patterns::AnakinDetectionPattern::operator()(
N
nhzlx 已提交
1741 1742
    std::vector<PDNode *> conv_in, int times, std::string priorbox_type,
    bool is_reshape) {
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
  // The times represents the repeat times of the
  // {prior_box, prior_box_loc_out, flatten, prior_box_var_out, reshape}
  const int kNumFields = 7;
  const int kPriorBoxLocOffset = 1;
  const int kReshape1Offset = 2;
  const int kReshape1OutOffset = 3;
  const int kPriorBoxVarOffset = 4;
  const int kReshape2Offset = 5;
  const int kReshape2OutOffset = 6;

  const int kBoxCoderThirdInputOffset = times;
  const int kMultiClassSecondInputNmsOffset = times + 1;

  std::vector<PDNode *> nodes;
N
nhzlx 已提交
1757
  std::string op_after_priorbox = is_reshape ? "reshape2" : "flatten2";
1758 1759 1760 1761

  for (int i = 0; i < times; i++) {
    nodes.push_back(
        pattern->NewNode(GetNodeName("prior_box" + std::to_string(i)))
N
nhzlx 已提交
1762
            ->assert_is_op(priorbox_type));
1763
    nodes.push_back(pattern->NewNode(GetNodeName("box_out" + std::to_string(i)))
N
nhzlx 已提交
1764 1765
                        ->assert_is_op_output(priorbox_type, "Boxes")
                        ->assert_is_op_input(op_after_priorbox, "X")
1766 1767 1768
                        ->AsIntermediate());
    nodes.push_back(
        pattern->NewNode(GetNodeName("reshape1" + std::to_string(i)))
N
nhzlx 已提交
1769
            ->assert_is_op(op_after_priorbox));
1770 1771 1772

    nodes.push_back(
        pattern->NewNode(GetNodeName("reshape1_out" + std::to_string(i)))
N
nhzlx 已提交
1773
            ->assert_is_op_output(op_after_priorbox)
1774 1775 1776 1777 1778
            ->assert_is_op_nth_input("concat", "X", i)
            ->AsIntermediate());

    nodes.push_back(
        pattern->NewNode(GetNodeName("box_var_out" + std::to_string(i)))
N
nhzlx 已提交
1779 1780
            ->assert_is_op_output(priorbox_type, "Variances")
            ->assert_is_op_input(op_after_priorbox, "X")
1781 1782 1783
            ->AsIntermediate());
    nodes.push_back(
        pattern->NewNode(GetNodeName("reshape2" + std::to_string(i)))
N
nhzlx 已提交
1784
            ->assert_is_op(op_after_priorbox));
1785 1786 1787

    nodes.push_back(
        pattern->NewNode(GetNodeName("reshape2_out" + std::to_string(i)))
N
nhzlx 已提交
1788
            ->assert_is_op_output(op_after_priorbox)
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
            ->assert_is_op_nth_input("concat", "X", i)
            ->AsIntermediate());
  }

  auto concat_op1 = pattern->NewNode(GetNodeName("concat1"))
                        ->assert_is_op("concat")
                        ->assert_op_has_n_inputs("concat", times);
  auto concat_out1 = pattern->NewNode(GetNodeName("concat1_out"))
                         ->assert_is_op_output("concat")
                         ->AsIntermediate();

  auto concat_op2 = pattern->NewNode(GetNodeName("concat2"))
                        ->assert_is_op("concat")
                        ->assert_op_has_n_inputs("concat", times);
  auto concat_out2 = pattern->NewNode(GetNodeName("concat2_out"))
                         ->assert_is_op_output("concat")
                         ->AsIntermediate();

  auto box_coder_op = pattern->NewNode(GetNodeName("box_coder"))
                          ->assert_is_op("box_coder")
                          ->assert_op_has_n_inputs("box_coder", 3);

  auto box_coder_out = pattern->NewNode(GetNodeName("box_coder_out"))
                           ->assert_is_op_output("box_coder")
                           ->AsIntermediate();

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
  auto transpose_before_nms =
      pattern->NewNode(GetNodeName("transpose_before_nms"))
          ->assert_is_op("transpose2");

  auto transpose_before_nms_out =
      pattern->NewNode(GetNodeName("transpose_before_nms_out"))
          ->assert_is_op_output("transpose2")
          ->assert_is_op_input("multiclass_nms", "Scores")
          ->AsIntermediate();

1825 1826 1827 1828 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 1872 1873 1874
  auto multiclass_nms_op = pattern->NewNode(GetNodeName("multiclass_nms"))
                               ->assert_is_op("multiclass_nms")
                               ->assert_op_has_n_inputs("multiclass_nms", 2);

  auto multiclass_nms_out = pattern->NewNode(GetNodeName("multiclass_nms_out"))
                                ->assert_is_op_output("multiclass_nms")
                                ->AsOutput();

  std::vector<PDNode *> reshape1_outs;
  std::vector<PDNode *> reshape2_outs;

  for (int i = 0; i < times; i++) {
    conv_in[i]->AsInput();
    // prior_box
    nodes[i * kNumFields]->LinksFrom({conv_in[i]});
    // prior_box box out
    nodes[i * kNumFields + kPriorBoxLocOffset]->LinksFrom(
        {nodes[i * kNumFields]});
    // reshape
    nodes[i * kNumFields + kReshape1Offset]->LinksFrom(
        {nodes[i * kNumFields + kPriorBoxLocOffset]});
    // reshape_out
    nodes[i * kNumFields + kReshape1OutOffset]->LinksFrom(
        {nodes[i * kNumFields + kReshape1Offset]});

    nodes[i * kNumFields + kPriorBoxVarOffset]->LinksFrom(
        {nodes[i * kNumFields]});
    // reshape
    nodes[i * kNumFields + kReshape2Offset]->LinksFrom(
        {nodes[i * kNumFields + kPriorBoxVarOffset]});
    // reshape_out
    nodes[i * kNumFields + kReshape2OutOffset]->LinksFrom(
        {nodes[i * kNumFields + kReshape2Offset]});

    reshape1_outs.push_back(nodes[i * kNumFields + kReshape1OutOffset]);
    reshape2_outs.push_back(nodes[i * kNumFields + kReshape2OutOffset]);
  }

  concat_op1->LinksFrom(reshape1_outs);
  concat_op2->LinksFrom(reshape2_outs);
  concat_out1->LinksFrom({concat_op1});
  concat_out2->LinksFrom({concat_op2});

  conv_in[kBoxCoderThirdInputOffset]->AsInput();
  conv_in[kMultiClassSecondInputNmsOffset]->AsInput();

  box_coder_op->LinksFrom(
      {concat_out1, concat_out2, conv_in[kBoxCoderThirdInputOffset]});
  box_coder_out->LinksFrom({box_coder_op});

1875 1876 1877 1878
  transpose_before_nms->LinksFrom({conv_in[kMultiClassSecondInputNmsOffset]});
  transpose_before_nms_out->LinksFrom({transpose_before_nms});

  multiclass_nms_op->LinksFrom({box_coder_out, transpose_before_nms_out})
1879 1880 1881 1882 1883
      .LinksTo({multiclass_nms_out});

  return multiclass_nms_out;
}

N
nhzlx 已提交
1884
PDNode *patterns::FillConstantElementWiseMulFuse::operator()(
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    PDNode *elementwise_op_input) {
  auto fill_constant =
      pattern->NewNode(fill_constant_repr())->assert_is_op("fill_constant");

  auto fill_constant_out = pattern->NewNode(fill_constant_out_repr())
                               ->assert_is_op_output("fill_constant")
                               ->assert_is_op_input("elementwise_mul", "Y")
                               ->AsIntermediate();

  auto elementwise_mul_op =
      pattern->NewNode(elementwise_mul_repr())->assert_is_op("elementwise_mul");

  auto elementwise_mul_out = pattern->NewNode(elementwise_mul_out_repr())
                                 ->assert_is_op_output("elementwise_mul")
                                 ->AsOutput();

  fill_constant_out->LinksFrom({fill_constant});
  elementwise_mul_op->LinksFrom({elementwise_op_input, fill_constant_out});
  elementwise_mul_out->LinksFrom({elementwise_mul_op});
  return elementwise_mul_out;
}

N
nhzlx 已提交
1907 1908 1909
void patterns::QuantDequantOpFuse::operator()(PDNode *quant_op_input,
                                              const std::string &op_type,
                                              const std::string &weight_name,
1910
                                              int times,
1911 1912 1913
                                              const std::string &quant_type,
                                              const std::string &dequant_type) {
  int kNumFields = 5;
N
nhzlx 已提交
1914 1915 1916 1917 1918
  const int kQuantizedWeightOffset = 0;
  const int kQuantizedOpOffset = 1;
  const int kQuantizedOpOutOffset = 2;
  const int kDequantOpOffset = 3;
  const int kDequantOpOutOffset = 4;
1919 1920
  const int kDequantOpWeightScaleOffset = 5;

N
nhzlx 已提交
1921
  // the quant op always be one.
1922 1923 1924 1925 1926
  auto quant_op_in_scale = pattern->NewNode(GetNodeName("quant_op_in_scale"))
                               ->assert_is_op_input(quant_type, "InScale")
                               ->AsInput();
  auto quant_op =
      pattern->NewNode(GetNodeName("quant_op"))->assert_is_op(quant_type);
N
nhzlx 已提交
1927

1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
  PDNode *quant_op_out_scale = nullptr;
  if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
    kNumFields += 1;
    quant_op_out_scale = pattern->NewNode(GetNodeName("quant_op_out_scale"))
                             ->assert_is_op_output(quant_type, "OutScale")
                             ->assert_is_op_nth_input(dequant_type, "Scales", 1)
                             ->AsIntermediate();
  } else {
    quant_op_out_scale = pattern->NewNode(GetNodeName("quant_op_out_scale"))
                             ->assert_is_op_output(quant_type, "OutScale")
                             ->assert_is_op_input(dequant_type, "Scale")
                             ->AsIntermediate();
  }
N
nhzlx 已提交
1941

1942 1943 1944 1945
  auto quant_op_out = pattern->NewNode(GetNodeName("quant_op_out"))
                          ->assert_is_op_output(quant_type, "Out")
                          ->assert_is_op_input(op_type)
                          ->AsIntermediate();
N
nhzlx 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960

  // there are 'times' quantized and dequant op
  std::vector<PDNode *> nodes;
  for (int i = 0; i < times; i++) {
    nodes.push_back(
        pattern->NewNode(GetNodeName("quantized_op_weight") + std::to_string(i))
            ->assert_is_op_input(op_type, weight_name)
            ->AsInput());
    nodes.push_back(
        pattern->NewNode(GetNodeName("quantized_op") + std::to_string(i))
            ->assert_is_op(op_type));

    nodes.push_back(
        pattern->NewNode(GetNodeName("quantized_op_out") + std::to_string(i))
            ->assert_is_op_output(op_type)
1961
            ->assert_is_op_input(dequant_type, "X")
N
nhzlx 已提交
1962 1963 1964 1965
            ->AsIntermediate());

    nodes.push_back(
        pattern->NewNode(GetNodeName("dequant_op") + std::to_string(i))
1966 1967
            ->assert_is_op(dequant_type));

N
nhzlx 已提交
1968 1969
    nodes.push_back(
        pattern->NewNode(GetNodeName("dequant_op_out") + std::to_string(i))
1970
            ->assert_is_op_output(dequant_type, "Out")
N
nhzlx 已提交
1971
            ->AsOutput());
1972 1973 1974 1975 1976 1977 1978 1979

    if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
      nodes.push_back(pattern
                          ->NewNode(GetNodeName("dequant_channel_scale") +
                                    std::to_string(i))
                          ->assert_is_op_nth_input(dequant_type, "Scales", 0)
                          ->AsInput());
    }
N
nhzlx 已提交
1980 1981 1982 1983 1984 1985 1986 1987 1988
  }

  quant_op->LinksFrom({quant_op_input, quant_op_in_scale});
  quant_op_out->LinksFrom({quant_op});
  for (int i = 0; i < times; i++) {
    nodes[i * kNumFields + kQuantizedOpOffset]->LinksFrom(
        {quant_op_out, nodes[i * kNumFields + kQuantizedWeightOffset]});
    nodes[i * kNumFields + kQuantizedOpOutOffset]->LinksFrom(
        {nodes[i * kNumFields + kQuantizedOpOffset]});
1989 1990 1991 1992 1993 1994 1995 1996
    if (dequant_type == "fake_channel_wise_dequantize_max_abs") {
      nodes[i * kNumFields + kDequantOpOffset]->LinksFrom(
          {nodes[i * kNumFields + kQuantizedOpOutOffset], quant_op_out_scale,
           nodes[i * kNumFields + kDequantOpWeightScaleOffset]});
    } else {
      nodes[i * kNumFields + kDequantOpOffset]->LinksFrom(
          {nodes[i * kNumFields + kQuantizedOpOutOffset], quant_op_out_scale});
    }
N
nhzlx 已提交
1997 1998 1999 2000 2001
    nodes[i * kNumFields + kDequantOpOutOffset]->LinksFrom(
        {nodes[i * kNumFields + kDequantOpOffset]});
  }
}

2002 2003 2004
void patterns::ShuffleChannelPattern::operator()(PDNode *reshape1_in) {
  auto reshape1_op =
      pattern->NewNode(reshape1_op_repr())->assert_is_op("reshape2");
2005 2006 2007
  reshape1_op->assert_more([&](Node *x) {
    return boost::get<std::vector<int>>(x->Op()->GetAttr("shape")).size() == 5;
  });
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035

  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});
}

2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
void patterns::DeleteQuantDequantOpPattern::operator()() {
  auto any_op_out =
      pattern->NewNode(any_op_out_repr())
          ->assert_is_op_input(
              "fake_quantize_dequantize_moving_average_abs_max", "X")
          ->AsInput();

  auto quant_dequant_op_inscale =
      pattern->NewNode(quant_dequant_op_inscale_repr())
          ->assert_is_op_input(
              "fake_quantize_dequantize_moving_average_abs_max", "InScale")
          ->AsInput();
  auto quant_dequant_op =
      pattern->NewNode(quant_dequant_op_repr())
          ->assert_is_op("fake_quantize_dequantize_moving_average_abs_max");

  auto quant_dequant_out =
      pattern->NewNode(quant_dequant_op_out_repr())
          ->assert_is_op_output(
              "fake_quantize_dequantize_moving_average_abs_max", "Out")
          ->AsIntermediate();

  auto quant_dequant_op_outscale =
      pattern->NewNode(quant_dequant_op_outscale_repr())
          ->assert_is_op_output(
              "fake_quantize_dequantize_moving_average_abs_max", "OutScale")
          ->AsOutput();
  auto any_op2 = pattern->NewNode(any_op2_repr())->assert_is_op()->AsOutput();

  quant_dequant_op->LinksFrom({any_op_out, quant_dequant_op_inscale});
  quant_dequant_op_outscale->LinksFrom({quant_dequant_op});
  quant_dequant_out->LinksFrom({quant_dequant_op});
  any_op2->LinksFrom({quant_dequant_out});
}

2071 2072 2073
}  // namespace ir
}  // namespace framework
}  // namespace paddle