/
debugmode.py
2300 lines (1968 loc) · 83.6 KB
/
debugmode.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
"""
Provides `DebugMode`, an evaluation mode for debugging aesara internals.
TODO: add support for IfElse Op, LazyLinker, etc.
"""
import copy
import gc
import logging
import sys
from io import StringIO
from itertools import chain
from itertools import product as itertools_product
from logging import Logger
from typing import Optional
from warnings import warn
import numpy as np
import aesara
from aesara.compile.function.types import (
Function,
FunctionMaker,
infer_reuse_pattern,
std_fgraph,
)
from aesara.compile.mode import Mode, register_mode
from aesara.compile.ops import OutputGuard, _output_guard
from aesara.configdefaults import config
from aesara.graph.basic import Variable, io_toposort
from aesara.graph.destroyhandler import DestroyHandler
from aesara.graph.features import AlreadyThere, BadOptimization, Feature
from aesara.graph.op import HasInnerGraph, Op
from aesara.graph.utils import InconsistencyError, MethodNotDefined
from aesara.link.basic import Container, LocalLinker
from aesara.link.c.op import COp
from aesara.link.utils import map_storage, raise_with_op
from aesara.printing import _debugprint
from aesara.tensor import TensorType
from aesara.utils import NoDuplicateOptWarningFilter, difference, get_unbound_function
__docformat__ = "restructuredtext en"
_logger: Logger = logging.getLogger("aesara.compile.debugmode")
_logger.addFilter(NoDuplicateOptWarningFilter())
class DebugModeError(Exception):
"""
Generic Exception raised to indicate an internal aesara problem.
"""
class BadThunkOutput(DebugModeError):
"""
Exception: Calling the same Op twice gives inconsistent outputs.
It can be raised, for instance, if an Op's c_code and perform method
do not agree, or if one of these methods do not give the same result
when called twice with the same inputs (but different memory layouts
for the output).
"""
r = None
"""
The `Variable` instance for which conflicting values were computed.
"""
thunk1 = ""
val1 = None
"""
The value computed by `thunk1`.
"""
thunk2 = ""
val2 = None
"""
The value computed by `thunk2`.
"""
def __init__(self, r, thunk1, val1, thunk2, val2, inputs_val=()):
super().__init__()
self.r = r
self.thunk1 = thunk1
self.val1 = val1
self.thunk2 = thunk2
self.val2 = val2
self.inputs_val = inputs_val
def offending_op(self):
"""
Return the Op class whose c_code and perform implementations
didn't match.
"""
return type(self.r.owner.op)
def __str__(self):
return self.str_diagnostic()
def str_diagnostic(self):
"""
Return a pretty multiline string representing the cause of the exception.
"""
sio = StringIO()
print("BadThunkOutput", file=sio)
print(" Apply :", self.r.owner, file=sio)
print(" op :", self.offending_op(), file=sio)
print(" Outputs Type:", self.r.type, file=sio)
print(" Outputs Shape:", getattr(self.val1, "shape", None), file=sio)
print(" Outputs Strides:", getattr(self.val1, "strides", None), file=sio)
print(" Inputs Type :", [i.type for i in self.r.owner.inputs], file=sio)
print(
" Inputs Shape:",
[getattr(val, "shape", None) for val in self.inputs_val],
file=sio,
)
print(
" Inputs Strides:",
[getattr(val, "strides", None) for val in self.inputs_val],
file=sio,
)
scalar_values = []
for ipt in self.inputs_val:
if getattr(ipt, "size", -1) <= 10:
scalar_values.append(ipt)
else:
scalar_values.append("not shown")
print(f" Inputs values: {scalar_values}", file=sio)
print(" Bad Variable:", self.r, file=sio)
print(" thunk1 :", self.thunk1, file=sio)
print(" thunk2 :", self.thunk2, file=sio)
print(str_diagnostic(self.val1, self.val2, None, None), file=sio)
ret = sio.getvalue()
return ret
class BadOptimization(DebugModeError, BadOptimization):
pass
class BadDestroyMap(DebugModeError):
"""
Exception: Some perform() or c_code() modified an input that
wasn't in the destroy_map.
"""
def __init__(self, node, idx, old_val, new_val, perform):
super().__init__()
self.node = node
self.idx = idx
self.old_val = old_val
self.new_val = new_val
self.perform = perform
def __str__(self):
sio = StringIO()
print(" node:", self.node, file=sio)
print(" perform:", self.perform, file=sio)
print(" node.inputs:", [(str(i), id(i)) for i in self.node.inputs], file=sio)
print(" destroy_map:", self.node.op.destroy_map, file=sio)
print(" changed input idx:", self.idx, file=sio)
print(" changed input type:", self.node.inputs[self.idx].type, file=sio)
print(" repr (old val):", repr(self.old_val), file=sio)
print(" repr (new val):", repr(self.new_val), file=sio)
try:
npy_old_val = np.asarray(self.old_val)
npy_new_val = np.asarray(self.new_val)
print(
" value dtype (new <space> old):",
npy_new_val.dtype,
npy_old_val.dtype,
file=sio,
)
print(
" value shape (new <space> old):",
npy_new_val.shape,
npy_old_val.shape,
file=sio,
)
print(
" value min (new <space> old):",
npy_new_val.min(),
npy_old_val.min(),
file=sio,
)
print(
" value max (new <space> old):",
npy_new_val.max(),
npy_old_val.max(),
file=sio,
)
delta = npy_new_val - npy_old_val
print(" value min (new-old):", delta.min(), file=sio)
print(" value max (new-old):", delta.max(), file=sio)
print(
" value argmin (new-old):",
np.unravel_index(delta.argmin(), npy_new_val.shape),
file=sio,
)
print(
" value argmax (new-old):",
np.unravel_index(delta.argmax(), npy_new_val.shape),
file=sio,
)
print(
" location of first 10 mismatches:",
np.transpose(np.nonzero(delta))[:10],
file=sio,
)
print("", file=sio)
except Exception as e:
print(f"(Numpy-hints failed with: {e})", file=sio)
print(
" Hint: this can also be caused by a deficient "
"values_eq_approx() or __eq__() implementation "
"[which compared input values]",
file=sio,
)
return sio.getvalue()
class BadViewMap(DebugModeError):
"""
Exception: Some perform() or c_code() created a memory alias
that wasn't in the view_map.
"""
def __init__(
self, node, output_idx, out_storage, in_alias_idx=None, out_alias_idx=None
):
super().__init__()
self.node = node
self.output_idx = output_idx
self.out_storage = out_storage
self.in_alias_idx = in_alias_idx
self.out_alias_idx = out_alias_idx
def __str__(self):
sio = StringIO()
print(" node:", self.node, file=sio)
print(" node.inputs:", [(str(i), id(i)) for i in self.node.inputs], file=sio)
print(" node.outputs:", [(str(i), id(i)) for i in self.node.outputs], file=sio)
print(" view_map:", self.node.op.view_map, file=sio)
print(" destroy_map:", self.node.op.destroy_map, file=sio)
print(" aliased output:", self.output_idx, file=sio)
print(" aliased output storage:", self.out_storage, file=sio)
if self.in_alias_idx:
print(" aliased to inputs:", self.in_alias_idx, file=sio)
if self.out_alias_idx:
print(" aliased to outputs:", self.out_alias_idx, file=sio)
return sio.getvalue()
class StochasticOrder(DebugModeError):
"""
Exception: Repeated Optimizations of the same graph do not give
identical results.
The most common cause is that an Optimization iterates over some
objects in a memory-address-dependent order (such as id() or
object.hash()).
"""
class InvalidValueError(DebugModeError):
"""
Exception: some Op an output value that is inconsistent with
the Type of that output.
Note: If there is only one parameter and it is a string, then we
will use it as the error message. This is needed when we catch,
extend, and reraise an error.
"""
def __init__(self, r, v=None, client_node=None, hint="none", specific_hint="none"):
super().__init__()
self.r = r
self.v = v
self.client_node = client_node
self.hint = hint
self.specific_hint = specific_hint
# To allow extending th error message of an existing error.
self.full_err = None
if isinstance(r, str):
assert (
v is None
and client_node is None
and hint == "none"
and specific_hint == "none"
)
self.full_err = r
def __str__(self):
# We have a pre-made message
if getattr(self, "full_err", None) is not None:
return self.full_err
r, v = self.r, self.v
type_r = r.type
type_v = type(v)
v_val = str(v)[0:100]
v_dtype = "N/A"
v_shape = "N/A"
v_min = "N/A"
v_max = "N/A"
v_isfinite = "N/A"
try:
v_shape = v.shape
v_dtype = v.dtype
v_min = v.min()
v_max = v.max()
v_isfinite = np.all(np.isfinite(v))
except Exception:
pass
client_node = self.client_node
hint = self.hint
specific_hint = self.specific_hint
context = _debugprint(r, prefix=" ", depth=12, file=StringIO()).getvalue()
return f"""InvalidValueError
type(variable) = {type_r}
variable = {r}
type(value) = {type_v}
dtype(value) = {v_dtype}
shape(value) = {v_shape}
value = {v_val}
min(value) = {v_min}
max(value) = {v_max}
isfinite = {v_isfinite}
client_node = {client_node}
hint = {hint}
specific_hint = {specific_hint}
context = ...
{context}
"""
def str_diagnostic(expected, value, rtol, atol):
"""Return a pretty multiline string representing the cause of the exception."""
sio = StringIO()
try:
ssio = StringIO()
print(" : shape, dtype, strides, min, max, n_inf, n_nan:", file=ssio)
print(" Expected :", end=" ", file=ssio)
print(expected.shape, end=" ", file=ssio)
print(expected.dtype, end=" ", file=ssio)
print(expected.strides, end=" ", file=ssio)
print(expected.min(), end=" ", file=ssio)
print(expected.max(), end=" ", file=ssio)
print(np.isinf(expected).sum(), end=" ", file=ssio)
print(np.isnan(expected).sum(), end=" ", file=ssio)
# only if all succeeds to we add anything to sio
print(ssio.getvalue(), file=sio)
except Exception:
pass
try:
ssio = StringIO()
print(" Value :", end=" ", file=ssio)
print(value.shape, end=" ", file=ssio)
print(value.dtype, end=" ", file=ssio)
print(value.strides, end=" ", file=ssio)
print(value.min(), end=" ", file=ssio)
print(value.max(), end=" ", file=ssio)
print(np.isinf(value).sum(), end=" ", file=ssio)
print(np.isnan(value).sum(), end=" ", file=ssio)
# only if all succeeds to we add anything to sio
print(ssio.getvalue(), file=sio)
except Exception:
pass
print(" expected :", expected, file=sio)
print(" value :", value, file=sio)
try:
ov = np.asarray(expected)
nv = np.asarray(value)
ssio = StringIO()
absdiff = np.absolute(nv - ov)
print(" Max Abs Diff: ", np.max(absdiff), file=ssio)
print(" Mean Abs Diff: ", np.mean(absdiff), file=ssio)
print(" Median Abs Diff: ", np.median(absdiff), file=ssio)
print(" Std Abs Diff: ", np.std(absdiff), file=ssio)
reldiff = np.absolute(nv - ov) / np.absolute(ov)
print(" Max Rel Diff: ", np.max(reldiff), file=ssio)
print(" Mean Rel Diff: ", np.mean(reldiff), file=ssio)
print(" Median Rel Diff: ", np.median(reldiff), file=ssio)
print(" Std Rel Diff: ", np.std(reldiff), file=ssio)
# only if all succeeds to we add anything to sio
print(ssio.getvalue(), file=sio)
except Exception:
pass
atol_, rtol_ = aesara.tensor.math._get_atol_rtol(expected, value)
if rtol is not None:
rtol_ = rtol
if atol is not None:
atol_ = atol
print(" rtol, atol:", rtol_, atol_, file=sio)
return sio.getvalue()
def _optcheck_fgraph(input_specs, output_specs, accept_inplace=False):
"""
Create a FunctionGraph for debugging.
Parameters
----------
input_specs: WRITEME
fgraph inputs.
output_specs: WRITEME
fgraph outputs.
accept_inplace : bool
Are inplace ops permitted in the original graph?
Returns
-------
FunctionGraph
A new FunctionGraph with a cloned graph, with debugging `Feature`
instances already installed.
"""
equivalence_tracker = _VariableEquivalenceTracker()
fgraph, updates = std_fgraph(
input_specs, output_specs, accept_inplace, force_clone=True
)
fgraph.attach_feature(equivalence_tracker)
return fgraph, updates
class DataDestroyed:
# this is a singleton class We put it in the storage_map when the
# variable value was destroyed to prevent reusing bad value for
# it.
pass
data_destroyed = DataDestroyed()
def check_eq(var, val1, val2):
if hasattr(var.tag, "values_eq_approx"):
return var.tag.values_eq_approx(val1, val2)
else:
return var.type.values_eq_approx(val1, val2)
def _check_inputs(
node,
storage_map,
r_vals,
dr_vals,
active_nodes,
clobber_dr_vals=True,
perform=None,
warn_input_not_reused=True,
):
"""
Raise BadDestroyMap if necessary, update dr_vals.
Returns a list of output variables that actually worked inplace
(their value is aliased to the value of at least one input).
It modify the storage_map to remove node.inputs variable that have
been destroyed.
"""
destroyed_idx_list = []
destroy_map = node.op.destroy_map
for o_pos, i_pos_list in destroy_map.items():
destroyed_idx_list.extend(i_pos_list)
destroyed_res_list = [node.inputs[i] for i in destroyed_idx_list]
actually_inplace_outputs = []
dmap = node.op.destroy_map
for oo, ii in dmap.items():
var = node.outputs[oo]
out_var = storage_map[var][0]
in_var = storage_map[node.inputs[ii[0]]][0]
if hasattr(var.type, "may_share_memory") and var.type.may_share_memory(
out_var, in_var
):
actually_inplace_outputs.append(node.outputs[oo])
if warn_input_not_reused and destroyed_res_list:
if isinstance(node.op, OutputGuard):
# The point of OutputGuard is to be declared as destructive
# while not destroying anything
continue
if out_var is not in_var:
_logger.warning(
f"Optimization Warning: input idx {int(ii[0])} marked "
f"as destroyed was not changed for node '{node}'"
)
vmap = node.op.view_map
for oo, ii in vmap.items():
var = node.outputs[oo]
out_var = storage_map[var][0]
in_var = storage_map[node.inputs[ii[0]]][0]
may_share = hasattr(var.type, "may_share_memory") and var.type.may_share_memory(
out_var, in_var
)
if may_share:
actually_inplace_outputs.append(node.outputs[oo])
if warn_input_not_reused:
# We don't try to optimize simple scalar and empty ndarray,
# as this is not worth our time. This happen at least in
# Subtensor when the output is a scalar But this depend on
# the version of numpy!
if getattr(out_var, "size", 2) <= 1:
continue
if isinstance(node.op, OutputGuard):
# This class is not in the final graph.
continue
if not may_share:
_logger.warning(
f"Optimization Warning: input idx {int(ii[0])} marked "
"as viewed but new memory allocated by node "
f"'{node}'"
)
for r_idx, r in enumerate(node.inputs):
if not r.type.values_eq(r_vals[r], storage_map[r][0]):
# some input node 'r' got changed by running the node
# this may or may not be ok...
if r in destroyed_res_list:
# ok, we expected r to be destroyed
if node in active_nodes:
if dr_vals.get(r, (0, node))[1] is not node:
# bad: there should only be one active node
# that destroys any variable
raise Exception("failure in topological ordering")
if clobber_dr_vals:
# no copy, this is the last use of this variable
dr_vals[r] = (storage_map[r][0], node)
# make sure that dr_vals[r] doesn't get used again
storage_map[r][0] = data_destroyed
else:
raise BadDestroyMap(node, r_idx, r_vals[r], storage_map[r][0], perform)
return actually_inplace_outputs
def _check_viewmap(fgraph, node, storage_map):
"""
This functions raises a BadViewMap exception when it detects the
following:
- Output node storages aliased to input storage, with no declaration
in view_map.
- If not aliased to an input, check if two outputs are aliased together
and used subsequently in the graph.
"""
for oi, onode in enumerate(node.outputs):
good_alias, bad_alias = {}, {}
outstorage = storage_map[onode][0]
# first find out which input it aliases
view_map = node.op.view_map
destroy_map = node.op.destroy_map
# In theory, aesara's view_map only allows for 1 output to
# alias 1 input. Checking for multiple aliases just in
# case...
for ii, inode in enumerate(node.inputs):
in_storage = storage_map[inode][0]
if in_storage is data_destroyed:
# If the input have been destroyed, it can't be a
# view. So no need to check. Also, we don't have the
# original value, we we wouldn't be able to do this
# useless check.
continue
if hasattr(inode.type, "may_share_memory") and inode.type.may_share_memory(
outstorage, in_storage
):
nodeid = id(inode)
bad_alias[nodeid] = ii
# check that the aliasing was declared in [view|destroy]_map
if [ii] == view_map.get(oi, None) or [ii] == destroy_map.get(oi, None):
good_alias[nodeid] = bad_alias.pop(nodeid)
# TODO: make sure this is correct
# According to OB, duplicate inputs are rejected on build graph time
# if they cause problems. So if they are here it should be ok.
for key, val in good_alias.items():
bad_alias.pop(key, None)
if bad_alias:
raise BadViewMap(node, oi, outstorage, list(bad_alias.values()))
# if its not aliased to input, check output->output aliasing
if not good_alias and _is_used_in_graph(fgraph, onode):
for other_oi, other_onode in enumerate(node.outputs):
if other_oi == oi:
continue
other_storage = storage_map[other_onode][0]
# check to see if we share memory with this other output
# this is not a problem if the node is not actually used
if (
_is_used_in_graph(fgraph, other_onode)
and hasattr(other_onode.type, "may_share_memory")
and other_onode.type.may_share_memory(outstorage, other_storage)
):
raise BadViewMap(node, oi, outstorage, out_alias_idx=other_oi)
def _is_used_in_graph(fgraph, var):
"""
Returns
-------
bool
True if `var` is used by another node in the graph.
"""
return not (fgraph.clients[var] == [("output", 1)] or fgraph.clients[var] == [])
def _check_strides_match(a, b, warn_err, op):
"""
Parameters
----------
warn_err
If 0, no warning, if 1 warning, if 2 error.
"""
if warn_err == 0:
return
try:
strides_eq = a.strides == b.strides
except Exception:
return # no strides
if not strides_eq:
e = TypeError(
"Stride mismatch", (a.shape, b.shape, a.strides, b.strides, str(op))
)
if warn_err == 2:
raise e
else:
warn(str(e))
def _lessbroken_deepcopy(a):
"""
Parameters
----------
a
Any object
Returns
-------
object
A copy of `a` that shares no internal storage with the original
(a deep copy). This function handles numpy arrays specially, because
copy.deepcopy() called on a 0-d array will return a numpy scalar,
not an array.
"""
# this exists because copy.deepcopy on numpy arrays is broken
# This logic is also in link.py
from aesara.link.c.type import _cdata_type
if isinstance(a, (np.ndarray, np.memmap)):
rval = a.copy(order="K")
elif isinstance(a, _cdata_type):
# This is not copyable (and should be used for constant data).
rval = a
else:
rval = copy.deepcopy(a)
assert type(rval) == type(a), (type(rval), type(a))
if isinstance(rval, np.ndarray):
assert rval.dtype == a.dtype
return rval
def _find_bad_optimizations(order, reasons, r_vals):
"""Iterate over variables looking for values that don't match the values of the variables they replaced.
This is a sign of a broken optimization.
This algorithm is simple to understand, but sometimes when there's
a problem it identifies the wrong optimization as the culprit.
The problem stems from the fact that results are not evaluated in
chronological order (looking at when they were introduced to the
graph).
"""
for i, node in enumerate(order):
for new_r in node.outputs:
for reason, r, old_graph_str, new_graph_str in reasons[new_r]:
# check if the value for new_r doesn't match the value for r
new_r_val = r_vals[new_r]
r_val = r_vals[r]
assert r.type.is_super(new_r.type)
if hasattr(new_r.tag, "values_eq_approx"):
check = new_r.tag.values_eq_approx(r_val, new_r_val)
elif hasattr(new_r, "values_eq_approx"):
# This way will be deprecated later, but not right now
check = new_r.values_eq_approx(r_val, new_r_val)
else:
check = r.type.values_eq_approx(r_val, new_r_val)
if not check:
raise BadOptimization(
old_r=r,
new_r=new_r,
old_r_val=r_val,
new_r_val=new_r_val,
reason=reason,
old_graph=old_graph_str,
new_graph=new_graph_str,
)
def _get_preallocated_maps(
node,
thunk,
prealloc_modes,
def_val,
storage_map,
r_vals,
dr_vals,
perform,
active_order_set,
inplace_outs,
init_outputs,
):
"""
Preallocate outputs in different memory layouts.
"""
# TODO: Sparse? Scalar does not really make sense.
# Do not preallocate memory for outputs that actually work inplace
considered_outputs = []
for r in node.outputs:
if r not in inplace_outs:
considered_outputs.append(r)
# Output storage that was initially present in the storage_map
if "initial" in prealloc_modes or "ALL" in prealloc_modes:
initial_outputs = {}
for r in considered_outputs:
if r in init_outputs:
initial_outputs[r] = init_outputs[r]
if initial_outputs:
yield ("initial", initial_outputs)
# reuse_output: use a copy of the same storage returned the first time
# TODO: optimization warning if the storage in reuse_outputs
# is not reused
if "previous" in prealloc_modes or "ALL" in prealloc_modes:
reuse_outputs = {}
for r in considered_outputs:
# We want to reuse the exact same memory buffer,
# so we keep the copy in r_vals
new_r = _lessbroken_deepcopy(r_vals[r])
reuse_outputs[r] = r_vals[r]
r_vals[r] = new_r
# Sometimes, outputs can be aliased together.
# I'm not sure why it is legitimate, but there are tests about it.
# So, we cannot fill r_vals[r] with def_val yet, we have to wait
# until all output values are deepcopied.
for r in considered_outputs:
# There is no risk to overwrite inputs, since r does not work
# inplace.
if isinstance(r.type, TensorType):
reuse_outputs[r][...] = np.asarray(def_val).astype(r.type.dtype)
if reuse_outputs:
yield ("previous", reuse_outputs)
# clear memory that is not needed any more
del reuse_outputs
# c_cont_output: use a c-continuous array
# (for TensorType, else None)
if "c_contiguous" in prealloc_modes or "ALL" in prealloc_modes:
c_cont_outputs = {}
for r in considered_outputs:
if isinstance(r.type, TensorType):
# Build a C-contiguous buffer
new_buf = np.empty(r_vals[r].shape, dtype=r.type.dtype)
assert new_buf.flags["C_CONTIGUOUS"]
new_buf[...] = np.asarray(def_val).astype(r.type.dtype)
c_cont_outputs[r] = new_buf
if len(c_cont_outputs):
yield ("c_contiguous", c_cont_outputs)
del c_cont_outputs
# f_cont_output: use a fortran-continuous ndarray
# (for TensorType, only)
if "f_contiguous" in prealloc_modes or "ALL" in prealloc_modes:
f_cont_outputs = {}
for r in considered_outputs:
if isinstance(r.type, TensorType):
new_buf = np.zeros(
shape=r_vals[r].shape, dtype=r_vals[r].dtype, order="F"
)
new_buf[...] = def_val
f_cont_outputs[r] = new_buf
if len(f_cont_outputs):
yield ("f_contiguous", f_cont_outputs)
del f_cont_outputs
# We assume that the different outputs of a same Op will behave
# independently, and there is no need to test over all combinations
# of outputs (the time taken is prohibitive).
# When all outputs on a certain dimension are broadcastable, the Op
# can assume that the shape is 1 on that dimension, and stride testing
# is less relevant.
# Dimensions should be align by the innermost index, so we iterate
# from the end of shapes.
if (
"strided" in prealloc_modes
or "wrong_size" in prealloc_modes
or "ALL" in prealloc_modes
):
max_ndim = 0
rev_out_shape = []
for r in considered_outputs:
if isinstance(r.type, TensorType):
if max_ndim < r.ndim:
rev_out_shape += [1] * (r.ndim - max_ndim)
max_ndim = r.ndim
assert len(rev_out_shape) == max_ndim
for i, s in enumerate(r.type.shape[::-1]):
rev_out_shape[i] = 1 if rev_out_shape[i] == 1 and s == 1 else None
out_shape = rev_out_shape[::-1]
if "strided" in prealloc_modes or "ALL" in prealloc_modes:
check_ndim = config.DebugMode__check_preallocated_output_ndim
# Initial allocation
init_strided = {}
for r in considered_outputs:
if isinstance(r.type, TensorType):
# Create a buffer twice as large in every dimension,
# except if broadcastable, or for dimensions above
# config.DebugMode__check_preallocated_output_ndim
buf_shape = []
for s, b in zip(r_vals[r].shape, r.broadcastable):
if b or ((r.ndim - len(buf_shape)) > check_ndim):
buf_shape.append(s)
else:
buf_shape.append(s * 2)
new_buf = np.empty(buf_shape, dtype=r.type.dtype)
new_buf[...] = np.asarray(def_val).astype(r.type.dtype)
init_strided[r] = new_buf
# The number of combinations is exponential in the number of
# dimensions, and some ops can have tens of outputs. To prevent
# tests from lasting days, we use the same strides for all
# dimensions but the last check_ndim ones.
# Moreover, to avoid memory problems, we do not test with strides
# 2 and -2 on those dimensions.
step_signs_list = []
for s in out_shape[-check_ndim:]:
if s == 1:
step_signs_list.append((1,))
else:
step_signs_list.append((-1, 1))
# Use the same step on all dimensions before the last check_ndim.
if all(s == 1 for s in out_shape[:-check_ndim]):
step_signs_list = [(1,)] + step_signs_list
else:
step_signs_list = [(-1, 1)] + step_signs_list
for step_signs in itertools_product(*step_signs_list):
for step_size in (1, 2):
strided = {}
# First, the dimensions above check_ndim, then the other ones
# Do not test with 2 or -2 for dimensions above check_ndim
steps = [step_signs[0]] * len(out_shape[:-check_ndim])
steps += [s * step_size for s in step_signs[1:]]
name = f"strided{tuple(steps)}"
for r in considered_outputs:
if r in init_strided:
strides = []
shapes = []
for i, size in enumerate(r_vals[r].shape):
shapes.append(slice(None, size, None))
strides.append(slice(None, None, steps[i]))
r_buf = init_strided[r]
if r_buf.ndim > 0:
r_buf = r_buf[tuple(strides)][tuple(shapes)]
assert r_buf.shape == r_vals[r].shape
r_buf[...] = np.asarray(def_val).astype(r_buf.dtype)
strided[r] = r_buf
if strided:
yield (name, strided)
del strided
if "wrong_size" in prealloc_modes or "ALL" in prealloc_modes:
# For each dimension, try size-1, size, size+1
for dim, s in enumerate(out_shape):
if s == 1:
# The shape has to be 1
continue
shape_diff = [0] * max_ndim
for diff in (-1, 1):
shape_diff[dim] = diff
wrong_size = {}
name = f"wrong_size{tuple(shape_diff)}"
for r in considered_outputs:
if isinstance(r.type, TensorType):
r_shape_diff = shape_diff[: r.ndim]
new_buf_shape = [
max((s + sd), 0)
for s, sd in zip(r_vals[r].shape, r_shape_diff)
]
new_buf = np.empty(new_buf_shape, dtype=r.type.dtype)
new_buf[...] = np.asarray(def_val).astype(r.type.dtype)
wrong_size[r] = new_buf
if wrong_size:
yield (name, wrong_size)
del wrong_size
def _check_preallocated_output(
fgraph,
node,
thunk,
prealloc_modes,
def_val,
storage_map,
r_vals,
dr_vals,
perform,
active_order_set,
inplace_outs,
init_outputs,
):
"""
Try to apply thunk() on different output storages.
"""
# If node has an inner compiled Aesara function with mode DebugMode,
# disable memory checks in that mode, since they were already run.
try:
changed_inner_mode = False
if isinstance(getattr(node, "op", None), HasInnerGraph):
fn = node.op.fn
if not fn or not hasattr(fn, "maker") or not hasattr(fn.maker, "mode"):
_logger.warning(f"Expected aesara function not found in {node.op}.fn")
else:
if isinstance(fn.maker.mode, DebugMode):
backup_mode = fn.maker.mode
new_mode = copy.copy(backup_mode)
# Disactivate as many checks as possible
new_mode.check_py_code = False
new_mode.check_isfinite = False
new_mode.require_matching_strides = 0
new_mode.check_preallocated_output = []
new_mode.stability_patience = 1
fn.maker.mode = new_mode
changed_inner_mode = True
_logger.info("changing inner mode")