graph_pattern_detector.cc 13.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.

Q
Qiao Longfei 已提交
15
#include <array>
16 17 18 19
#include <string>
#include <vector>

#include "paddle/fluid/framework/ir/graph_helper.h"
20
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
21 22 23 24 25 26 27
#include "paddle/fluid/framework/ir/graph_traits.h"
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace framework {
namespace ir {

28 29
size_t PDPattern::id_ = 0UL;

Y
Yan Chunwei 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
PDNode* PDPattern::NewNode(const std::string& name) {
  if (!name.empty()) {
    PADDLE_ENFORCE_EQ(node_map_.count(name), 0,
                      "PDNode's name should be unique, get duplicate [%s]",
                      name);
  }

  nodes_.emplace_back(new PDNode(this, name));
  auto* cur = nodes_.back().get();
  node_map_[name] = cur;
  return cur;
}

43
PDNode* PDPattern::NewNode(PDNode::teller_t&& teller, const std::string& name) {
44 45 46 47 48 49
  if (!name.empty()) {
    PADDLE_ENFORCE_EQ(node_map_.count(name), 0,
                      "PDNode's name should be unique, get duplicate [%s]",
                      name);
  }

50
  nodes_.emplace_back(new PDNode(std::move(teller), this, name));
51
  auto* cur = nodes_.back().get();
52
  node_map_[name] = cur;
53 54 55
  return cur;
}

Y
Yan Chunwei 已提交
56
PDNode* PDPattern::RetrieveNode(const std::string& id) const {
57 58 59 60 61 62 63 64
  auto it = node_map_.find(id);
  if (it == node_map_.end()) {
    return nullptr;
  }

  return it->second;
}

65 66 67 68 69 70 71
void PDPattern::AddEdge(PDNode* a, PDNode* b) {
  PADDLE_ENFORCE(a);
  PADDLE_ENFORCE(b);
  PADDLE_ENFORCE(a != b, "can't connect to the same nodes.");
  edges_.emplace_back(a, b);
}

72 73
void GraphPatternDetector::operator()(Graph* graph,
                                      GraphPatternDetector::handle_t handler) {
74 75 76 77
  if (!MarkPDNodesInGraph(*graph)) return;
  auto subgraphs = DetectPatterns();
  UniquePatterns(&subgraphs);
  RemoveOverlappedMatch(&subgraphs);
Y
Yan Chunwei 已提交
78
  ValidateByNodeRole(&subgraphs);
79

Y
Yan Chunwei 已提交
80
  if (subgraphs.empty()) return;
81 82
  LOG(INFO) << "detect " << subgraphs.size() << " subgraph matches the pattern";
  int id = 0;
83
  for (auto& g : subgraphs) {
84
    LOG(INFO) << "optimizing #" << id++ << " subgraph";
85 86 87 88
    handler(g, graph);
  }
}

89
bool GraphPatternDetector::MarkPDNodesInGraph(const ir::Graph& graph) {
90
  VLOG(4) << "mark pdnodes in graph";
91 92 93 94 95
  if (graph.Nodes().empty()) return false;

  for (auto& node : GraphTraits::DFS(graph)) {
    for (const auto& pdnode : pattern_.nodes()) {
      if (pdnode->Tell(&node)) {
96
        VLOG(4) << "pdnode " << pdnode->name() << " marked";
97 98 99 100
        pdnodes2nodes_[pdnode.get()].insert(&node);
      }
    }
  }
Y
Yan Chunwei 已提交
101 102 103 104 105 106 107 108
  // Check to early stop if some PDNode can't find matched Node.
  for (auto& pdnode : pattern_.nodes()) {
    if (!pdnodes2nodes_.count(pdnode.get())) {
      VLOG(4) << pdnode->name() << " can't find matched Node, early stop";

      return false;
    }
  }
109
  VLOG(3) << pdnodes2nodes_.size() << " nodes marked";
110 111 112
  return !pdnodes2nodes_.empty();
}

Y
Yan Chunwei 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
// The intermediate Nodes can only link to the nodes inside the pattern, or this
// subgraph will be droped.
void GraphPatternDetector::ValidateByNodeRole(
    std::vector<GraphPatternDetector::subgraph_t>* subgraphs) {
  std::vector<GraphPatternDetector::subgraph_t> result;

  subgraphs->erase(
      std::remove_if(
          subgraphs->begin(), subgraphs->end(),
          [](const GraphPatternDetector::subgraph_t& subgraph) -> bool {
            // Collect the inputs and outputs.
            std::unordered_set<Node*> ios;
            for (auto& item : subgraph) {
              if (!item.first->IsIntermediate()) {
                ios.insert(item.second);
              }
            }
            for (auto& item : subgraph) {
              if (item.first->IsIntermediate()) {
                for (auto* x : item.second->inputs) {
                  if (!ios.count(x)) {
                    return true;
                  }
                }
                for (auto* x : item.second->outputs) {
                  if (!ios.count(x)) {
                    return true;
                  }
                }
              }
            }
            return false;
          }),
      subgraphs->end());
}

149 150 151 152
struct HitGroup {
  std::unordered_map<PDNode*, Node*> roles;

  bool Match(Node* node, PDNode* pat) {
153 154 155 156
    if (nodes_.count(node)) {
      if (!roles.count(pat)) return false;
      return roles[pat] == node;
    }
157 158 159
    return !roles.count(pat) || roles.at(pat) == node;
  }

160 161 162 163 164 165 166
  void Register(Node* node, PDNode* pat) {
    roles[pat] = node;
    nodes_.insert(node);
  }

 private:
  std::unordered_set<Node*> nodes_;
167 168 169 170 171 172 173 174 175 176 177 178
};

// Tell whether Node a links to b.
bool IsNodesLink(Node* a, Node* b) {
  for (auto* node : a->outputs) {
    if (b == node) {
      return true;
    }
  }
  return false;
}

179 180
std::vector<GraphPatternDetector::subgraph_t>
GraphPatternDetector::DetectPatterns() {
181
  // Init empty subgraphs.
182
  std::vector<GraphPatternDetector::subgraph_t> result;
183
  std::vector<HitGroup> init_groups;
184 185 186 187
  std::array<std::vector<HitGroup>, 2> bi_records;
  // PADDLE_ENFORCE(!pattern_.edges().empty(), "At least one edge is needed");
  auto* first_pnode = pattern_.edges().empty() ? pattern().nodes().front().get()
                                               : pattern_.edges().front().first;
188 189 190 191 192 193 194 195 196 197 198 199 200
  if (!pdnodes2nodes_.count(first_pnode)) return result;
  for (auto* node : pdnodes2nodes_[first_pnode]) {
    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.
  for (const auto& edge : pattern_.edges()) {
201
    VLOG(4) << "check " << edge.first->name() << " -> " << edge.second->name();
Y
Yan Chunwei 已提交
202
    // TODO(Superjomn) Fix bug here, the groups might be duplicate here.
203 204 205 206 207
    // Each role has two PDNodes, which indicates two roles.
    // Detect two Nodes that can match these two roles and they are connected.
    auto& pre_groups = bi_records[step % 2];
    auto& cur_groups = bi_records[1 - (step++ % 2)];
    cur_groups.clear();
208
    if (pre_groups.empty()) break;
209 210 211
    // source -> target
    for (Node* source : pdnodes2nodes_[edge.first]) {
      for (Node* target : pdnodes2nodes_[edge.second]) {
Y
Yan Chunwei 已提交
212
        VLOG(8) << "check " << source->id() << " -- " << target->id();
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        // TODO(Superjomn) add some prune strategies.
        for (const auto& group : pre_groups) {
          HitGroup new_group = group;
          if (IsNodesLink(source, target) &&
              new_group.Match(source, edge.first)) {
            new_group.Register(source, edge.first);
            if (new_group.Match(target, edge.second)) {
              new_group.Register(target, edge.second);
              cur_groups.push_back(new_group);
              // TODO(Superjomn) need to unique
            }
          }
        }
      }
    }
228
    VLOG(3) << "step " << step << " get records: " << cur_groups.size();
Y
Yan Chunwei 已提交
229 230 231 232 233 234
    for (auto& group : cur_groups) {
      for (auto& item : group.roles) {
        VLOG(4) << "node " << item.second->id() << " as " << item.first->name();
      }
      VLOG(4) << "=========================================================";
    }
235 236 237
  }

  for (auto& group : bi_records[step % 2]) {
238
    GraphPatternDetector::subgraph_t subgraph;
239 240 241 242 243 244 245 246
    for (auto& role : group.roles) {
      subgraph.emplace(role.first, role.second);
    }
    result.emplace_back(subgraph);
  }
  return result;
}

247 248
void GraphPatternDetector::UniquePatterns(
    std::vector<GraphPatternDetector::subgraph_t>* subgraphs) {
249
  if (subgraphs->empty()) return;
250
  std::vector<GraphPatternDetector::subgraph_t> result;
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  std::unordered_set<size_t> set;
  for (auto& g : *subgraphs) {
    size_t key = 0;
    for (auto& item : g) {
      key ^= std::hash<void*>{}(item.first);
      key ^= std::hash<void*>{}(item.second);
    }
    if (!set.count(key)) {
      result.emplace_back(g);
      set.insert(key);
    }
  }
  *subgraphs = result;
}

267
void GraphPatternDetector::RemoveOverlappedMatch(
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    std::vector<subgraph_t>* subgraphs) {
  std::vector<subgraph_t> result;
  std::unordered_set<Node*> node_set;

  for (const auto& subgraph : *subgraphs) {
    bool valid = true;
    for (auto& item : subgraph) {
      if (node_set.count(item.second)) {
        valid = false;
        break;
      }
    }
    if (valid) {
      for (auto& item : subgraph) {
        node_set.insert(item.second);
      }
      result.push_back(subgraph);
    }
  }
  *subgraphs = result;
}

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
std::string PDPattern::DotString() const {
  using inference::analysis::Dot;
  Dot dot;
  int id = 0;
  // Create Nodes
  std::unordered_map<PDNode*, std::string> node2dot;
  for (const auto& node : nodes()) {
    std::string node_id = "Node" + std::to_string(id++);
    dot.AddNode(node_id, {}, node->name());
    node2dot[node.get()] = node_id;
  }
  // Create Edges
  for (const auto& edge : edges()) {
    if (!node2dot.count(edge.first) || !node2dot.count(edge.second)) {
      LOG(ERROR) << "no node " << edge.first << " " << edge.second;
      continue;
    }
    auto& src = node2dot.at(edge.first);
    auto& trg = node2dot.at(edge.second);
    dot.AddEdge(src, trg, {});
  }
  return dot.Build();
}

PDNode& PDNode::LinksTo(const std::vector<PDNode*>& others) {
  // extend outlinks.
  for (PDNode* x : others) {
    pattern_->AddEdge(this, x);
  }
  return *this;
}

PDNode& PDNode::LinksFrom(const std::vector<PDNode*>& others) {
  // extend outlinks.
  for (PDNode* x : others) {
    pattern_->AddEdge(x, this);
  }
  return *this;
}

Y
Yan Chunwei 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
PDNode* PDNode::assert_is_op() {
  asserts_.emplace_back([this](Node* x) { return x && x->IsOp(); });
  return this;
}
PDNode* PDNode::assert_is_op(const std::string& op_type) {
  asserts_.emplace_back([this, op_type](Node* x) {
    return x && x->IsOp() && x->Op()->Type() == op_type;
  });
  return this;
}
PDNode* PDNode::assert_is_var() {
  asserts_.emplace_back([this](Node* x) { return x && x->IsVar(); });
  return this;
}
PDNode* PDNode::assert_var_not_persistable() {
  assert_is_var();
  asserts_.emplace_back([this](Node* x) { return !x->Var()->Persistable(); });
  return this;
}
PDNode* PDNode::assert_is_persistable_var() {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) { return x->Var()->Persistable(); });
  return this;
}
PDNode* PDNode::assert_is_op_nth_input(const std::string& op_type,
                                       const std::string& argument, int nth) {
  assert_is_var();
  assert_is_op_input(op_type);
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->outputs) {
      if (IsNthInput(x, op, argument, nth)) return true;
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_is_op_nth_output(const std::string& op_type,
                                        const std::string& argument, int nth) {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->inputs) {
      if (IsNthOutput(x, op, argument, nth)) return true;
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_is_only_input_of_op(const std::string& op_type) {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->outputs) {
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->inputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_is_only_output_of_op(const std::string& op_type) {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->inputs) {
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type &&
          op->outputs.size() == 1) {
        return true;
      }
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_is_op_output(const std::string& op_type) {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->inputs) {
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
        return true;
      }
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_is_op_input(const std::string& op_type) {
  assert_is_var();
  asserts_.emplace_back([=](Node* x) {
    for (auto* op : x->outputs) {
      if (op && op->IsOp() && op->Op() && op->Op()->Type() == op_type) {
        return true;
      }
    }
    return false;
  });
  return this;
}
PDNode* PDNode::assert_op_has_n_inputs(const std::string& op_type, size_t n) {
  assert_is_op(op_type);
  asserts_.emplace_back([=](Node* x) { return x->inputs.size() == n; });
  return this;
}
PDNode* PDNode::assert_op_has_n_outputs(const std::string& op_type, size_t n) {
  assert_is_op(op_type);
  asserts_.emplace_back([=](Node* x) { return x->outputs.size() == n; });
  return this;
}
PDNode* PDNode::assert_more(PDNode::teller_t&& teller) {
  asserts_.emplace_back(std::move(teller));
  return this;
}

442 443 444
}  // namespace ir
}  // namespace framework
}  // namespace paddle