-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisual.py
41 lines (32 loc) · 1015 Bytes
/
visual.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from graphviz import Digraph
def trace(root):
nodes, edges = set(), set()
def build(v):
if v not in nodes:
nodes.add(v)
for child in v._prev:
edges.add((child, v))
build(child)
build(root)
return nodes, edges
def draw_dot(root, format="svg", rankdir="LR"):
"""
format: png | svg | ...
rankdir: TB (top to bottom graph) | LR (left to right)
"""
assert rankdir in ["LR", "TB"]
nodes, edges = trace(root)
dot = Digraph(
format=format, graph_attr={"rankdir": rankdir}
) # , node_attr={'rankdir': 'TB'})
for n in nodes:
dot.node(
name=str(id(n)),
label="{ data %.4f | grad %.4f }" % (n.data, n.grad),
shape="record",
)
if n._op:
dot.node(name=str(id(n)) + n._op, label=n._op)
dot.edge(str(id(n)) + n._op, str(id(n)))
[dot.edge(str(id(n1)), str(id(n2)) + n2._op) for n1, n2 in edges]
return dot