graph_viz_pass.cc 6.6 KB
Newer Older
X
Xin Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

15
#include "paddle/fluid/framework/ir/graph_viz_pass.h"
16

17 18
#include <fstream>
#include <ostream>
19
#include <string>
20

21
#include "paddle/fluid/framework/ir/graph_helper.h"
C
chengduo 已提交
22
#include "paddle/fluid/framework/ir/graph_printer.h"
23
#include "paddle/fluid/framework/op_proto_maker.h"
24
#include "paddle/fluid/framework/program_desc.h"
X
Xin Pan 已提交
25
#include "paddle/fluid/inference/analysis/dot.h"
26
#include "paddle/fluid/inference/analysis/helper.h"
X
Xin Pan 已提交
27 28 29 30

namespace paddle {
namespace framework {
namespace ir {
31
using inference::analysis::Dot;
32
namespace {
X
fix  
Xin Pan 已提交
33 34 35 36
std::string FormatName(const Node* node) {
  if (!node->IsOp() || !node->Op() ||
      !node->Op()->HasAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName())) {
    return node->Name();
37
  }
R
Ruibiao Chen 已提交
38
  const std::string full_scope = PADDLE_GET_CONST(
39
      std::string,
X
fix  
Xin Pan 已提交
40 41
      node->Op()->GetAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName()));
  return string::Sprintf("%s%s", full_scope.c_str(), node->Name().c_str());
42 43
}
}  // namespace
X
Xin Pan 已提交
44

45
void GraphVizPass::ApplyImpl(ir::Graph* graph) const {
46 47 48 49 50 51 52
  std::string optim_cache_dir;
  if (Has("optim_cache_dir")) {
    optim_cache_dir = Get<std::string>("optim_cache_dir");
    if (!optim_cache_dir.empty()) {
      paddle::inference::analysis::MakeDirIfNotExists(optim_cache_dir);
    }
  }
C
chengduo 已提交
53
  const std::string& graph_viz_path = Get<std::string>(kGraphvizPath);
M
minqiyang 已提交
54
  VLOG(3) << "draw IR graph viz to " << graph_viz_path;
X
Xin Pan 已提交
55
  std::unique_ptr<std::ostream> fout(new std::ofstream(graph_viz_path));
56
  PADDLE_ENFORCE_EQ(
57 58
      fout->good(),
      true,
59 60
      platform::errors::Unavailable(
          "Can not open file %s for printing the graph.", graph_viz_path));
X
Xin Pan 已提交
61 62
  std::ostream& sout = *fout;

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  // serialize only model file.
  std::string program_path;
  std::size_t found1 = graph_viz_path.find("_ir_");
  std::size_t found2 = graph_viz_path.find(".dot");
  if (found1 != std::string::npos && found2 != std::string::npos) {
    ProgramDesc program_desc;
    GraphToProgram(*graph, &program_desc);
    // TODO(wilber): GraphToProgram seems have bugs.
    for (size_t i = 0; i < program_desc.Size(); ++i) {
      for (size_t j = 0; j < program_desc.Block(i).OpSize(); ++j) {
        if (program_desc.Block(i).Op(j)->Type() == "tensorrt_engine") {
          program_desc.Block(i).Op(j)->RemoveAttr("sub_block");
        }
      }
    }
    std::string program_bytes = program_desc.Proto()->SerializeAsString();
    // rename from "17_ir_fc_fuse_pass.dot" to "fc_fuse_pass.pdmodel"
    program_path =
        graph_viz_path.substr(found1 + 4, found2 - found1 - 4) + ".pdmodel";
82 83 84
    if (!optim_cache_dir.empty()) {
      program_path = optim_cache_dir + "/" + program_path;
    }
85 86 87 88 89 90
    std::ofstream file(program_path.c_str(), std::ios::binary);
    file.write(program_bytes.c_str(), program_bytes.size());
    file.close();
    VLOG(3) << "serialize program to " << program_path;
  }

91 92 93 94
  std::unordered_map<const ir::Node*, std::string> node2dot;

  Dot dot;

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  const std::vector<Dot::Attr> op_attrs({
      Dot::Attr("style", "rounded,filled,bold"),  //
      Dot::Attr("shape", "box"),                  //
      Dot::Attr("color", "#303A3A"),              //
      Dot::Attr("fontcolor", "#ffffff"),          //
      Dot::Attr("width", "1.3"),                  //
      Dot::Attr("height", "0.84"),                //
      Dot::Attr("fontname", "Arial"),             //
  });
  const std::vector<Dot::Attr> arg_attrs({
      Dot::Attr("shape", "box"),                  //
      Dot::Attr("style", "rounded,filled,bold"),  //
      Dot::Attr("fontname", "Arial"),             //
      Dot::Attr("fillcolor", "#999999"),          //
      Dot::Attr("color", "#dddddd"),              //
  });

  const std::vector<Dot::Attr> param_attrs({
      Dot::Attr("shape", "box"),                  //
      Dot::Attr("style", "rounded,filled,bold"),  //
      Dot::Attr("fontname", "Arial"),             //
      Dot::Attr("color", "#148b97"),              //
      Dot::Attr("fontcolor", "#ffffff"),          //
  });

  const std::vector<Dot::Attr> marked_op_attrs(
121 122
      {Dot::Attr("style", "rounded,filled,bold"),
       Dot::Attr("shape", "box"),
123 124
       Dot::Attr("fillcolor", "yellow")});
  const std::vector<Dot::Attr> marked_var_attrs(
125 126
      {Dot::Attr("style", "filled,rounded"),
       Dot::Attr("shape", "box"),
127
       Dot::Attr("fillcolor", "yellow")});
128

129
  auto marked_nodes = ConsumeMarkedNodes(graph);
130 131
  // Create nodes
  for (const Node* n : graph->Nodes()) {
132
    std::string node_id = FormatName(n) + "(" + std::to_string(n->id()) + ")";
133 134 135 136 137
    if (n->IsOp()) {
      decltype(op_attrs) attr =
          marked_nodes.count(n) ? marked_op_attrs : op_attrs;
      dot.AddNode(node_id, attr, node_id);
    } else if (n->IsVar()) {
138 139 140 141 142 143 144 145 146 147 148
      if (n->Var() && n->Var()->GetType() == proto::VarType::LOD_TENSOR) {
        bool is_first = true;
        for (int64_t length : n->Var()->GetShape()) {
          if (is_first) {
            node_id += "\n" + std::to_string(length);
            is_first = false;
          } else {
            node_id += "," + std::to_string(length);
          }
        }
      }
149 150 151 152 153 154 155 156 157 158 159
      decltype(op_attrs)* attr;
      if (marked_nodes.count(n)) {
        attr = &marked_var_attrs;
      } else if (const_cast<Node*>(n)->Var() &&
                 const_cast<Node*>(n)->Var()->Persistable()) {
        attr = &param_attrs;
      } else {
        attr = &arg_attrs;
      }

      dot.AddNode(node_id, *attr, node_id);
X
Xin Pan 已提交
160
    }
161 162 163 164 165 166 167 168
    node2dot[n] = node_id;
  }
  // Create edges
  for (const Node* n : graph->Nodes()) {
    const auto& src_id = node2dot.at(n);
    for (auto* out : n->outputs) {
      const auto& trg_id = node2dot.at(out);
      dot.AddEdge(src_id, trg_id, {});
X
Xin Pan 已提交
169 170 171
    }
  }

172
  sout << dot.Build();
X
Xin Pan 已提交
173
}
X
Xin Pan 已提交
174

175 176 177 178 179 180 181 182 183 184 185
GraphVizPass::marked_nodes_t GraphVizPass::ConsumeMarkedNodes(
    Graph* graph) const {
  marked_nodes_t res;
  if (graph->Has(kGraphvizMarkedNodeAttr)) {
    auto& attr = graph->Get<marked_nodes_t>(kGraphvizMarkedNodeAttr);
    res = attr;
    attr.clear();
  }
  return res;
}

X
Xin Pan 已提交
186 187 188
}  // namespace ir
}  // namespace framework
}  // namespace paddle
X
Xin Pan 已提交
189

X
Xin Pan 已提交
190
REGISTER_PASS(graph_viz_pass, paddle::framework::ir::GraphVizPass)
C
chengduo 已提交
191
    .RequirePassAttr(paddle::framework::ir::kGraphvizPath);