3 from __future__
import absolute_import
4 from __future__
import division
5 from __future__
import print_function
6 from __future__
import unicode_literals
10 from collections
import defaultdict
11 from caffe2.python
import utils
13 logger = logging.getLogger(__name__)
14 logger.setLevel(logging.INFO)
20 'Cannot import pydot, which is required for drawing a network. This ' 21 'can usually be installed in python with "pip install pydot". Also, ' 22 'pydot requires graphviz to convert dot files to pdf: in ubuntu, this ' 23 'can usually be installed with "sudo apt-get install graphviz".' 26 'net_drawer will not run correctly. Please install the correct ' 31 from caffe2.proto
import caffe2_pb2
37 'fontcolor':
'#FFFFFF' 39 BLOB_STYLE = {
'shape':
'octagon'}
42 def _rectify_operator_and_name(operators_or_net, name):
43 """Gets the operators and name for the pydot graph.""" 44 if isinstance(operators_or_net, caffe2_pb2.NetDef):
45 operators = operators_or_net.op
47 name = operators_or_net.name
48 elif hasattr(operators_or_net,
'Proto'):
49 net = operators_or_net.Proto()
50 if not isinstance(net, caffe2_pb2.NetDef):
52 "Expecting NetDef, but got {}".format(type(net)))
57 operators = operators_or_net
60 return operators, name
63 def _escape_label(name):
65 return json.dumps(name)
68 def GetOpNodeProducer(append_output, **kwargs):
69 def ReallyGetOpNode(op, op_id):
71 node_name =
'%s/%s (op#%d)' % (op.name, op.type, op_id)
73 node_name =
'%s (op#%d)' % (op.type, op_id)
75 for output_name
in op.output:
76 node_name +=
'\n' + output_name
77 return pydot.Node(node_name, **kwargs)
78 return ReallyGetOpNode
87 if node_producer
is None:
88 node_producer = GetOpNodeProducer(
False, **OP_STYLE)
89 operators, name = _rectify_operator_and_name(operators_or_net, name)
90 graph = pydot.Dot(name, rankdir=rankdir)
92 pydot_node_counts = defaultdict(int)
93 for op_id, op
in enumerate(operators):
94 op_node = node_producer(op, op_id)
95 graph.add_node(op_node)
99 for input_name
in op.input:
100 if input_name
not in pydot_nodes:
101 input_node = pydot.Node(
103 input_name + str(pydot_node_counts[input_name])),
104 label=_escape_label(input_name),
107 pydot_nodes[input_name] = input_node
109 input_node = pydot_nodes[input_name]
110 graph.add_node(input_node)
111 graph.add_edge(pydot.Edge(input_node, op_node))
112 for output_name
in op.output:
113 if output_name
in pydot_nodes:
115 pydot_node_counts[output_name] += 1
116 output_node = pydot.Node(
118 output_name + str(pydot_node_counts[output_name])),
119 label=_escape_label(output_name),
122 pydot_nodes[output_name] = output_node
123 graph.add_node(output_node)
124 graph.add_edge(pydot.Edge(op_node, output_node))
132 minimal_dependency=False,
135 """Different from GetPydotGraph, hide all blob nodes and only show op nodes. 137 If minimal_dependency is set as well, for each op, we will only draw the 138 edges to the minimal necessary ancestors. For example, if op c depends on 139 op a and b, and op b depends on a, then only the edge b->c will be drawn 140 because a->c will be implied. 142 if node_producer
is None:
143 node_producer = GetOpNodeProducer(
False, **OP_STYLE)
144 operators, name = _rectify_operator_and_name(operators_or_net, name)
145 graph = pydot.Dot(name, rankdir=rankdir)
149 op_ancestry = defaultdict(set)
150 for op_id, op
in enumerate(operators):
151 op_node = node_producer(op, op_id)
152 graph.add_node(op_node)
155 blob_parents[input_name]
for input_name
in op.input
156 if input_name
in blob_parents
158 op_ancestry[op_node].update(parents)
160 op_ancestry[op_node].update(op_ancestry[node])
161 if minimal_dependency:
165 [node
not in op_ancestry[other_node]
166 for other_node
in parents]
168 graph.add_edge(pydot.Edge(node, op_node))
172 graph.add_edge(pydot.Edge(node, op_node))
174 for output_name
in op.output:
175 blob_parents[output_name] = op_node
179 def GetOperatorMapForPlan(plan_def):
181 for net_id, net
in enumerate(plan_def.network):
182 if net.HasField(
'name'):
183 operator_map[plan_def.name +
"_" + net.name] = net.op
185 operator_map[plan_def.name +
"_network_%d" % net_id] = net.op
189 def _draw_nets(nets, g):
191 for i, net
in enumerate(nets):
192 nodes.append(pydot.Node(_escape_label(net)))
193 g.add_node(nodes[-1])
195 g.add_edge(pydot.Edge(nodes[-2], nodes[-1]))
199 def _draw_steps(steps, g, skip_step_edges=False):
200 kMaxParallelSteps = 3
203 label = [step.name +
'\n']
205 label.append(
'Reporter: {}'.format(step.report_net))
206 if step.should_stop_blob:
207 label.append(
'Stopper: {}'.format(step.should_stop_blob))
208 if step.concurrent_substeps:
209 label.append(
'Concurrent')
212 return '\n'.join(label)
214 def substep_edge(start, end):
215 return pydot.Edge(start, end, arrowhead=
'dot', style=
'dashed')
218 for i, step
in enumerate(steps):
219 parallel = step.concurrent_substeps
221 nodes.append(pydot.Node(_escape_label(get_label()), **OP_STYLE))
222 g.add_node(nodes[-1])
224 if i > 0
and not skip_step_edges:
225 g.add_edge(pydot.Edge(nodes[-2], nodes[-1]))
228 sub_nodes = _draw_nets(step.network, g)
231 sub_nodes = _draw_steps(
232 step.substep[:kMaxParallelSteps], g, skip_step_edges=
True)
234 sub_nodes = _draw_steps(step.substep, g)
236 raise ValueError(
'invalid step')
240 g.add_edge(substep_edge(nodes[-1], sn))
241 if len(step.substep) > kMaxParallelSteps:
242 ellipsis = pydot.Node(
'{} more steps'.format(
243 len(step.substep) - kMaxParallelSteps), **OP_STYLE)
245 g.add_edge(substep_edge(nodes[-1], ellipsis))
247 g.add_edge(substep_edge(nodes[-1], sub_nodes[0]))
252 def GetPlanGraph(plan_def, name=None, rankdir='TB'):
253 graph = pydot.Dot(name, rankdir=rankdir)
254 _draw_steps(plan_def.execution_step, graph)
258 def GetGraphInJson(operators_or_net, output_filepath):
259 operators, _ = _rectify_operator_and_name(operators_or_net,
None)
260 blob_strid_to_node_id = {}
261 node_name_counts = defaultdict(int)
264 for op_id, op
in enumerate(operators):
265 op_label = op.name +
'/' + op.type
if op.name
else op.type
266 op_node_id = len(nodes)
273 for input_name
in op.input:
274 strid = _escape_label(
275 input_name + str(node_name_counts[input_name]))
276 if strid
not in blob_strid_to_node_id:
282 blob_strid_to_node_id[strid] = len(nodes)
283 nodes.append(input_node)
285 input_node = nodes[blob_strid_to_node_id[strid]]
287 'source': blob_strid_to_node_id[strid],
290 for output_name
in op.output:
291 strid = _escape_label(
292 output_name + str(node_name_counts[output_name]))
293 if strid
in blob_strid_to_node_id:
295 node_name_counts[output_name] += 1
296 strid = _escape_label(
297 output_name + str(node_name_counts[output_name]))
299 if strid
not in blob_strid_to_node_id:
302 'label': output_name,
305 blob_strid_to_node_id[strid] = len(nodes)
306 nodes.append(output_node)
308 'source': op_node_id,
309 'target': blob_strid_to_node_id[strid]
312 with open(output_filepath,
'w')
as f:
313 json.dump({
'nodes': nodes,
'edges': edges}, f)
319 b
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00' 320 b
'\x01\x01\x00\x00\x00\x007n\xf9$\x00\x00\x00\nIDATx\x9cc`\x00\x00' 321 b
'\x00\x02\x00\x01H\xaf\xa4q\x00\x00\x00\x00IEND\xaeB`\x82')
326 Invokes `func` (e.g. GetPydotGraph) with args. If anything fails - returns 327 and empty image instead of throwing Exception 330 graph = func(*args, **kwargs)
331 if not isinstance(graph, pydot.Dot):
332 raise ValueError(
"func is expected to return pydot.Dot")
333 return graph.create_png()
334 except Exception
as e:
335 logger.error(
"Failed to draw graph: {}".format(e))
336 return _DummyPngImage
340 parser = argparse.ArgumentParser(description=
"Caffe2 net drawer.")
344 help=
"The input protobuf file." 348 type=str, default=
"",
349 help=
"The prefix to be added to the output filename." 352 "--minimal", action=
"store_true",
353 help=
"If set, produce a minimal visualization." 356 "--minimal_dependency", action=
"store_true",
357 help=
"If set, only draw minimal dependency." 360 "--append_output", action=
"store_true",
361 help=
"If set, append the output blobs to the operator names.")
363 "--rankdir", type=str, default=
"LR",
364 help=
"The rank direction of the pydot graph." 366 args = parser.parse_args()
367 with open(args.input,
'r') as fid: 371 caffe2_pb2.PlanDef: lambda x: GetOperatorMapForPlan(x),
372 caffe2_pb2.NetDef:
lambda x: {x.name: x.op},
375 for key, operators
in graphs.items():
380 rankdir=args.rankdir,
381 node_producer=GetOpNodeProducer(args.append_output, **OP_STYLE),
382 minimal_dependency=args.minimal_dependency)
384 graph = GetPydotGraph(
387 rankdir=args.rankdir,
388 node_producer=GetOpNodeProducer(args.append_output, **OP_STYLE))
389 filename = args.output_prefix + graph.get_name() +
'.dot' 390 graph.write(filename, format=
'raw')
391 pdf_filename = filename[:-3] +
'pdf' 393 graph.write_pdf(pdf_filename)
396 'Error when writing out the pdf file. Pydot requires graphviz ' 397 'to convert dot files to pdf, and you may not have installed ' 398 'graphviz. On ubuntu this can usually be installed with "sudo ' 399 'apt-get install graphviz". We have generated the .dot file ' 400 'but will not be able to generate pdf file for now.' 404 if __name__ ==
'__main__':
def GetPydotGraphMinimal(operators_or_net, name=None, rankdir='LR', minimal_dependency=False, node_producer=None)
def GetContentFromProtoString(s, function_map)
def GetGraphPngSafe(func, args, kwargs)