-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgprint.py
1408 lines (1176 loc) · 41 KB
/
gprint.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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Utilities to generate a graphical representation for a graph."""
import json
import os
from hrepr import hrepr
from myia.abstract import (
AbstractValue, AbstractScalar, AbstractFunction, AbstractTuple,
AbstractList, AbstractClass, AbstractJTagged, AbstractArray,
GraphFunction, PartialApplication, TypedPrimitive, PrimitiveFunction,
MetaGraphFunction,
VALUE, InferenceError, ANYTHING, PendingTentative
)
from myia.dtype import Type, Bool, Int, Float, Tuple, List, Class, Function, \
TypeMeta, UInt, Array
from myia.utils import OrderedSet, UNKNOWN
try:
from myia.dtype import JTagged
except ImportError:
class JTagged:
pass
from myia.abstract import Reference, VirtualReference, Context
from myia.info import DebugInfo, About
from myia.ir import ANFNode, Apply, Constant, Graph, GraphCloner, \
ParentProxy, GraphManager, manage
from myia.parser import Location
from myia.prim import ops as primops
from myia.opt import LocalPassOptimizer, pattern_replacer, NodeMap
from myia.utils import Registry, NS
from myia.utils.unify import Var, SVar, var, FilterVar
from myia.vm import VMFrame, Closure
from myia.debug.label import NodeLabeler, short_labeler, \
short_relation_symbols, CosmeticPrimitive
from myia.debug.utils import mixin
gcss_path = f'{os.path.dirname(__file__)}/graph.css'
gcss = open(gcss_path).read()
mcss_path = f'{os.path.dirname(__file__)}/myia.css'
mcss = open(mcss_path).read()
def _has_error(dbg):
# Whether an error occurred somewhere in a DebugInfo
if dbg.errors:
return True
elif dbg.about:
return _has_error(dbg.about.debug)
else:
return False
class GraphPrinter:
"""Utility to generate a graphical representation for a graph.
This is intended to be used as a base class for classes that
specialize over particular graph structures.
"""
def __init__(self,
cyoptions,
tooltip_gen=None,
extra_style=None):
"""Initialize GraphPrinter."""
# Nodes and edges are accumulated in these lists
self.nodes = []
self.edges = []
self.cyoptions = cyoptions
self.tooltip_gen = tooltip_gen
self.extra_style = extra_style or ''
def id(self, x):
"""Return the id associated to x."""
return f'X{id(x)}'
def fresh_id(self):
"""Return sequential identifier to guarantee a unique node."""
self.currid += 1
return f'Y{self.currid}'
def _strip_cosmetic(self, node):
while node and node.debug.about \
and node.debug.about.relation == 'cosmetic':
node = node.debug.about.debug.obj
return node
def cynode(self, id, label, classes, parent=None, node=None):
"""Build data structure for a node in cytoscape."""
if not isinstance(id, str):
if node is None:
node = id
id = self.id(id)
data = {'id': id, 'label': str(label)}
if self.tooltip_gen and node:
ttip = self.tooltip_gen(self._strip_cosmetic(node))
if ttip is not None:
if not isinstance(ttip, str):
ttip = str(hrepr(ttip))
data['tooltip'] = ttip
if parent:
parent = parent if isinstance(parent, str) else self.id(parent)
data['parent'] = parent
self.nodes.append({'data': data, 'classes': classes})
def cyedge(self, src_id, dest_id, label):
"""Build data structure for an edge in cytoscape."""
cl = 'input-edge'
if isinstance(label, tuple):
label, cl = label
if not isinstance(label, str):
label = str(label)
if not isinstance(dest_id, str):
dest_id = self.id(dest_id)
if not isinstance(src_id, str):
src_id = self.id(src_id)
data = {
'id': f'{dest_id}-{src_id}-{label}',
'label': label,
'source': dest_id,
'target': src_id
}
self.edges.append({'data': data, 'classes': cl})
@classmethod
def __hrepr_resources__(cls, H):
"""Require the cytoscape plugin for buche."""
return (H.style(mcss),
H.bucheRequire(name='cytoscape',
channels='cytoscape',
components='cytoscape-graph'))
def __hrepr__(self, H, hrepr):
"""Return HTML representation (uses buche-cytoscape)."""
opts = {
'style': gcss + self.extra_style,
'elements': self.nodes + self.edges,
}
return H.cytoscapeGraph(
H.script(
json.dumps({**opts, **self.cyoptions}),
type='buche/configure'
),
width=hrepr.config.graph_width or '800px',
height=hrepr.config.graph_height or '500px',
interactive=True,
)
class MyiaGraphPrinter(GraphPrinter):
"""
Utility to generate a graphical representation for a graph.
Attributes:
duplicate_constants: Whether to create a separate node for
every instance of the same constant.
duplicate_free_variables: Whether to create a separate node
to represent the use of a free variable, or point directly
to that node in a different graph.
function_in_node: Whether to print, when possible, the name
of a node's operation directly in the node's label instead
of creating a node for the operation and drawing an edge
to it.
follow_references: Whether to also print graphs that are
called by this graph.
"""
def __init__(self,
entry_points,
*,
duplicate_constants=False,
duplicate_free_variables=False,
function_in_node=False,
follow_references=False,
tooltip_gen=None,
class_gen=None,
extra_style=None,
beautify=True):
"""Initialize a MyiaGraphPrinter."""
super().__init__(
{
'layout': {
'name': 'dagre',
'rankDir': 'TB'
}
},
tooltip_gen=tooltip_gen,
extra_style=extra_style
)
# Graphs left to process
if beautify:
self.graphs = set()
self.focus = set()
for g in entry_points:
self._import_graph(g)
else:
self.graphs = set(entry_points)
self.focus = set(self.graphs)
self.beautify = beautify
self.duplicate_constants = duplicate_constants
self.duplicate_free_variables = duplicate_free_variables
self.function_in_node = function_in_node
self.follow_references = follow_references
self.labeler = NodeLabeler(
function_in_node=function_in_node,
relation_symbols=short_relation_symbols
)
self._class_gen = class_gen
# Nodes processed
self.processed = set()
# Nodes left to process
self.pool = set()
# Nodes that are to be colored as return nodes
self.returns = set()
# IDs for duplicated constants
self.currid = 0
def _import_graph(self, graph):
mng = manage(graph, weak=True)
graphs = set()
parents = mng.parents
g = graph
clone = GraphCloner(total=True, relation='cosmetic')
while g:
clone.add_clone(g)
graphs.add(g)
g = parents[g]
self.graphs |= {clone[g] for g in graphs}
self.focus.add(clone[graph])
def name(self, x):
"""Return the name of a node."""
return self.labeler.name(x, force=True)
def label(self, node, fn_label=None):
"""Return the label to give to a node."""
return self.labeler.label(node, None, fn_label=fn_label)
def const_fn(self, node):
"""
Return name of function, if constant.
Given an `Apply` node of a constant function, return the
name of that function, otherwise return None.
"""
return self.labeler.const_fn(node)
def add_graph(self, g):
"""Create a node for a graph."""
if g in self.processed:
return
if self.beautify:
g = cosmetic_transformer(g)
name = self.name(g)
argnames = [self.name(p) for p in g.parameters]
lbl = f'{name}({", ".join(argnames)})'
classes = ['function', 'focus' if g in self.focus else '']
self.cynode(id=g, label=lbl, classes=' '.join(classes))
self.processed.add(g)
def process_node_generic(self, node, g, cl):
"""Create node and edges for a node."""
lbl = self.label(node)
self.cynode(id=node, label=lbl, parent=g, classes=cl)
fn = node.inputs[0] if node.inputs else None
if fn and fn.is_constant_graph():
self.graphs.add(fn.value)
for inp in node.inputs:
if inp.is_constant_graph():
self.cyedge(src_id=g, dest_id=inp.value, label=('', 'use-edge'))
edges = []
if fn and not (fn.is_constant() and self.function_in_node):
edges.append((node, 'F', fn))
edges += [(node, i + 1, inp)
for i, inp in enumerate(node.inputs[1:]) or []]
self.process_edges(edges)
def class_gen(self, node, cl=None):
"""Generate the class name for this node."""
g = node.graph
if cl is not None:
pass
elif node in self.returns:
cl = 'output'
elif node.is_parameter():
cl = 'input'
if node not in g.parameters:
cl += ' unlisted'
elif node.is_constant():
cl = 'constant'
elif node.is_special():
cl = f'special-{type(node.special).__name__}'
else:
cl = 'intermediate'
if _has_error(node.debug):
cl += ' error'
if self._class_gen:
return self._class_gen(self._strip_cosmetic(node), cl)
else:
return cl
def process_node(self, node):
"""Create node and edges for a node."""
if node in self.processed:
return
g = node.graph
self.follow(node)
cl = self.class_gen(node)
if g and g not in self.processed:
self.add_graph(g)
if node.inputs and node.inputs[0].is_constant():
fn = node.inputs[0].value
if fn in cosmetics:
cosmetics[fn](self, node, g, cl)
elif hasattr(fn, 'graph_display'):
fn.graph_display(self, node, g, cl)
else:
self.process_node_generic(node, g, cl)
else:
self.process_node_generic(node, g, cl)
self.processed.add(node)
def process_edges(self, edges):
"""Create edges."""
for edge in edges:
src, lbl, dest = edge
if dest.is_constant() and self.duplicate_constants:
self.follow(dest)
cid = self.fresh_id()
self.cynode(id=cid,
parent=src.graph,
label=self.label(dest),
classes=self.class_gen(dest, 'constant'),
node=dest)
self.cyedge(src_id=src, dest_id=cid, label=lbl)
elif self.duplicate_free_variables and \
src.graph and dest.graph and \
src.graph is not dest.graph:
self.pool.add(dest)
cid = self.fresh_id()
self.cynode(id=cid,
parent=src.graph,
label=self.labeler.label(dest, force=True),
classes=self.class_gen(dest, 'freevar'),
node=dest)
self.cyedge(src_id=src, dest_id=cid, label=lbl)
self.cyedge(src_id=cid, dest_id=dest, label=(lbl, 'link-edge'))
self.cyedge(src_id=src.graph, dest_id=dest.graph,
label=('', 'nest-edge'))
else:
self.pool.add(dest)
self.cyedge(src_id=src, dest_id=dest, label=lbl)
def process_graph(self, g):
"""Process a graph."""
self.add_graph(g)
for inp in g.parameters:
self.process_node(inp)
if not g.return_:
return
ret = g.return_.inputs[1]
if not ret.is_apply() or ret.graph is not g:
ret = g.return_
self.returns.add(ret)
self.pool.add(ret)
while self.pool:
node = self.pool.pop()
self.process_node(node)
def process(self):
"""Process all graphs in entry_points."""
if self.nodes or self.edges:
return
while self.graphs:
g = self.graphs.pop()
self.process_graph(g)
return self.nodes, self.edges
def follow(self, node):
"""Add this node's graph if follow_references is True."""
if node.is_constant_graph() and self.follow_references:
self.graphs.add(node.value)
class MyiaNodesPrinter(GraphPrinter):
def __init__(self,
nodes,
*,
duplicate_constants=True,
duplicate_free_variables=True,
function_in_node=True,
tooltip_gen=None,
class_gen=None,
extra_style=None):
super().__init__(
{
'layout': {
'name': 'dagre',
'rankDir': 'TB'
}
},
tooltip_gen=tooltip_gen,
extra_style=extra_style
)
self.duplicate_constants = duplicate_constants
self.duplicate_free_variables = duplicate_free_variables
self.function_in_node = function_in_node
self.labeler = NodeLabeler(
function_in_node=function_in_node,
relation_symbols=short_relation_symbols
)
self._class_gen = class_gen
self.todo = set(nodes)
self.graphs = {node.graph for node in nodes if node.graph}
self.focus = set()
# Nodes that are to be colored as return nodes
self.returns = {node for node in nodes
if node.graph and node is node.graph.return_}
# IDs for duplicated constants
self.currid = 0
def name(self, x):
"""Return the name of a node."""
return self.labeler.name(x, force=True)
def label(self, node, fn_label=None):
"""Return the label to give to a node."""
return self.labeler.label(node, None, fn_label=fn_label)
def const_fn(self, node):
"""
Return name of function, if constant.
Given an `Apply` node of a constant function, return the
name of that function, otherwise return None.
"""
return self.labeler.const_fn(node)
def add_graph(self, g):
"""Create a node for a graph."""
name = self.name(g)
argnames = [self.name(p) for p in g.parameters]
lbl = f'{name}({", ".join(argnames)})'
classes = ['function', 'focus' if g in self.focus else '']
self.cynode(id=g, label=lbl, classes=' '.join(classes))
# self.processed.add(g)
def process_node_generic(self, node, g, cl):
"""Create node and edges for a node."""
if node.is_constant() and self.duplicate_constants:
return
lbl = self.label(node)
self.cynode(id=node, label=lbl, parent=g, classes=cl)
fn = node.inputs[0] if node.inputs else None
if fn and fn.is_constant_graph():
self.graphs.add(fn.value)
for inp in node.inputs:
if inp.is_constant_graph():
self.cyedge(src_id=g, dest_id=inp.value, label=('', 'use-edge'))
edges = []
if fn and not (fn.is_constant() and self.function_in_node):
edges.append((node, 'F', fn))
edges += [(node, i + 1, inp)
for i, inp in enumerate(node.inputs[1:]) or []]
self.process_edges(edges)
def class_gen(self, node, cl=None):
"""Generate the class name for this node."""
g = node.graph
if cl is not None:
pass
elif node in self.returns:
cl = 'output'
elif node.is_parameter():
cl = 'input'
if node not in g.parameters:
cl += ' unlisted'
elif node.is_constant():
cl = 'constant'
elif node.is_special():
cl = f'special-{type(node.special).__name__}'
else:
cl = 'intermediate'
if _has_error(node.debug):
cl += ' error'
if self._class_gen:
return self._class_gen(self._strip_cosmetic(node), cl)
else:
return cl
def process_node(self, node):
"""Create node and edges for a node."""
# if node in self.processed:
# return
g = node.graph
# self.follow(node)
cl = self.class_gen(node)
if node.inputs and node.inputs[0].is_constant():
fn = node.inputs[0].value
if fn in cosmetics:
cosmetics[fn](self, node, g, cl)
elif hasattr(fn, 'graph_display'):
fn.graph_display(self, node, g, cl)
else:
self.process_node_generic(node, g, cl)
else:
self.process_node_generic(node, g, cl)
def process_edges(self, edges):
"""Create edges."""
for edge in edges:
src, lbl, dest = edge
if dest not in self.todo:
continue
if dest.is_constant() and self.duplicate_constants:
cid = self.fresh_id()
self.cynode(id=cid,
parent=src.graph,
label=self.label(dest),
classes=self.class_gen(dest, 'constant'),
node=dest)
self.cyedge(src_id=src, dest_id=cid, label=lbl)
elif self.duplicate_free_variables and \
src.graph and dest.graph and \
src.graph is not dest.graph:
cid = self.fresh_id()
self.cynode(id=cid,
parent=src.graph,
label=self.labeler.label(dest, force=True),
classes=self.class_gen(dest, 'freevar'),
node=dest)
self.cyedge(src_id=src, dest_id=cid, label=lbl)
self.cyedge(src_id=cid, dest_id=dest, label=(lbl, 'link-edge'))
self.cyedge(src_id=src.graph, dest_id=dest.graph,
label=('', 'nest-edge'))
else:
self.cyedge(src_id=src, dest_id=dest, label=lbl)
def process(self):
"""Process all graphs in entry_points."""
if self.nodes or self.edges:
return
for g in self.graphs:
self.add_graph(g)
for node in self.todo:
self.process_node(node)
return self.nodes, self.edges
cosmetics = Registry()
@cosmetics.register(primops.return_)
def _cosmetic_node_return(self, node, g, cl):
"""Create node and edges for `return ...`."""
self.cynode(id=node, label='', parent=g, classes='const_output')
ret = node.inputs[1]
self.process_edges([(node, '', ret)])
class GraphCosmeticPrimitive(CosmeticPrimitive):
"""Cosmetic primitive that prints pretty in graphs.
Attributes:
on_edge: Whether to display the label on the edge.
"""
def __init__(self, label, on_edge=False):
"""Initialize a GraphCosmeticPrimitive."""
super().__init__(label)
self.on_edge = on_edge
def graph_display(self, gprint, node, g, cl):
"""Display a node in cytoscape graph."""
if gprint.function_in_node and self.on_edge:
lbl = gprint.label(node, '')
gprint.cynode(id=node, label=lbl, parent=g, classes=cl)
gprint.process_edges([(node,
(self.label, 'fn-edge'),
node.inputs[1])])
else:
gprint.process_node_generic(node, g, cl)
make_tuple = GraphCosmeticPrimitive('(...)')
X = Var('X')
Y = Var('Y')
Xs = SVar(Var())
V = var(lambda x: x.is_constant())
V1 = var(lambda x: x.is_constant())
V2 = var(lambda x: x.is_constant())
L = var(lambda x: x.is_constant_graph())
@pattern_replacer(primops.make_tuple, Xs)
def _opt_fancy_make_tuple(optimizer, node, equiv):
xs = equiv[Xs]
ct = Constant(GraphCosmeticPrimitive('(...)'))
with About(node.debug, 'cosmetic'):
return Apply([ct, *xs], node.graph)
@pattern_replacer(primops.tuple_getitem, X, V)
def _opt_fancy_getitem(optimizer, node, equiv):
x = equiv[X]
v = equiv[V]
ct = Constant(GraphCosmeticPrimitive(f'[{v.value}]', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.resolve, V1, V2)
def _opt_fancy_resolve(optimizer, node, equiv):
ns = equiv[V1]
name = equiv[V2]
with About(node.debug, 'cosmetic'):
lbl = f'{ns.value.label}.{name.value}'
ct = Constant(GraphCosmeticPrimitive(lbl))
return ct
@pattern_replacer(primops.getattr, X, V)
def _opt_fancy_getattr(optimizer, node, equiv):
x = equiv[X]
v = equiv[V]
ct = Constant(GraphCosmeticPrimitive(f'{v.value}', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.array_map, V, Xs)
def _opt_fancy_array_map(optimizer, node, equiv):
xs = equiv[Xs]
v = equiv[V]
if v.is_constant_graph():
return node
name = short_labeler.label(v)
ct = Constant(GraphCosmeticPrimitive(f'[{name}]'))
with About(node.debug, 'cosmetic'):
return Apply([ct, *xs], node.graph)
@pattern_replacer(primops.distribute, X, V)
def _opt_fancy_distribute(optimizer, node, equiv):
x = equiv[X]
v = equiv[V]
ct = Constant(GraphCosmeticPrimitive(f'shape→{v.value}', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.scalar_to_array, X)
def _opt_fancy_scalar_to_array(optimizer, node, equiv):
x = equiv[X]
ct = Constant(GraphCosmeticPrimitive(f'to_array', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.array_to_scalar, X)
def _opt_fancy_array_to_scalar(optimizer, node, equiv):
x = equiv[X]
ct = Constant(GraphCosmeticPrimitive(f'to_scalar', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.transpose, X, V)
def _opt_fancy_transpose(optimizer, node, equiv):
if equiv[V].value == (1, 0):
x = equiv[X]
ct = Constant(GraphCosmeticPrimitive(f'T', on_edge=True))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
else:
return node
@pattern_replacer(primops.array_reduce, primops.scalar_add, X, V)
def _opt_fancy_sum(optimizer, node, equiv):
x = equiv[X]
shp = equiv[V].value
ct = Constant(GraphCosmeticPrimitive(f'sum {"x".join(map(str, shp))}'))
with About(node.debug, 'cosmetic'):
return Apply([ct, x], node.graph)
@pattern_replacer(primops.distribute, (primops.scalar_to_array, V), X)
def _opt_distributed_constant(optimizer, node, equiv):
return equiv[V]
def cosmetic_transformer(g):
"""Transform a graph so that it looks nicer.
The resulting graph is not a valid one to run, because it may contain nodes
with fake functions that only serve a cosmetic purpose.
"""
spec = (
_opt_distributed_constant,
_opt_fancy_make_tuple,
_opt_fancy_getitem,
_opt_fancy_resolve,
_opt_fancy_getattr,
_opt_fancy_array_map,
_opt_fancy_distribute,
_opt_fancy_transpose,
_opt_fancy_sum,
# _opt_fancy_scalar_to_array,
_opt_fancy_array_to_scalar,
# careful=True
)
nmap = NodeMap()
for opt in spec:
nmap.register(getattr(opt, 'interest', None), opt)
opt = LocalPassOptimizer(nmap)
opt(g)
return g
@mixin(Graph)
class _Graph:
@classmethod
def __hrepr_resources__(cls, H):
"""Require the cytoscape plugin for buche."""
return GraphPrinter.__hrepr_resources__(H)
def __hrepr__(self, H, hrepr):
"""Return HTML representation (uses buche-cytoscape)."""
if hrepr.config.depth > 1 and not hrepr.config.graph_expand_all:
label = short_labeler.label(self, True)
return H.span['node', f'node-Graph'](label)
dc = hrepr.config.duplicate_constants
dfv = hrepr.config.duplicate_free_variables
fin = hrepr.config.function_in_node
fr = hrepr.config.follow_references
tgen = hrepr.config.node_tooltip
cgen = hrepr.config.node_class
xsty = hrepr.config.graph_style
beau = hrepr.config.graph_beautify
gpr = MyiaGraphPrinter(
{self},
duplicate_constants=True if dc is None else dc,
duplicate_free_variables=True if dfv is None else dfv,
function_in_node=True if fin is None else fin,
follow_references=True if fr is None else fr,
tooltip_gen=tgen,
class_gen=cgen,
extra_style=xsty,
beautify=True if beau is None else beau
)
gpr.process()
return gpr.__hrepr__(H, hrepr)
#################
# Node printers #
#################
@mixin(ANFNode)
class _ANFNode:
@classmethod
def __hrepr_resources__(cls, H):
"""Require the cytoscape plugin for buche."""
return H.style(mcss)
def __hrepr__(self, H, hrepr):
class_name = self.__class__.__name__.lower()
label = short_labeler.label(self, True)
return H.span['node', f'node-{class_name}'](label)
@mixin(Apply)
class _Apply:
def __hrepr__(self, H, hrepr):
if len(self.inputs) == 2 and \
isinstance(self.inputs[0], Constant) and \
self.inputs[0].value is primops.return_:
if hasattr(hrepr, 'hrepr_nowrap'):
return hrepr.hrepr_nowrap(self.inputs[1])['node-return']
else:
return hrepr(self.inputs[1])['node-return']
else:
return super(Apply, self).__hrepr__(H, hrepr)
@mixin(ParentProxy)
class _ParentProxy:
@classmethod
def __hrepr_resources__(cls, H):
"""Require the cytoscape plugin for buche."""
return H.style(mcss)
def __hrepr__(self, H, hrepr):
class_name = 'constant'
label = 'Prox:' + short_labeler.label(self.graph, True)
return H.span['node', f'node-{class_name}'](label)
########
# Misc #
########
@mixin(NS)
class _NS:
def __hrepr__(self, H, hrepr):
return hrepr(self.__dict__)
@mixin(OrderedSet)
class _OrderedSet:
def __hrepr__(self, H, hrepr):
return hrepr(set(self._d.keys()))
@mixin(VirtualReference)
class _VirtualReference:
def __hrepr__(self, H, hrepr):
return hrepr.stdrepr_object(
'VirtualReference',
self.values.items()
)
@mixin(Reference)
class _Reference:
def __hrepr__(self, H, hrepr):
return hrepr.stdrepr_object(
'Reference',
(('node', self.node), ('context', self.context))
)
@mixin(Context)
class _Context:
def __hrepr__(self, H, hrepr):
d = {}
curr = self
while curr:
if curr.argkey and isinstance(curr.argkey[0], tuple):
sig = {}
for group in curr.argkey:
for name, value in group:
l = sig.setdefault(name, [])
l.append(value)
d[curr.graph] = sig
else:
d[curr.graph] = curr.argkey
curr = curr.parent
return hrepr.stdrepr_object('Context', list(d.items()))
@mixin(Location)
class _Location:
def __hrepr__(self, H, hrepr):
return H.div(
H.style('.hljs, .hljs-linenos { font-size: 10px !IMPORTANT; }'),
H.codeSnippet(
src=self.filename,
language="python",
line=self.line,
column=self.column + 1,
context=hrepr.config.snippet_context or 4
)
)
@mixin(DebugInfo)
class _DebugInfo:
def __hrepr__(self, H, hrepr):
exclude = {'save_trace', 'about'}
def mkdict(info):
d = {k: v for k, v in info.__dict__.items()
if not k.startswith('_') and k not in exclude}
tr = d.get('trace', None)
if tr:
fr = tr[-3]
d['trace'] = Location(
fr.filename, fr.lineno, 0, fr.lineno, 0, None
)
d['name'] = short_labeler.label(info)
return d
tabs = []
info = self
while getattr(info, 'about', None):
tabs.append((info, info.about.relation))
info = info.about.debug
tabs.append((info, 'initial'))
rval = H.boxTabs()
for info, rel in tabs:
pane = hrepr(mkdict(info))
rval = rval(H.tabEntry(H.tabLabel(rel), H.tabPane(pane)))
return rval
@mixin(GraphManager)
class _GraphManager:
@classmethod
def __hrepr_resources__(cls, H):
return GraphPrinter.__hrepr_resources__(H)
def __hrepr__(self, H, hrepr):
pr = GraphPrinter({
'layout': {
'name': 'dagre',
'rankDir': 'TB'
}
})
mode = hrepr.config.manager_mode or 'parents'
def lbl(x):
if isinstance(x, ParentProxy):
return f"{short_labeler.label(x.graph)}'"
else:
return short_labeler.label(x)
if mode == 'parents':
graph = {g: set() if parent is None else {parent}
for g, parent in self.parents.items()}
elif mode == 'children':
graph = self.children
elif mode == 'graph_dependencies_direct':
graph = self.graph_dependencies_direct
elif mode == 'graph_dependencies_total':
graph = self.graph_dependencies_total
else:
raise Exception(
f'Unknown display mode for GraphManager: "{mode}"'
)
for g, deps in graph.items():
pr.cynode(g, lbl(g), 'intermediate')
for dep in deps:
pr.cynode(dep, lbl(dep), 'intermediate')
pr.cynode(dep, lbl(dep), 'intermediate')
pr.cyedge(g, dep, '')
return pr.__hrepr__(H, hrepr)
@mixin(VMFrame)
class _VMFrame:
def __hrepr__(self, H, hrepr):
return hrepr.stdrepr_object(
'Frame',
[
('graph', self.graph),
('values', self.values),
('closure', self.closure),
('todo', self.todo),
('ownership', [x.graph in (None, self.graph)
for x in self.todo])
]
)
@mixin(Closure)
class _Closure:
def __hrepr__(self, H, hrepr):
return hrepr.stdrepr_object('Closure', [