/
printing.py
1877 lines (1596 loc) · 62.6 KB
/
printing.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
"""Functions for printing Aesara graphs."""
import hashlib
import logging
import os
import sys
import warnings
from abc import ABC, abstractmethod
from contextlib import contextmanager
from copy import copy
from functools import reduce, singledispatch
from io import StringIO
from typing import Any, Callable, Dict, List, Optional, Sequence, TextIO, Tuple, Union
import numpy as np
from typing_extensions import Literal
from aesara.compile import Function, SharedVariable
from aesara.compile.io import In, Out
from aesara.compile.profiling import ProfileStats
from aesara.configdefaults import config
from aesara.graph.basic import Apply, Constant, Variable, graph_inputs, io_toposort
from aesara.graph.fg import FunctionGraph
from aesara.graph.op import HasInnerGraph, Op, StorageMapType
from aesara.graph.utils import Scratchpad
IDTypesType = Literal["id", "int", "CHAR", "auto", ""]
pydot_imported = False
pydot_imported_msg = ""
try:
# pydot-ng is a fork of pydot that is better maintained
import pydot_ng as pd
if pd.find_graphviz():
pydot_imported = True
else:
pydot_imported_msg = "pydot-ng can't find graphviz. Install graphviz."
except ImportError:
try:
# fall back on pydot if necessary
import pydot as pd
if hasattr(pd, "find_graphviz"):
if pd.find_graphviz():
pydot_imported = True
else:
pydot_imported_msg = "pydot can't find graphviz"
else:
pd.Dot.create(pd.Dot())
pydot_imported = True
except ImportError:
# tests should not fail on optional dependency
pydot_imported_msg = (
"Install the python package pydot or pydot-ng." " Install graphviz."
)
except Exception as e:
pydot_imported_msg = "An error happened while importing/trying pydot: "
pydot_imported_msg += str(e.args)
_logger = logging.getLogger("aesara.printing")
VALID_ASSOC = {"left", "right", "either"}
def char_from_number(number):
"""Convert numbers to strings by rendering it in base 26 using capital letters as digits."""
base = 26
rval = ""
if number == 0:
rval = "A"
while number != 0:
remainder = number % base
new_char = chr(ord("A") + remainder)
rval = new_char + rval
number //= base
return rval
@singledispatch
def op_debug_information(op: Op, node: Apply) -> Dict[Apply, Dict[Variable, str]]:
"""Provide extra debug print information based on the type of `Op` and `Apply` node.
Implementations of this dispatch function should return a ``dict`` keyed by
the `Apply` node, `node`, associated with the given `op`. The value
associated with the `node` is another ``dict`` mapping `Variable` inputs
and/or outputs of `node` to their debug information.
The `node` key allows the information in the ``dict``'s values to be
specific to the given `node`, so that--for instance--the provided debug
information is only ever printed/associated with a given `Variable`
input/output when that `Variable` is displayed as an input/output of `node`
and not in every/any other place where said `Variable` is present in a
graph.
"""
return {}
def debugprint(
graph_like: Union[
Union[Variable, Apply, Function, FunctionGraph],
Sequence[Union[Variable, Apply, Function, FunctionGraph]],
],
depth: int = -1,
print_type: bool = False,
file: Optional[Union[Literal["str"], TextIO]] = None,
id_type: IDTypesType = "CHAR",
stop_on_name: bool = False,
done: Optional[Dict[Union[Literal["output"], Variable, Apply], str]] = None,
print_storage: bool = False,
used_ids: Optional[Dict[Union[Literal["output"], Variable, Apply], str]] = None,
print_op_info: bool = False,
print_destroy_map: bool = False,
print_view_map: bool = False,
print_fgraph_inputs: bool = False,
ids: Optional[IDTypesType] = None,
) -> Union[str, TextIO]:
r"""Print a graph as text.
Each line printed represents a `Variable` in a graph.
The indentation of lines corresponds to its depth in the symbolic graph.
The first part of the text identifies whether it is an input or the output
of some `Apply` node.
The second part of the text is an identifier of the `Variable`.
If a `Variable` is encountered multiple times in the depth-first search,
it is only printed recursively the first time. Later, just the `Variable`
identifier is printed.
If an `Apply` node has multiple outputs, then a ``.N`` suffix will be appended
to the `Apply` node's identifier, indicating to which output a line corresponds.
Parameters
----------
graph_like
The object(s) to be printed.
depth
Print graph to this depth (``-1`` for unlimited).
print_type
If ``True``, print the `Type`\s of each `Variable` in the graph.
file
When `file` extends `TextIO`, print to it; when `file` is
equal to ``"str"``, return a string; when `file` is ``None``, print to
`sys.stdout`.
id_type
Determines the type of identifier used for `Variable`\s:
- ``"id"``: print the python id value,
- ``"int"``: print integer character,
- ``"CHAR"``: print capital character,
- ``"auto"``: print the `Variable.auto_name` values,
- ``""``: don't print an identifier.
stop_on_name
When ``True``, if a node in the graph has a name, we don't print
anything below it.
done
A ``dict`` where we store the ids of printed nodes.
Useful to have multiple call to `debugprint` share the same ids.
print_storage
If ``True``, this will print the storage map for Aesara functions. When
combined with ``allow_gc=False``, after the execution of an Aesara
function, the output will show the intermediate results.
used_ids
A map between nodes and their printed ids.
print_op_info
Print extra information provided by the relevant `Op`\s. For example,
print the tap information for `Scan` inputs and outputs.
print_destroy_map
Whether to print the `destroy_map`\s of printed objects
print_view_map
Whether to print the `view_map`\s of printed objects
print_fgraph_inputs
Print the inputs of `FunctionGraph`\s.
Returns
-------
A string representing the printed graph, if `file` is a string, else `file`.
"""
if not isinstance(depth, int):
raise Exception("depth parameter must be an int")
if file == "str":
_file: Union[TextIO, StringIO] = StringIO()
elif file is None:
_file = sys.stdout
else:
_file = file
if ids is not None:
warnings.warn(
"`ids` is deprecated; use `id_type` instead.",
DeprecationWarning,
stacklevel=2,
)
id_type = ids
if done is None:
done = dict()
if used_ids is None:
used_ids = dict()
inputs_to_print = []
outputs_to_print = []
profile_list: List[Optional[Any]] = []
topo_orders: List[Optional[List[Apply]]] = []
storage_maps: List[Optional[StorageMapType]] = []
if isinstance(graph_like, (list, tuple, set)):
graphs = graph_like
else:
graphs = (graph_like,)
for obj in graphs:
if isinstance(obj, Variable):
outputs_to_print.append(obj)
profile_list.append(None)
storage_maps.append(None)
topo_orders.append(None)
elif isinstance(obj, Apply):
outputs_to_print.extend(obj.outputs)
profile_list.extend([None for item in obj.outputs])
storage_maps.extend([None for item in obj.outputs])
topo_orders.extend([None for item in obj.outputs])
elif isinstance(obj, Function):
if print_fgraph_inputs:
inputs_to_print.extend(obj.maker.fgraph.inputs)
outputs_to_print.extend(obj.maker.fgraph.outputs)
profile_list.extend([obj.profile for item in obj.maker.fgraph.outputs])
if print_storage:
storage_maps.extend(
[obj.vm.storage_map for item in obj.maker.fgraph.outputs]
)
else:
storage_maps.extend([None for item in obj.maker.fgraph.outputs])
topo = obj.maker.fgraph.toposort()
topo_orders.extend([topo for item in obj.maker.fgraph.outputs])
elif isinstance(obj, FunctionGraph):
if print_fgraph_inputs:
inputs_to_print.extend(obj.inputs)
outputs_to_print.extend(obj.outputs)
profile_list.extend([getattr(obj, "profile", None) for item in obj.outputs])
storage_maps.extend(
[getattr(obj, "storage_map", None) for item in obj.outputs]
)
topo = obj.toposort()
topo_orders.extend([topo for item in obj.outputs])
elif isinstance(obj, (int, float, np.ndarray)):
print(obj, file=_file)
elif isinstance(obj, (In, Out)):
outputs_to_print.append(obj.variable)
profile_list.append(None)
storage_maps.append(None)
topo_orders.append(None)
else:
raise TypeError(f"debugprint cannot print an object type {type(obj)}")
inner_graph_vars: List[Variable] = []
if any(p for p in profile_list if p is not None and p.fct_callcount > 0):
print(
"""
Timing Info
-----------
--> <time> <% time> - <total time> <% total time>'
<time> computation time for this node
<% time> fraction of total computation time for this node
<total time> time for this node + total times for this node's ancestors
<% total time> total time for this node over total computation time
N.B.:
* Times include the node time and the function overhead.
* <total time> and <% total time> may over-count computation times
if inputs to a node share a common ancestor and should be viewed as a
loose upper bound. Their intended use is to help rule out potential nodes
to remove when optimizing a graph because their <total time> is very low.
""",
file=_file,
)
op_information: Dict[Apply, Dict[Variable, str]] = {}
for var in inputs_to_print:
_debugprint(
var,
prefix="-",
depth=depth,
done=done,
print_type=print_type,
file=_file,
id_type=id_type,
inner_graph_ops=inner_graph_vars,
stop_on_name=stop_on_name,
used_ids=used_ids,
op_information=op_information,
parent_node=var.owner,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
)
for var, profile, storage_map, topo_order in zip(
outputs_to_print, profile_list, storage_maps, topo_orders
):
if hasattr(var.owner, "op"):
if isinstance(var.owner.op, HasInnerGraph) and var not in inner_graph_vars:
inner_graph_vars.append(var)
if print_op_info:
op_information.update(op_debug_information(var.owner.op, var.owner))
_debugprint(
var,
depth=depth,
done=done,
print_type=print_type,
file=_file,
topo_order=topo_order,
id_type=id_type,
inner_graph_ops=inner_graph_vars,
stop_on_name=stop_on_name,
profile=profile,
storage_map=storage_map,
used_ids=used_ids,
op_information=op_information,
parent_node=var.owner,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
)
if len(inner_graph_vars) > 0:
print("", file=_file)
new_prefix = " >"
new_prefix_child = " >"
print("Inner graphs:", file=_file)
for ig_var in inner_graph_vars:
# This is a work-around to maintain backward compatibility
# (e.g. to only print inner graphs that have been compiled through
# a call to `Op.prepare_node`)
inner_fn = getattr(ig_var.owner.op, "_fn", None)
if inner_fn:
# If the op was compiled, print the optimized version.
inner_inputs = inner_fn.maker.fgraph.inputs
inner_outputs = inner_fn.maker.fgraph.outputs
else:
inner_inputs = ig_var.owner.op.inner_inputs
inner_outputs = ig_var.owner.op.inner_outputs
outer_inputs = ig_var.owner.inputs
if hasattr(ig_var.owner.op, "get_oinp_iinp_iout_oout_mappings"):
inner_to_outer_inputs = {
inner_inputs[i]: outer_inputs[o]
for i, o in ig_var.owner.op.get_oinp_iinp_iout_oout_mappings()[
"outer_inp_from_inner_inp"
].items()
}
else:
inner_to_outer_inputs = None
if print_op_info:
op_information.update(
op_debug_information(ig_var.owner.op, ig_var.owner)
)
print("", file=_file)
_debugprint(
ig_var,
depth=depth,
done=done,
print_type=print_type,
file=_file,
id_type=id_type,
inner_graph_ops=inner_graph_vars,
stop_on_name=stop_on_name,
inner_to_outer_inputs=inner_to_outer_inputs,
used_ids=used_ids,
op_information=op_information,
parent_node=ig_var.owner,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
)
if print_fgraph_inputs:
for inp in inner_inputs:
_debugprint(
inp,
prefix="-",
depth=depth,
done=done,
print_type=print_type,
file=_file,
id_type=id_type,
stop_on_name=stop_on_name,
inner_graph_ops=inner_graph_vars,
inner_to_outer_inputs=inner_to_outer_inputs,
used_ids=used_ids,
op_information=op_information,
parent_node=ig_var.owner,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
inner_graph_node=ig_var.owner,
)
inner_to_outer_inputs = None
for out in inner_outputs:
if (
isinstance(getattr(out.owner, "op", None), HasInnerGraph)
and out not in inner_graph_vars
):
inner_graph_vars.append(out)
_debugprint(
out,
prefix=new_prefix,
depth=depth,
done=done,
print_type=print_type,
file=_file,
id_type=id_type,
stop_on_name=stop_on_name,
prefix_child=new_prefix_child,
inner_graph_ops=inner_graph_vars,
inner_to_outer_inputs=inner_to_outer_inputs,
used_ids=used_ids,
op_information=op_information,
parent_node=ig_var.owner,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
inner_graph_node=ig_var.owner,
)
if file is _file:
return file
elif file == "str":
assert isinstance(_file, StringIO)
return _file.getvalue()
else:
_file.flush()
return _file
def _debugprint(
var: Variable,
prefix: str = "",
depth: int = -1,
done: Optional[Dict[Union[Literal["output"], Variable, Apply], str]] = None,
print_type: bool = False,
file: TextIO = sys.stdout,
print_destroy_map: bool = False,
print_view_map: bool = False,
topo_order: Optional[Sequence[Apply]] = None,
id_type: IDTypesType = "CHAR",
stop_on_name: bool = False,
prefix_child: Optional[str] = None,
inner_graph_ops: Optional[List[Variable]] = None,
profile: Optional[ProfileStats] = None,
inner_to_outer_inputs: Optional[Dict[Variable, Variable]] = None,
storage_map: Optional[StorageMapType] = None,
used_ids: Optional[Dict[Union[Literal["output"], Variable, Apply], str]] = None,
op_information: Optional[Dict[Apply, Dict[Variable, str]]] = None,
parent_node: Optional[Apply] = None,
print_op_info: bool = False,
inner_graph_node: Optional[Apply] = None,
) -> TextIO:
r"""Print the graph represented by `var`.
Parameters
----------
var
A `Variable` instance.
prefix
Prefix to each line (typically some number of spaces).
depth
Print graph to this depth (``-1`` for unlimited).
done
See `debugprint`.
print_type
See `debugprint`.
file
File-like object to which to print.
print_destroy_map
Whether to print the `Variable`'s type.
print_view_map
Whether to print `Op` ``destroy_map``\s.
topo_order
If not empty will print the index in the toposort.
id_type
See `debugprint`.
stop_on_name
Whether to print `Op` ``view_map``\s.
inner_graph_ops
A list of `Op`\s with inner graphs.
inner_to_outer_inputs
A dictionary mapping an `Op`'s inner-inputs to its outer-inputs.
storage_map
``None`` or the storage map (e.g. when printing an Aesara function).
used_ids
See `debugprint`.
op_information
Extra `Op`-level information to be added to variable print-outs.
parent_node
The parent node of `var`.
print_op_info
See `debugprint`.
inner_graph_node
The inner-graph node in which `var` is contained.
"""
if depth == 0:
return file
if topo_order is None:
topo_order = []
if done is None:
_done = dict()
else:
_done = done
if inner_graph_ops is None:
inner_graph_ops = []
if print_type:
type_str = f" <{var.type}>"
else:
type_str = ""
if prefix_child is None:
prefix_child = prefix
if used_ids is None:
_used_ids = dict()
else:
_used_ids = used_ids
if op_information is None:
op_information = {}
def get_id_str(
obj: Union[Literal["output"], Apply, Variable], get_printed: bool = True
) -> str:
id_str: str = ""
if obj in _used_ids:
id_str = _used_ids[obj]
elif obj == "output":
id_str = "output"
elif id_type == "id":
id_str = f"[id {id(var)}]"
elif id_type == "int":
id_str = f"[id {len(_used_ids)}]"
elif id_type == "CHAR":
id_str = f"[id {char_from_number(len(_used_ids))}]"
elif id_type == "auto":
id_str = f"[id {var.auto_name}]"
elif id_type == "":
id_str = ""
if get_printed:
_done[obj] = id_str
_used_ids[obj] = id_str
return id_str
if var.owner:
# This variable is the output of a computation, so just print out the
# `Apply` node
node = var.owner
var_name = getattr(var, "name", "")
if var_name is None:
var_name = ""
if var_name:
var_name = f" '{var_name}'"
if print_destroy_map and node.op.destroy_map:
destroy_map_str = f" d={node.op.destroy_map}"
else:
destroy_map_str = ""
if print_view_map and node.op.view_map:
view_map_str = f" v={node.op.view_map}"
else:
view_map_str = ""
if topo_order:
o = f" {topo_order.index(node)}"
else:
o = ""
already_done = node in _done
id_str = get_id_str(node)
if len(node.outputs) == 1:
output_idx = ""
else:
output_idx = f".{node.outputs.index(var)}"
if id_str:
id_str = f" {id_str}"
if storage_map and node.outputs[0] in storage_map:
data = f" {storage_map[node.outputs[0]]}"
else:
data = ""
var_output = f"{prefix}{node.op}{output_idx}{id_str}{type_str}{var_name}{destroy_map_str}{view_map_str}{o}{data}"
if print_op_info and node not in op_information:
op_information.update(op_debug_information(node.op, node))
node_info = (
parent_node and op_information.get(parent_node)
) or op_information.get(node)
if node_info and var in node_info:
var_output = f"{var_output} ({node_info[var]})"
if profile and profile.apply_time and node in profile.apply_time:
op_time = profile.apply_time[node]
op_time_percent = (op_time / profile.fct_call_time) * 100
tot_time_dict = profile.compute_total_times()
tot_time = tot_time_dict[node]
tot_time_percent = (tot_time_dict[node] / profile.fct_call_time) * 100
print(
"%s --> %8.2es %4.1f%% %8.2es %4.1f%%"
% (
var_output,
op_time,
op_time_percent,
tot_time,
tot_time_percent,
),
file=file,
)
else:
print(var_output, file=file)
if not already_done and (
not stop_on_name or not (hasattr(var, "name") and var.name is not None)
):
new_prefix = prefix_child + " |"
new_prefix_child = prefix_child + " |"
for in_idx, in_var in enumerate(node.inputs):
if in_idx == len(node.inputs) - 1:
new_prefix_child = prefix_child + " "
if hasattr(in_var, "owner") and hasattr(in_var.owner, "op"):
if (
isinstance(in_var.owner.op, HasInnerGraph)
and in_var not in inner_graph_ops
):
inner_graph_ops.append(in_var)
_debugprint(
in_var,
new_prefix,
depth=depth - 1,
done=_done,
print_type=print_type,
file=file,
topo_order=topo_order,
id_type=id_type,
stop_on_name=stop_on_name,
prefix_child=new_prefix_child,
inner_graph_ops=inner_graph_ops,
profile=profile,
inner_to_outer_inputs=inner_to_outer_inputs,
storage_map=storage_map,
used_ids=_used_ids,
op_information=op_information,
parent_node=node,
print_op_info=print_op_info,
print_destroy_map=print_destroy_map,
print_view_map=print_view_map,
inner_graph_node=inner_graph_node,
)
else:
id_str = get_id_str(var)
if id_str:
id_str = f" {id_str}"
if storage_map and var in storage_map:
data = f" {storage_map[var]}"
else:
data = ""
var_output = f"{prefix}{var}{id_str}{type_str}{data}"
if print_op_info and var.owner and var.owner not in op_information:
op_information.update(op_debug_information(var.owner.op, var.owner))
if inner_to_outer_inputs is not None and var in inner_to_outer_inputs:
outer_var = inner_to_outer_inputs[var]
if outer_var.owner:
outer_id_str = get_id_str(outer_var.owner)
else:
outer_id_str = get_id_str(outer_var)
var_output = f"{var_output} -> {outer_id_str}"
# TODO: This entire approach will only print `Op` info for two levels
# of nesting.
for node in dict.fromkeys([inner_graph_node, parent_node, var.owner]):
node_info = op_information.get(node)
if node_info and var in node_info:
var_output = f"{var_output} ({node_info[var]})"
print(var_output, file=file)
return file
def _print_fn(op, xin):
for attr in op.attrs:
temp = getattr(xin, attr)
if callable(temp):
pmsg = temp()
else:
pmsg = temp
print(op.message, attr, "=", pmsg)
class Print(Op):
"""This identity-like Op print as a side effect.
This identity-like Op has the side effect of printing a message
followed by its inputs when it runs. Default behaviour is to print
the __str__ representation. Optionally, one can pass a list of the
input member functions to execute, or attributes to print.
@type message: String
@param message: string to prepend to the output
@type attrs: list of Strings
@param attrs: list of input node attributes or member functions to print.
Functions are identified through callable(), executed and
their return value printed.
:note: WARNING. This can disable some optimizations!
(speed and/or stabilization)
Detailed explanation:
As of 2012-06-21 the Print op is not known by any optimization.
Setting a Print op in the middle of a pattern that is usually
optimized out will block the optimization. for example, log(1+x)
optimizes to log1p(x) but log(1+Print(x)) is unaffected by
optimizations.
"""
view_map = {0: [0]}
__props__ = ("message", "attrs", "global_fn")
def __init__(self, message="", attrs=("__str__",), global_fn=_print_fn):
self.message = message
self.attrs = tuple(attrs) # attrs should be a hashable iterable
self.global_fn = global_fn
def make_node(self, xin):
xout = xin.type()
return Apply(op=self, inputs=[xin], outputs=[xout])
def perform(self, node, inputs, output_storage):
(xin,) = inputs
(xout,) = output_storage
xout[0] = xin
self.global_fn(self, xin)
def grad(self, input, output_gradients):
return output_gradients
def R_op(self, inputs, eval_points):
return [x for x in eval_points]
def __setstate__(self, dct):
dct.setdefault("global_fn", _print_fn)
self.__dict__.update(dct)
def c_code_cache_version(self):
return (1,)
def do_constant_folding(self, fgraph, node):
return False
class PrinterState(Scratchpad):
def __init__(self, props=None, **more_props):
if props is None:
props = {}
elif isinstance(props, Scratchpad):
self.__update__(props)
else:
self.__dict__.update(props)
self.__dict__.update(more_props)
# A dict from the object to print to its string
# representation. If it is a dag and not a tree, it allow to
# parse each node of the graph only once. They will still be
# printed many times
self.memo = {}
class Printer(ABC):
@abstractmethod
def process(self, var: Variable, pstate: PrinterState) -> str:
"""Construct a string representation for a `Variable`."""
@contextmanager
def set_precedence(pstate: PrinterState, precedence: int = -1000):
"""Temporarily set the precedence of a `PrinterState`."""
old_precedence = getattr(pstate, "precedence", None)
pstate.precedence = precedence
try:
yield
finally:
pstate.precedence = old_precedence
class OperatorPrinter(Printer):
def __init__(self, operator, precedence, assoc="left"):
self.operator = operator
self.precedence = precedence
self.assoc = assoc
assert self.assoc in VALID_ASSOC
def process(self, output, pstate):
if output in pstate.memo:
return pstate.memo[output]
pprinter = pstate.pprinter
node = output.owner
if node is None:
raise TypeError(
f"operator {self.operator} cannot represent a variable that is "
"not the result of an operation"
)
# Precedence seems to be buggy, see #249
# So, in doubt, we parenthesize everything.
# outer_precedence = getattr(pstate, 'precedence', -999999)
# outer_assoc = getattr(pstate, 'assoc', 'none')
# if outer_precedence > self.precedence:
# parenthesize = True
# else:
# parenthesize = False
parenthesize = True
input_strings = []
max_i = len(node.inputs) - 1
for i, input in enumerate(node.inputs):
new_precedence = self.precedence
if self.assoc == "left" and i != 0 or self.assoc == "right" and i != max_i:
new_precedence += 1e-6
with set_precedence(pstate, new_precedence):
s = pprinter.process(input, pstate)
input_strings.append(s)
if len(input_strings) == 1:
s = self.operator + input_strings[0]
else:
s = f" {self.operator} ".join(input_strings)
if parenthesize:
r = f"({s})"
else:
r = s
pstate.memo[output] = r
return r
class PatternPrinter(Printer):
def __init__(self, *patterns):
self.patterns = []
for pattern in patterns:
if isinstance(pattern, str):
self.patterns.append((pattern, ()))
else:
self.patterns.append((pattern[0], pattern[1:]))
def process(self, output, pstate):
if output in pstate.memo:
return pstate.memo[output]
pprinter = pstate.pprinter
node = output.owner
if node is None:
raise TypeError(
f"Patterns {self.patterns} cannot represent a variable that is "
"not the result of an operation"
)
idx = node.outputs.index(output)
pattern, precedences = self.patterns[idx]
precedences += (1000,) * len(node.inputs)
def pp_process(input, new_precedence):
with set_precedence(pstate, new_precedence):
r = pprinter.process(input, pstate)
return r
d = {
str(i): x
for i, x in enumerate(
pp_process(input, precedence)
for input, precedence in zip(node.inputs, precedences)
)
}
r = pattern % d
pstate.memo[output] = r
return r
class FunctionPrinter(Printer):
def __init__(self, names: List[str], keywords: Optional[List[str]] = None):
"""
Parameters
----------
names
The function names used for each output.
keywords
The `Op` keywords to include in the output.
"""
self.names = names
if keywords is None:
keywords = []
self.keywords = keywords
def process(self, output, pstate):
if output in pstate.memo:
return pstate.memo[output]
pprinter = pstate.pprinter
node = output.owner
if node is None:
raise TypeError(
f"function {self.names} cannot represent a variable that is "
"not the result of an operation"
)
idx = node.outputs.index(output)
name = self.names[idx]
with set_precedence(pstate):
inputs_str = ", ".join(
[pprinter.process(input, pstate) for input in node.inputs]
)
keywords_str = ", ".join(
[f"{kw}={getattr(node.op, kw)}" for kw in self.keywords]
)
if keywords_str and inputs_str:
keywords_str = f", {keywords_str}"
r = f"{name}({inputs_str}{keywords_str})"
pstate.memo[output] = r
return r
class IgnorePrinter(Printer):
def process(self, output, pstate):
if output in pstate.memo:
return pstate.memo[output]
pprinter = pstate.pprinter
node = output.owner
if node is None:
raise TypeError(
f"function {self.function} cannot represent a variable that is"
" not the result of an operation"
)
input = node.inputs[0]
r = f"{pprinter.process(input, pstate)}"
pstate.memo[output] = r
return r
class LeafPrinter(Printer):
def process(self, output, pstate):
if output in pstate.memo:
return pstate.memo[output]
if output.name in greek:
r = greek[output.name]
else: