graphviz.py 7.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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.

import os
import random
M
minqiyang 已提交
17
import functools
18 19 20 21 22
import subprocess
import logging


def crepr(v):
23
    if isinstance(v, str):
24 25 26 27
        return '"%s"' % v
    return str(v)


28
class Rank:
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    def __init__(self, kind, name, priority):
        '''
        kind: str
        name: str
        priority: int
        '''
        self.kind = kind
        self.name = name
        self.priority = priority
        self.nodes = []

    def __str__(self):
        if not self.nodes:
            return ''

44 45 46 47 48 49
        return (
            '{'
            + 'rank={};'.format(self.kind)
            + ','.join([node.name for node in self.nodes])
            + '}'
        )
50 51


52
class Graph:
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 82 83 84 85 86 87 88 89
    rank_counter = 0

    def __init__(self, title, **attrs):
        self.title = title
        self.attrs = attrs
        self.nodes = []
        self.edges = []
        self.rank_groups = {}

    def code(self):
        return self.__str__()

    def rank_group(self, kind, priority):
        name = "rankgroup-%d" % Graph.rank_counter
        Graph.rank_counter += 1
        rank = Rank(kind, name, priority)
        self.rank_groups[name] = rank
        return name

    def node(self, label, prefix, description="", **attrs):
        node = Node(label, prefix, description, **attrs)

        if 'rank' in attrs:
            rank = self.rank_groups[attrs['rank']]
            del attrs['rank']
            rank.nodes.append(node)
        self.nodes.append(node)
        return node

    def edge(self, source, target, **attrs):
        edge = Edge(source, target, **attrs)
        self.edges.append(edge)
        return edge

    def compile(self, dot_path):
        file = open(dot_path, 'w')
        file.write(self.__str__())
90 91 92
        image_path = os.path.join(
            os.path.dirname(dot_path), dot_path[:-3] + "pdf"
        )
93
        cmd = ["dot", "-Tpdf", dot_path, "-o", image_path]
94 95 96 97 98 99
        subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
100 101 102 103 104 105
        logging.warning("write block debug graph to {}".format(image_path))
        return image_path

    def show(self, dot_path):
        image = self.compile(dot_path)
        cmd = ["open", image]
106 107 108 109 110 111
        subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
112 113

    def _rank_repr(self):
114 115 116 117 118 119
        ranks = sorted(
            self.rank_groups.items(),
            key=functools.cmp_to_key(
                lambda a, b: a[1].priority > b[1].priority
            ),
        )
120 121 122 123 124 125 126 127 128 129 130 131
        repr = []
        for x in ranks:
            repr.append(str(x[1]))
        return '\n'.join(repr) + '\n'

    def __str__(self):
        reprs = [
            'digraph G {',
            'title = {}'.format(crepr(self.title)),
        ]

        for attr in self.attrs:
132 133 134
            reprs.append(
                "{key}={value};".format(key=attr, value=crepr(self.attrs[attr]))
            )
135 136 137 138 139 140 141 142 143 144 145 146 147

        reprs.append(self._rank_repr())

        random.shuffle(self.nodes)
        reprs += [str(node) for node in self.nodes]

        for x in self.edges:
            reprs.append(str(x))

        reprs.append('}')
        return '\n'.join(reprs)


148
class Node:
149 150 151 152 153 154 155 156 157 158 159 160 161
    counter = 1

    def __init__(self, label, prefix, description="", **attrs):
        self.label = label
        self.name = "%s_%d" % (prefix, Node.counter)
        self.description = description
        self.attrs = attrs
        Node.counter += 1

    def __str__(self):
        reprs = '{name} [label={label} {extra} ];'.format(
            name=self.name,
            label=self.label,
162 163 164 165 166 167 168 169
            extra=','
            + ','.join(
                "%s=%s" % (key, crepr(value))
                for key, value in self.attrs.items()
            )
            if self.attrs
            else "",
        )
170 171 172
        return reprs


173
class Edge:
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    def __init__(self, source, target, **attrs):
        '''
        Link source to target.
        :param source: Node
        :param target: Node
        :param graph: Graph
        :param attrs: dic
        '''
        self.source = source
        self.target = target
        self.attrs = attrs

    def __str__(self):
        repr = "{source} -> {target} {extra}".format(
            source=self.source.name,
            target=self.target.name,
190 191 192 193 194 195 196 197 198
            extra=""
            if not self.attrs
            else "["
            + ','.join(
                "{}={}".format(attr[0], crepr(attr[1]))
                for attr in self.attrs.items()
            )
            + "]",
        )
199 200 201
        return repr


202
class GraphPreviewGenerator:
203 204 205 206 207 208 209 210 211 212
    '''
    Generate a graph image for ONNX proto.
    '''

    def __init__(self, title):
        # init graphviz graph
        self.graph = Graph(
            title,
            layout="dot",
            concentrate="true",
213 214
            rankdir="TB",
        )
215 216 217 218 219 220 221 222 223 224 225

        self.op_rank = self.graph.rank_group('same', 2)
        self.param_rank = self.graph.rank_group('same', 1)
        self.arg_rank = self.graph.rank_group('same', 0)

    def __call__(self, path='temp.dot', show=False):
        if not show:
            self.graph.compile(path)
        else:
            self.graph.show(path)

G
gongweibao 已提交
226
    def add_param(self, name, data_type, highlight=False):
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
        label = '\n'.join(
            [
                '<<table cellpadding="5">',
                '  <tr>',
                '    <td bgcolor="#2b787e">',
                '    <b>',
                name,
                '    </b>',
                '    </td>',
                '  </tr>',
                '  <tr>',
                '    <td>',
                str(data_type),
                '    </td>' '  </tr>',
                '</table>>',
            ]
        )
        return self.graph.node(
            label,
            prefix="param",
            description=name,
            shape="none",
            style="rounded,filled,bold",
            width="1.3",
            color="#148b97" if not highlight else "orange",
            fontcolor="#ffffff",
            fontname="Arial",
        )
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    def add_op(self, opType, **kwargs):
        highlight = False
        if 'highlight' in kwargs:
            highlight = kwargs['highlight']
            del kwargs['highlight']
        return self.graph.node(
            "<<B>%s</B>>" % opType,
            prefix="op",
            description=opType,
            shape="box",
            style="rounded, filled, bold",
            color="#303A3A" if not highlight else "orange",
            fontname="Arial",
            fontcolor="#ffffff",
            width="1.3",
271 272
            height="0.84",
        )
273 274

    def add_arg(self, name, highlight=False):
275 276 277 278 279 280 281 282 283 284
        return self.graph.node(
            crepr(name),
            prefix="arg",
            description=name,
            shape="box",
            style="rounded,filled,bold",
            fontname="Arial",
            fontcolor="#999999",
            color="#dddddd" if not highlight else "orange",
        )
285 286 287 288 289 290

    def add_edge(self, source, target, **kwargs):
        highlight = False
        if 'highlight' in kwargs:
            highlight = kwargs['highlight']
            del kwargs['highlight']
291 292 293 294 295 296
        return self.graph.edge(
            source,
            target,
            color="#00000" if not highlight else "orange",
            **kwargs
        )