net_drawer.py 3.5 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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 16
from __future__ import print_function

17 18 19 20 21
import argparse
import json
import logging
from collections import defaultdict

22 23
import paddle.fluid.core as core
import paddle.fluid.proto.framework_pb2 as framework_pb2
24
from paddle.fluid.log_helper import get_logger
25

26
logger = get_logger(__name__, logging.INFO)
27 28

try:
M
minqiyang 已提交
29
    from .graphviz import Graph
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
except ImportError:
    logger.info(
        'Cannot import graphviz, which is required for drawing a network. This '
        'can usually be installed in python with "pip install graphviz". Also, '
        'pydot requires graphviz to convert dot files to pdf: in ubuntu, this '
        'can usually be installed with "sudo apt-get install graphviz".')
    print('net_drawer will not run correctly. Please install the correct '
          'dependencies.')
    exit(0)

OP_STYLE = {
    'shape': 'oval',
    'color': '#0F9D58',
    'style': 'filled',
    'fontcolor': '#FFFFFF'
}

VAR_STYLE = {}

GRAPH_STYLE = {"rankdir": "TB", }

GRAPH_ID = 0


def unique_id():
    def generator():
        GRAPH_ID += 1
        return GRAPH_ID

    return generator


def draw_node(op):
    node = OP_STYLE
    node["name"] = op.type
    node["label"] = op.type
    return node


def draw_edge(var_parent, op, var, arg):
    edge = VAR_STYLE
    edge["label"] = "%s(%s)" % (var.parameter, arg)
    edge["head_name"] = op.type
    edge["tail_name"] = var_parent[arg]
    return edge


def parse_graph(program, graph, var_dict, **kwargs):

    # fill the known variables
    for block in program.blocks:
        for var in block.vars:
82
            if var not in var_dict:
83 84
                var_dict[var] = "Feed"

Y
Yang Yang(Tony) 已提交
85
    temp_id = 0
86 87 88 89
    proto = framework_pb2.ProgramDesc.FromString(
        program.desc.serialize_to_string())
    for block in proto.blocks:
        for op in block.ops:
Y
Yang Yang(Tony) 已提交
90 91
            op.type = op.type + "_" + str(temp_id)
            temp_id += 1
92 93 94 95 96 97
            graph.node(**draw_node(op))
            for o in op.outputs:
                for arg in o.arguments:
                    var_dict[arg] = op.type
            for e in op.inputs:
                for arg in e.arguments:
98
                    if arg in var_dict:
99
                        graph.edge(**draw_edge(var_dict, op, e, arg))
Y
Yang Yang(Tony) 已提交
100
        break  # only plot the first block
101 102


103
def draw_graph(startup_program, main_program, **kwargs):
104
    if "graph_attr" in kwargs:
105
        GRAPH_STYLE.update(kwargs[graph_attr])
106
    if "node_attr" in kwargs:
107
        OP_STYLE.update(kwargs[node_attr])
108
    if "edge_attr" in kwargs:
109 110 111 112 113 114
        VAR_STYLE.update(kwargs[edge_attr])

    graph_id = unique_id()
    filename = kwargs.get("filename")
    if filename == None:
        filename = str(graph_id) + ".gv"
M
minqiyang 已提交
115
    g = Graph(
116 117 118 119 120 121 122 123
        name=str(graph_id),
        filename=filename,
        graph_attr=GRAPH_STYLE,
        node_attr=OP_STYLE,
        edge_attr=VAR_STYLE,
        **kwargs)

    var_dict = {}
124 125
    parse_graph(startup_program, g, var_dict)
    parse_graph(main_program, g, var_dict)
126 127 128 129

    if filename != None:
        g.save()
    return g