graph_print_pass.cc 4.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/framework/details/graph_print_pass.h"
#include <string>
#include <vector>
D
dzhwinter 已提交
18
#include "paddle/fluid/framework/ir/graph_helper.h"
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

namespace paddle {
namespace framework {
namespace details {

class GraphvizVar : public GraphvizNode {
 public:
  GraphvizVar(ir::Node* n, const int& i) : GraphvizNode(n, i) {}
  friend std::ostream& operator<<(std::ostream& sout, const GraphvizVar& var) {
    sout << "var_" << var.id_ << " [label=\"" << var.node_->Name() << "\"]"
         << std::endl;
    return sout;
  }
};

class GraphvizOp : public GraphvizNode {
 public:
  GraphvizOp(ir::Node* n, const int& i) : GraphvizNode(n, i) {}
  friend std::ostream& operator<<(std::ostream& sout, const GraphvizOp& op) {
    sout << "op_" + std::to_string(op.id_) << " [label=\"" << op.node_->Name()
         << "\", shape=rect]" << std::endl;
    sout << op.stream_.str();
    return sout;
  }
  template <typename Callback>
  void AddEdge(const Callback& cb) {
    std::string op_name = "op_" + std::to_string(id_);
    for (auto var : node_->inputs) {
      std::string var_name = "var_" + std::to_string(cb(var));
      stream_ << var_name << "->" << op_name << std::endl;
    }
    for (auto var : node_->outputs) {
      std::string var_name = "var_" + std::to_string(cb(var));
      stream_ << op_name << "->" << var_name << std::endl;
    }
  }

D
dzhwinter 已提交
56 57 58 59 60
  template <typename Callback>
  void AddCustomEdge(const Callback& cb) {
    stream_ << cb() << std::endl;
  }

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
 private:
  std::ostringstream stream_;
};

template <typename T, typename Container>
std::vector<T*> FilterByNodeWrapper(const Container& con) {
  std::vector<T*> ret;
  for (auto& node : con) {
    auto i = dynamic_cast<T*>(node.get());
    if (i != nullptr) ret.emplace_back(i);
  }
  return ret;
}

std::unordered_map<ir::Node*, int> SSAGraphPrinterImpl::ToGraphvizNode(
    const ir::Graph& graph) const {
  // Convert to GraphvizNode format
  auto& graphviz_nodes = graph.Get<GraphvizNodes>(kGraphviz);
  graphviz_nodes.clear();
  std::unordered_map<ir::Node*, int> vars;
D
dzhwinter 已提交
81
  std::unordered_map<ir::Node*, GraphvizOp*> ops;
82 83 84 85 86 87 88
  int var_id = 0;
  int op_id = 0;
  for (auto& node : graph.Nodes()) {
    if (node->IsVar()) {
      graphviz_nodes.emplace(new GraphvizVar(node, var_id));
      vars.emplace(std::make_pair(node, var_id++));
    } else if (node->IsOp()) {
D
dzhwinter 已提交
89 90 91
      std::unique_ptr<GraphvizOp> op(new GraphvizOp(node, op_id++));
      ops[node] = op.get();
      graphviz_nodes.emplace(std::move(op));
92 93 94 95
    } else {
      PADDLE_THROW("Unknown op type");
    }
  }
D
dzhwinter 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

  // Detect circle. Draw circle in different lines
  std::vector<std::vector<ir::Node*>> circles;
  const std::string kCircleEdge = "[color=red,penwidth=3.0]";
  if (ir::FindCircleSubGraph(graph, &circles)) {
    VLOG(3) << "Graph has circle! circles count : " << circles.size();
    for (auto& circle : circles) {
      for (size_t i = 0; i < circle.size() - 1; ++i) {
        GraphvizOp* prev = ops[circle[i]];
        GraphvizOp* next = ops[circle[i + 1]];
        std::string prev_op = "op_" + std::to_string(prev->Id());
        std::string next_op = "op_" + std::to_string(next->Id());
        prev->AddCustomEdge([&]() -> std::string {
          return prev_op + "->" + next_op + kCircleEdge;
        });
      }
    }
  }
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 149 150
  return vars;
}

void SSAGraphPrinterImpl::Print(const ir::Graph& graph,
                                std::ostream& sout) const {
  auto vars = ToGraphvizNode(graph);
  auto& nodes = graph.Get<GraphvizNodes>(kGraphviz);

  sout << "digraph G {\n";
  for (auto& var : FilterByNodeWrapper<GraphvizVar>(nodes)) {
    sout << *var;
  }

  for (auto& op : FilterByNodeWrapper<GraphvizOp>(nodes)) {
    op->AddEdge([&vars](ir::Node* var) { return vars.at(var); });
    sout << *op;
  }
  sout << "}\n";
}

std::unique_ptr<ir::Graph> SSAGraphPrintPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  printer_.reset(new SSAGraphPrinterImpl());
  std::unique_ptr<std::ostream> fout(
      new std::ofstream(Get<std::string>(kGraphvizPath)));
  PADDLE_ENFORCE(fout->good() == true, "Failed to open file.");

  printer_->Print(*graph, *fout);
  return graph;
}

}  // namespace details
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(graph_print_pass, paddle::framework::details::SSAGraphPrintPass)
    .RequirePassAttr(paddle::framework::details::kGraphvizPath);