-
Notifications
You must be signed in to change notification settings - Fork 112
/
basic.py
1226 lines (1017 loc) · 40.2 KB
/
basic.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
"""Tensor optimizations addressing the ops in basic.py.
Notes
-----
There are two ways of broadcasting arrays:
second(x, y) == alloc(y, broadcast_shapes(x.shape, y.shape))
The second can be more efficient because x doesn't usually need to be computed when we only want its shape.
It may also allow other rewrites that don't try to modify x when it has multiple clients (for fear of duplicating computation).
However, the first one is easier to reason about.
Knowing we have such a graph allows to do certain rewrites such as "sinking" broadcasting operations below Elemwise.
The same rewrites with alloc would be more complicated as we would need to symbolically combine the shapes of each one.
As an example contrast rewriting the following two equivalent graphs
alloc(x, broadcast_shapes(x.shape, y.shape)) + alloc(y, broadcast_shapes(x.shape, y.shape)) -> x + y
second(y, x) + second(x, y) -> x + y
Theano developers (mostly) preferred to use the first form during canonicalization and introduce the second form later,
via rewrites like `local_fill_to_alloc`, and using the `alloc_like` helper inside rewrites.
Many stabilize and stabilization rewrites refuse to be applied when a variable has multiple clients, so this is important.
"""
import logging
import numpy as np
import pytensor.scalar.basic as ps
from pytensor import compile, config
from pytensor.compile.ops import ViewOp
from pytensor.graph import FunctionGraph
from pytensor.graph.basic import Constant, Variable
from pytensor.graph.rewriting.basic import (
NodeRewriter,
RemovalNodeRewriter,
Rewriter,
copy_stack_trace,
in2out,
node_rewriter,
)
from pytensor.graph.rewriting.db import RewriteDatabase
from pytensor.raise_op import Assert, CheckAndRaise, assert_op
from pytensor.tensor.basic import (
Alloc,
AllocEmpty,
Join,
MakeVector,
ScalarFromTensor,
Split,
TensorFromScalar,
alloc,
as_tensor_variable,
cast,
extract_constant,
fill,
get_underlying_scalar_constant_value,
join,
ones_like,
register_infer_shape,
switch,
tensor_copy,
zeros,
zeros_like,
)
from pytensor.tensor.elemwise import DimShuffle, Elemwise
from pytensor.tensor.exceptions import NotScalarConstantError
from pytensor.tensor.extra_ops import broadcast_arrays
from pytensor.tensor.math import Sum, add, eq
from pytensor.tensor.shape import Shape_i, shape_padleft
from pytensor.tensor.type import DenseTensorType, TensorType
from pytensor.tensor.variable import TensorConstant, TensorVariable
from pytensor.utils import NoDuplicateOptWarningFilter
_logger = logging.getLogger("pytensor.tensor.rewriting.basic")
_logger.addFilter(NoDuplicateOptWarningFilter())
def broadcasted_by(x: TensorVariable, y: TensorVariable) -> bool:
"""Check whether x would be broadcasted by y in an Elemwise operation
Parameters
----------
x: TensorVariable
The variable that may be broadcasted by y
y: TensorVariable
The variable that may broadcast x
Returns
-------
broadcasted_by: bool
"""
bx = x.type.broadcastable
by = y.type.broadcastable
if len(bx) < len(by):
return True
bx = bx[-len(by) :]
return any(bx_dim and not by_dim for bx_dim, by_dim in zip(bx, by))
def merge_broadcastables(broadcastables):
return [all(bcast) for bcast in zip(*broadcastables)]
def alloc_like(
value: TensorVariable,
template: TensorVariable,
fgraph: FunctionGraph,
dtype=None,
) -> TensorVariable:
"""Fill value to the same shape and dtype as the template via alloc."""
value = as_tensor_variable(value)
if value.type.is_super(template.type):
return value
if template not in fgraph.variables:
raise NotImplementedError(
"broadcast_like currently requires the "
"template Variable to be in the fgraph already"
)
if dtype is None:
dtype = template.dtype
value = cast(value, dtype)
if value.type.is_super(template.type):
return value
if hasattr(fgraph, "shape_feature"):
new_shape = fgraph.shape_feature.shape_of[template]
else:
new_shape = template.shape
rval = alloc(value, *new_shape)
assert rval.type.dtype == dtype
return rval
def register_useless(
node_rewriter: RewriteDatabase | NodeRewriter | str, *tags, **kwargs
):
if isinstance(node_rewriter, str):
def register(inner_rewriter: RewriteDatabase | Rewriter):
return register_useless(inner_rewriter, node_rewriter, *tags, **kwargs)
return register
else:
name = kwargs.pop("name", None) or node_rewriter.__name__
compile.mode.local_useless.register(
name, node_rewriter, "fast_run", *tags, position="last", **kwargs
)
return node_rewriter
def register_canonicalize(
node_rewriter: RewriteDatabase | NodeRewriter | str, *tags: str, **kwargs
):
if isinstance(node_rewriter, str):
def register(inner_rewriter: RewriteDatabase | Rewriter):
return register_canonicalize(inner_rewriter, node_rewriter, *tags, **kwargs)
return register
else:
name = kwargs.pop("name", None) or node_rewriter.__name__
compile.optdb["canonicalize"].register(
name, node_rewriter, "fast_run", "fast_compile", *tags, **kwargs
)
return node_rewriter
def register_stabilize(
node_rewriter: RewriteDatabase | NodeRewriter | str, *tags: str, **kwargs
):
if isinstance(node_rewriter, str):
def register(inner_rewriter: RewriteDatabase | Rewriter):
return register_stabilize(inner_rewriter, node_rewriter, *tags, **kwargs)
return register
else:
name = kwargs.pop("name", None) or node_rewriter.__name__
compile.optdb["stabilize"].register(
name, node_rewriter, "fast_run", *tags, **kwargs
)
return node_rewriter
def register_specialize(
node_rewriter: RewriteDatabase | NodeRewriter | str, *tags: str, **kwargs
):
if isinstance(node_rewriter, str):
def register(inner_rewriter: RewriteDatabase | Rewriter):
return register_specialize(inner_rewriter, node_rewriter, *tags, **kwargs)
return register
else:
name = kwargs.pop("name", None) or node_rewriter.__name__
compile.optdb["specialize"].register(
name, node_rewriter, "fast_run", *tags, **kwargs
)
return node_rewriter
def register_uncanonicalize(
node_rewriter: RewriteDatabase | NodeRewriter | str, *tags: str, **kwargs
):
if isinstance(node_rewriter, str):
def register(inner_rewriter: RewriteDatabase | Rewriter):
return register_uncanonicalize(
inner_rewriter, node_rewriter, *tags, **kwargs
)
return register
else:
name = (kwargs and kwargs.pop("name", None)) or node_rewriter.__name__
compile.optdb["uncanonicalize"].register(
name, node_rewriter, "fast_run", *tags, **kwargs
)
return node_rewriter
@register_canonicalize
@register_specialize
@node_rewriter([TensorFromScalar])
def local_tensor_scalar_tensor(fgraph, node):
"""tensor_from_scalar(scalar_from_tensor(x)) -> x"""
if isinstance(node.op, TensorFromScalar):
s = node.inputs[0]
if s.owner and isinstance(s.owner.op, ScalarFromTensor):
t = s.owner.inputs[0]
# We don't need to copy over any stack traces here
return [t]
@register_canonicalize
@register_specialize
@node_rewriter([ScalarFromTensor])
def local_scalar_tensor_scalar(fgraph, node):
"""scalar_from_tensor(tensor_from_scalar(x)) -> x"""
if isinstance(node.op, ScalarFromTensor):
t = node.inputs[0]
if t.owner and isinstance(t.owner.op, TensorFromScalar):
s = t.owner.inputs[0]
# We don't need to copy over any stack traces here
return [s]
@register_specialize("shape_unsafe")
@node_rewriter([Elemwise])
def local_elemwise_alloc(fgraph, node):
r"""Remove unnecessary `Alloc`\s that occur as inputs of `Elemwise` `Op`\s.
The rewrite essentially performs the following replacement:
``Elemwise{op}(..., Alloc(x, s), ..., y, ...) -> Elemwise{op}(..., x, ..., y, ...)``
In its current form, it also explicitly accounts for `DimShuffle`\s of
`Alloc`\s. This is largely due to `local_alloc_sink_dimshuffle`, which
introduces them as a canonicalization of `Alloc`'s with leading
broadcastable dimensions.
"""
# This is handled by local_alloc_unary
if len(node.inputs) == 1:
return None
def dimshuffled_alloc(i):
return (
isinstance(i.owner.op, DimShuffle)
and i.owner.inputs[0].owner
and isinstance(i.owner.inputs[0].owner.op, Alloc)
)
# At least one input must have an owner that is either a `Alloc` or a
# `DimShuffle` with an owner that is a `Alloc` -- otherwise there is
# nothing to optimize.
alloc_idxs = [
idx
for idx, i in enumerate(node.inputs)
if i.owner and (isinstance(i.owner.op, Alloc) or dimshuffled_alloc(i))
]
if len(alloc_idxs) == 0:
return False
new_inputs = list(node.inputs)
for idx in alloc_idxs:
i = node.inputs[idx]
# Remove simple `Alloc`
if isinstance(i.owner.op, Alloc):
new_inp = i.owner.inputs[0]
# Remove `Dimshuffle(Alloc)`
elif isinstance(i.owner.op, DimShuffle):
old_alloc = i.owner.inputs[0]
old_alloc_inp = old_alloc.owner.inputs[0]
missing_ndims = old_alloc.type.ndim - old_alloc_inp.type.ndim
if missing_ndims > 0:
# The `Alloc` added new dimensions to the left.
# We replace those cases with a `DimShuffle` here.
# Nested dimshuffles will be merged later by other rewrites.
old_alloc_inp = shape_padleft(old_alloc_inp, missing_ndims)
# We need to keep the old `DimShuffle`. It could swap axes or
# add dimensions anywhere.
new_inp = i.owner.op(old_alloc_inp)
copy_stack_trace(i, new_inp)
new_inputs[idx] = new_inp
new_outs = node.op(*new_inputs, return_list=True)
if new_outs[0].type.broadcastable != node.outputs[0].type.broadcastable:
new_outs = [
alloc_like(new_out, node.outputs[0], fgraph) for new_out in new_outs
]
copy_stack_trace(node.outputs, new_outs)
return new_outs
@register_canonicalize("shape_unsafe")
@node_rewriter([Elemwise])
def local_fill_sink(fgraph, node):
"""
f(fill(a, b), fill(c, d), e) -> fill(c, fill(a, f(b, d, e)))
f need to be an elemwise that isn't a fill.
"""
if not hasattr(node, "op") or not isinstance(node.op, Elemwise) or node.op == fill:
return False
models = []
inputs = []
for inp in node.inputs:
if inp.owner and inp.owner.op == fill:
models.append(inp.owner.inputs[0])
inputs.append(inp.owner.inputs[1])
else:
inputs.append(inp)
if not models:
return False
c = node.op(*inputs)
for model in models:
if (
model.type.dtype != c.type.dtype
or model.type.broadcastable != c.type.broadcastable
):
c = fill(model, c)
# The newly created node c doesn't has 'clients',
# so this iteration is took place with node.outputs[0]
# TODO: This should just be a WalkingGraphRewrite!
replacements = {node.outputs[0]: c}
for client, cl_idx in fgraph.clients[node.outputs[0]]:
if (
hasattr(client, "op")
and isinstance(client.op, Elemwise)
and client.op != fill
):
client_inputs = client.inputs[:]
client_inputs[cl_idx] = c
new_client = client.op(*client_inputs)
# Add clients to new_client
fgraph.clients[new_client.owner.outputs[0]] = fgraph.clients[
client.outputs[0]
]
r = local_fill_sink.transform(fgraph, new_client.owner)
if not r:
continue
replacements.update(r)
return replacements
@register_specialize("shape_unsafe")
@register_stabilize("shape_unsafe")
@node_rewriter([fill])
def local_fill_to_alloc(fgraph, node):
r"""Remove `fill`\s or replace them with `Alloc`\s.
`Alloc`\s are preferable because they replace explicit tensor dependencies
with their dependencies on those tensors' shapes, and sometimes those
shapes can be computed without needing to compute the tensors themselves.
Like `local_fill_sink` this rewrites assumes non-broadcastable shapes are equivalent,
which could mask shape errors.
"""
shape_ref, values_ref = node.inputs
out_type = node.outputs[0].type
if values_ref.type.broadcastable == out_type.broadcastable:
# The assumption here is that `values_ref` already has the same shape
# as `shape_ref`, so a `fill`/`Alloc` is unnecessary.
return [values_ref]
if shape_ref.type.broadcastable == out_type.broadcastable:
# In this case, we assume that some broadcasting is needed (otherwise
# the condition above would've been true), so we replace the `fill`
# with an `Alloc`.
o = alloc_like(values_ref, shape_ref, fgraph, dtype=values_ref.dtype)
copy_stack_trace(node.outputs[0], o)
return [o]
# The case that is not covered is when `shape_ref` is broadcasted by `values_ref`
# TODO: Return broadcast_to(values_ref, broadcast_shapes(values_ref.shape, shape_ref.shape))
return
# Register this after stabilize at 1.5 to make sure stabilize don't
# get affected by less canonicalized graph due to alloc.
compile.optdb.register(
"local_fill_to_alloc", in2out(local_fill_to_alloc), "fast_run", position=1.51
)
# Needed to clean some extra alloc added by local_fill_to_alloc
compile.optdb.register(
"local_elemwise_alloc", in2out(local_elemwise_alloc), "fast_run", position=1.52
)
@register_infer_shape
@register_canonicalize("fast_compile", "shape_unsafe")
@register_useless("shape_unsafe")
@node_rewriter([fill])
def local_useless_fill(fgraph, node):
"""fill(s,v) -> v
This rewrite is only needed in FAST_COMPILE mode to make the code
more readable. Normally, it is done by the `local_fill_to_alloc`
rewrite.
"""
r, v = node.inputs
out_type = node.outputs[0].type
if (
v.type.dtype == out_type.dtype
and v.type.broadcastable == out_type.broadcastable
):
return [v]
@register_infer_shape
@register_specialize("shape_unsafe")
@register_stabilize("shape_unsafe")
@register_canonicalize("shape_unsafe")
@register_useless("shape_unsafe")
@node_rewriter([Alloc])
def local_useless_alloc(fgraph, node):
"""
If the input type is the same as the output type (dtype and broadcast)
there is no change in the shape of the input. So this is just a simple copy
of the input. This is not needed.
"""
if not isinstance(node.op, Alloc):
return False
inp = node.inputs[0]
output = node.outputs[0]
if (
inp.type.dtype == output.type.dtype
and inp.type.broadcastable == output.type.broadcastable
):
return [inp]
@register_specialize
@register_stabilize
@register_canonicalize
@node_rewriter([Alloc])
def local_alloc_sink_dimshuffle(fgraph, node):
r"""Convert broadcastable leading dimensions in an `Alloc` to `DimShuffle`\s."""
op = node.op
if not isinstance(op, Alloc):
return False
inp = node.inputs[0]
output = node.outputs[0]
# Check if alloc adds a broadcastable dimension with shape 1.
output_shape = node.inputs[1:]
num_dims_with_size_1_added_to_left = 0
for i in range(len(output_shape) - inp.ndim):
if extract_constant(output_shape[i], only_process_constants=True) == 1:
num_dims_with_size_1_added_to_left += 1
else:
break
new_output_shape = output_shape[num_dims_with_size_1_added_to_left:]
if num_dims_with_size_1_added_to_left > 0 and len(new_output_shape) >= inp.ndim:
if (
output.broadcastable[num_dims_with_size_1_added_to_left:]
== inp.broadcastable
):
inner = inp
else:
inner = op(*([inp, *new_output_shape]))
dimshuffle_new_order = ["x"] * num_dims_with_size_1_added_to_left + list(
range(len(new_output_shape))
)
return [DimShuffle(inner.type.broadcastable, dimshuffle_new_order)(inner)]
@node_rewriter([AllocEmpty])
def local_alloc_empty_to_zeros(fgraph, node):
"""This convert AllocEmpty to Alloc of 0.
This helps one investigate NaNs in `NanGuardMode`. Not registered by
default. To activate it, use the setting
``optimizer_including == alloc_empty_to_zeros``.
"""
if isinstance(node.op, AllocEmpty):
return [zeros(node.inputs, dtype=node.outputs[0].dtype)]
compile.optdb.register(
"local_alloc_empty_to_zeros",
in2out(local_alloc_empty_to_zeros),
# After move to gpu and merge2, before inplace.
"alloc_empty_to_zeros",
position=49.3,
)
@register_infer_shape
@register_useless
@register_canonicalize("fast_compile")
@register_specialize
@node_rewriter([Elemwise])
def local_useless_elemwise(fgraph, node):
"""
eq(x, x) -> 1
neq(x, x) -> 0
mul(x) -> x
add(x) -> x
identity(x) -> x
and(x, 1) -> x (if x.dtype == 'bool')
and(x, 0) -> zeros_like(x)
or(x, 0) -> x
or(x, 1) -> ones_like(x) (if x.dtype == 'bool')
xor(x, x) -> zeros_like(x)
TODO: This implementation is painfully redundant.
"""
if isinstance(node.op, Elemwise):
# We call zeros_like and one_like with opt=True to generate a
# cleaner graph.
dtype = node.outputs[0].dtype
if node.op.scalar_op == ps.eq and len(node.inputs) == 2:
if node.inputs[0] == node.inputs[1]:
# it is the same var in the graph. That will always be true
ret = ones_like(node.inputs[0], dtype=dtype, opt=True)
# Copy stack trace from input to constant output
copy_stack_trace(node.outputs[0], ret)
return [ret]
elif node.op.scalar_op == ps.neq and len(node.inputs) == 2:
if node.inputs[0] == node.inputs[1]:
# it is the same var in the graph. That will always be false
ret = zeros_like(node.inputs[0], dtype=dtype, opt=True)
# Copy stack trace from input to constant output
copy_stack_trace(node.outputs[0], ret)
return [ret]
elif node.op.scalar_op == ps.mul and len(node.inputs) == 1:
# No need to copy over any stack trace
return [node.inputs[0]]
elif node.op.scalar_op == ps.add and len(node.inputs) == 1:
# No need to copy over any stack trace
return [node.inputs[0]]
elif node.op.scalar_op == ps.identity and len(node.inputs) == 1:
return [node.inputs[0]]
elif isinstance(node.op.scalar_op, ps.AND) and len(node.inputs) == 2:
if isinstance(node.inputs[0], TensorConstant):
const_val = extract_constant(
node.inputs[0], only_process_constants=True
)
if not isinstance(const_val, Variable):
if const_val == 0:
return [zeros_like(node.inputs[1], dtype=dtype, opt=True)]
elif node.outputs[0].dtype == "bool":
# If the output is not Boolean, it is the bitwise AND,
# and this rewrite would be wrong
return [node.inputs[1].astype(node.outputs[0].dtype)]
if isinstance(node.inputs[1], TensorConstant):
const_val = extract_constant(
node.inputs[1], only_process_constants=True
)
if not isinstance(const_val, Variable):
if const_val == 0:
return [zeros_like(node.inputs[0], dtype=dtype, opt=True)]
elif node.outputs[0].dtype == "bool":
# If the output is not Boolean, it is the bitwise AND,
# and this rewrite would be wrong
return [node.inputs[0].astype(node.outputs[0].dtype)]
elif isinstance(node.op.scalar_op, ps.OR) and len(node.inputs) == 2:
if isinstance(node.inputs[0], TensorConstant):
const_val = extract_constant(
node.inputs[0], only_process_constants=True
)
if not isinstance(const_val, Variable):
if const_val == 0:
return [node.inputs[1].astype(node.outputs[0].dtype)]
elif node.outputs[0].dtype == "bool":
# If the output is not Boolean, it is the bitwise OR,
# and this rewrite would be wrong
return [ones_like(node.inputs[1], dtype=dtype, opt=True)]
if isinstance(node.inputs[1], TensorConstant):
const_val = extract_constant(
node.inputs[1], only_process_constants=True
)
if not isinstance(const_val, Variable):
if const_val == 0:
return [node.inputs[0].astype(node.outputs[0].dtype)]
elif node.outputs[0].dtype == "bool":
# If the output is not Boolean, it is the bitwise OR,
# and this rewrite would be wrong
return [ones_like(node.inputs[0], dtype=dtype, opt=True)]
elif isinstance(node.op.scalar_op, ps.XOR) and len(node.inputs) == 2:
if node.inputs[0] is node.inputs[1]:
return [zeros_like(node.inputs[0], dtype=dtype, opt=True)]
@register_specialize
@node_rewriter([Elemwise])
def local_alloc_unary(fgraph, node):
"""unary(alloc(x, shp)) -> alloc(unary(x), shp)"""
if isinstance(node.op, Elemwise) and len(node.inputs) == 1:
a = node.inputs[0]
if a.owner and isinstance(a.owner.op, Alloc):
x = a.owner.inputs[0]
shp = a.owner.inputs[1:]
v = node.op(x)
# at.alloc does not preserve the stacktrace of v,
# so we need to copy it over from x.
copy_stack_trace(node.outputs[0], v)
ret = alloc(cast(v, node.outputs[0].dtype), *shp)
# at.cast does not preserve the stacktrace of x,
# so we need to copy it over to the output.
copy_stack_trace([node.outputs[0], a], ret)
return [ret]
@register_canonicalize
@register_specialize
@node_rewriter([Elemwise])
def local_cast_cast(fgraph, node):
"""cast(cast(x, dtype1), dtype2)
when those constrain:
dtype1 == dtype2
OR the base dtype is the same (int, uint, float, complex)
and the first cast cause an upcast.
"""
if not isinstance(node.op, Elemwise) or not isinstance(node.op.scalar_op, ps.Cast):
return
x = node.inputs[0]
if (
not x.owner
or not isinstance(x.owner.op, Elemwise)
or not isinstance(x.owner.op.scalar_op, ps.Cast)
):
return
type1 = x.owner.op.scalar_op.o_type
type2 = node.op.scalar_op.o_type
base = x.owner.inputs[0]
if type1 == type2:
# We don't need to copy over any stack traces here
return [x]
if is_an_upcast(base.dtype, type1.dtype):
# Checking for further redundancy. Eg: int8 -> int32 -> int8
if type2.dtype == base.dtype:
return x.owner.inputs
else:
# Apply the second cast only
v = node.op(base)
# Copy stack trace from the output of the original cast
copy_stack_trace(node.outputs[0], v)
return [v]
def is_an_upcast(type1, type2):
"""Given two data types (as strings), check if converting to
type2 from type1 constitutes an upcast.
Differs from pytensor.scalar.upcast
"""
category = {
# The first number in the pair is the dtype (bool, uint, int, float,
# complex). Conversion from higher to lower is never an upcast.
# The second number roughly indicates the precision. Again, conversion
# from higher to lower is never an upcast.
"bool": (0, 0),
"uint8": (1, 1),
"uint16": (1, 2),
"uint32": (1, 3),
"uint64": (1, 4),
"int8": (2, 1),
"int16": (2, 2),
"int32": (2, 3),
"int64": (2, 4),
"float16": (3, 1.5),
"float32": (3, 2.5),
"float64": (3, 3.5),
"complex64": (4, 3),
"complex128": (4, 4),
}
cat1 = category[type1]
cat2 = category[type2]
if cat2[0] >= cat1[0] and cat2[1] > cat1[1]:
return True
else:
return False
@register_useless
@register_specialize
@node_rewriter(None)
def local_remove_useless_assert(fgraph, node):
if not isinstance(node.op, CheckAndRaise):
return False
new_conds = []
n_conds = len(node.inputs[1:])
for c in node.inputs[1:]:
try:
const = get_underlying_scalar_constant_value(c)
if 0 != const.ndim or const == 0:
# Should we raise an error here? How to be sure it
# is not caught?
new_conds.append(c)
except NotScalarConstantError:
new_conds.append(c)
if len(new_conds) == 0:
return [node.inputs[0]]
if len(new_conds) < n_conds:
new_var = node.op(*(node.inputs[:1] + new_conds))
copy_stack_trace(node.outputs[0], new_var)
return [new_var]
@node_rewriter([Assert])
def local_remove_all_assert(fgraph, node):
r"""A rewrite that removes all `Assert`\s from a graph.
Notes
-----
See the :ref:`unsafe` section.
"""
if not isinstance(node.op, Assert):
return
return [node.inputs[0]]
compile.optdb["canonicalize"].register(
"local_remove_all_assert",
local_remove_all_assert,
"unsafe",
use_db_name_as_tag=False,
)
compile.optdb["stabilize"].register(
"local_remove_all_assert",
local_remove_all_assert,
"unsafe",
use_db_name_as_tag=False,
)
compile.optdb["specialize"].register(
"local_remove_all_assert",
local_remove_all_assert,
"unsafe",
use_db_name_as_tag=False,
)
compile.optdb["useless"].register(
"local_remove_all_assert",
local_remove_all_assert,
"unsafe",
use_db_name_as_tag=False,
)
@register_infer_shape
@register_specialize
@register_canonicalize
@register_useless
@node_rewriter([Join])
def local_join_1(fgraph, node):
"""Join(i, x) => x
Remove Join() when only one element is joined.
"""
if not isinstance(node.op, Join):
return
tensors = node.inputs[1:]
if len(tensors) == 1:
# We don't need to copy over any stacktrace here, because the
# input variable should already have its own stacktrace.
return [tensors[0]]
# TODO: merge in local_useless_join
@register_infer_shape
@register_useless
@register_specialize
@register_canonicalize
@node_rewriter([Join])
def local_join_empty(fgraph, node):
"""Join(i, x, y, empty) => Join(i, x, y)
Remove empty inputs to joins. The empty inputs can be anywhere.
"""
if not isinstance(node.op, Join):
return
new_inputs = []
try:
join_idx = get_underlying_scalar_constant_value(
node.inputs[0], only_process_constants=True
)
except NotScalarConstantError:
return
for idx in range(1, len(node.inputs)):
inp = node.inputs[idx]
# We can not use size == 0,, as this can change shape from 3,0
# to 2,0. This trigger DebugMode error. This happen with
# stack(...,[]) as this add a dimshuffle on [], that add a
# dimensions with shape 1.
if isinstance(inp, Constant) and inp.data.shape[join_idx] == 0:
continue
new_inputs.append(inp)
if len(new_inputs) < len(node.inputs) - 1:
if len(new_inputs) == 0:
# at.join do not work in that case.
# constant folding will take care of this case.
return
ret = join(node.inputs[0], *new_inputs)
o = node.outputs[0]
if ret.dtype != o.dtype:
# Join can upcast some inputs
return
# Copy over stacktrace from previous output (after join op)
# to new output, because an error in the new op must be caused
# by an error in the old join op.
copy_stack_trace(node.outputs, ret)
return [ret]
@register_specialize
@register_canonicalize
@register_useless
@node_rewriter([Join])
def local_join_make_vector(fgraph, node):
r"""Merge `MakeVector` inputs within a `Join`.
For example:
Join(0, make_vector1, make_vector2, ...) => Join(0, make_vector12, ...)
This, in combination with the `local_join_1` rewrite, can make `Join`\s
completely disappear.
"""
if not isinstance(node.op, Join) or node.outputs[0].ndim != 1:
return
new_inputs = [node.inputs[1]]
for idx in range(2, len(node.inputs)):
inp = node.inputs[idx]
if (
inp.owner
and isinstance(inp.owner.op, MakeVector)
and new_inputs[-1].owner
and isinstance(new_inputs[-1].owner.op, MakeVector)
and
# MakeVector have a dtype parameter
inp.owner.op == new_inputs[-1].owner.op
):
inps = new_inputs[-1].owner.inputs + inp.owner.inputs
new_inputs[-1] = inp.owner.op(*inps)
# Copy over stacktrace from previous output (after join op)
# to new intermediate output, because an error in the intermediate
# op must be caused by an error in the old join op.
copy_stack_trace(node.outputs, new_inputs[-1])
else:
new_inputs.append(inp)
if len(new_inputs) < len(node.inputs) - 1:
ret = join(node.inputs[0], *new_inputs)
# Copy over stacktrace from previous output (after join op)
# to new output, because an error in the new op must be caused
# by an error in the old join op.
copy_stack_trace(node.outputs, ret)
return [ret]
@register_specialize
@register_canonicalize
@register_useless
@node_rewriter([Sum])
def local_sum_make_vector(fgraph, node):
"""A sum of a MakeVector node is just the sum of the elements."""
(array,) = node.inputs
if array.owner is None:
return
if not isinstance(array.owner.op, MakeVector):
return
if node.op.axis == ():
return [array]
# If this is not the case the sum is invalid
assert node.op.axis is None or node.op.axis == (0,) or node.op.axis == (-1,)
elements = array.owner.inputs
acc_dtype = node.op.acc_dtype
out_dtype = node.op.dtype
# Skip rewrite if it would add unnecessary float64 to the graph
if acc_dtype == "float64" and out_dtype != "float64" and config.floatX != "float64":
return
if len(elements) == 0:
element_sum = zeros(dtype=out_dtype, shape=())
elif len(elements) == 1:
element_sum = cast(elements[0], out_dtype)
else:
element_sum = cast(
add(*[cast(value, acc_dtype) for value in elements]), out_dtype
)
return [element_sum]
def equivalent_up_to_constant_casting(a, b) -> bool:
"""Return True if a and b are equivalent up to constant casting."""
if a == b:
return True
# Return equivalence based on data values, ignoring dtype
if (
isinstance(a, TensorConstant)
and isinstance(b, TensorConstant)
and a.type.shape == b.type.shape
# We don't want to spend a lot of time comparing large constant arrays
# First, check if dtype matches, otherwise a == b would be true if they hold the same values
and a.type.dtype != b.type.dtype
# Check property sum() that is cached for TensorConstants, to filter down candidates even more
and a.signature().sum == b.signature().sum
):
return np.array_equal(a.data, b.data)
return False
@register_useless("shape_unsafe")
@register_canonicalize("fast_compile", "shape_unsafe")
@register_specialize("shape_unsafe")
@node_rewriter([switch])
def local_useless_switch(fgraph, node):
"""
This rewrite makes the following changes in a graph:
switch(cond, left, right) ->
if cond is constant and cond == 0: right
if cond is constant and cond != 0: left
if left is right -> left
and
switch(le(shape_i{id}(X), 0), 0, shape_i{id}(X)) -> shape_i{id}(X)
"""
left = node.inputs[1]
right = node.inputs[2]
cond_var = node.inputs[0]
cond = extract_constant(cond_var, only_process_constants=True)