forked from pymc-devs/pytensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.py
3645 lines (3142 loc) · 121 KB
/
math.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
r"""Rewrites for the `Op`\s in :mod:`pytensor.tensor.math`."""
import itertools
import operator
from collections import defaultdict
from functools import partial, reduce
import numpy as np
import pytensor.scalar.basic as ps
import pytensor.scalar.math as ps_math
from pytensor.graph.basic import Constant, Variable
from pytensor.graph.rewriting.basic import (
NodeRewriter,
PatternNodeRewriter,
SequentialNodeRewriter,
copy_stack_trace,
in2out,
node_rewriter,
)
from pytensor.graph.rewriting.utils import get_clients_at_depth
from pytensor.misc.safe_asarray import _asarray
from pytensor.raise_op import assert_op
from pytensor.tensor.basic import (
Alloc,
Join,
MakeVector,
alloc,
as_tensor_variable,
cast,
constant,
extract_constant,
get_underlying_scalar_constant_value,
moveaxis,
ones_like,
register_infer_shape,
switch,
zeros_like,
)
from pytensor.tensor.blockwise import Blockwise
from pytensor.tensor.elemwise import CAReduce, DimShuffle, Elemwise
from pytensor.tensor.exceptions import NotScalarConstantError
from pytensor.tensor.extra_ops import broadcast_arrays
from pytensor.tensor.math import (
All,
Any,
Dot,
FixedOpCAReduce,
NonZeroDimsCAReduce,
Prod,
ProdWithoutZeros,
Sum,
_conj,
)
from pytensor.tensor.math import abs as pt_abs
from pytensor.tensor.math import (
add,
digamma,
dot,
eq,
erf,
erfc,
exp,
expm1,
ge,
int_div,
isinf,
le,
log,
log1mexp,
log1p,
makeKeepDims,
)
from pytensor.tensor.math import max as pt_max
from pytensor.tensor.math import maximum, mul, neg, polygamma
from pytensor.tensor.math import pow as pt_pow
from pytensor.tensor.math import (
prod,
reciprocal,
sigmoid,
sign,
softplus,
sqr,
sqrt,
sub,
)
from pytensor.tensor.math import sum as pt_sum
from pytensor.tensor.math import tri_gamma, true_div
from pytensor.tensor.rewriting.basic import (
alloc_like,
broadcasted_by,
local_fill_sink,
register_canonicalize,
register_specialize,
register_stabilize,
register_uncanonicalize,
register_useless,
)
from pytensor.tensor.shape import Shape, Shape_i
from pytensor.tensor.subtensor import Subtensor
from pytensor.tensor.type import (
complex_dtypes,
uint_dtypes,
values_eq_approx_remove_inf,
values_eq_approx_remove_inf_nan,
values_eq_approx_remove_nan,
)
from pytensor.tensor.variable import TensorConstant, get_unique_constant_value
def scalarconsts_rest(inputs, elemwise=True, only_process_constants=False):
"""Partition a list of variables into two kinds:
scalar constants, and the rest."""
consts = []
origconsts = []
nonconsts = []
for i in inputs:
try:
v = get_underlying_scalar_constant_value(
i, elemwise=elemwise, only_process_constants=only_process_constants
)
consts.append(v)
origconsts.append(i)
except NotScalarConstantError:
nonconsts.append(i)
return consts, origconsts, nonconsts
def get_constant(v):
"""
Returns
-------
object
A numeric constant if v is a Constant or, well, a
numeric constant. If v is a plain Variable, returns None.
"""
if isinstance(v, Constant):
unique_value = get_unique_constant_value(v)
if unique_value is not None:
data = unique_value
else:
data = v.data
if data.ndim == 0:
return data
else:
return None
elif isinstance(v, Variable):
return None
else:
return v
@register_canonicalize
@register_stabilize
@node_rewriter([Dot])
def local_0_dot_x(fgraph, node):
if not isinstance(node.op, Dot):
return False
x = node.inputs[0]
y = node.inputs[1]
replace = False
try:
if get_underlying_scalar_constant_value(x, only_process_constants=True) == 0:
replace = True
except NotScalarConstantError:
pass
try:
if get_underlying_scalar_constant_value(y, only_process_constants=True) == 0:
replace = True
except NotScalarConstantError:
pass
if replace:
constant_zero = constant(0, dtype=node.outputs[0].type.dtype)
if x.ndim == 2 and y.ndim == 2:
constant_zero = assert_op(constant_zero, eq(x.shape[1], y.shape[0]))
return [alloc(constant_zero, x.shape[0], y.shape[1])]
elif x.ndim == 1 and y.ndim == 2:
constant_zero = assert_op(constant_zero, eq(x.shape[0], y.shape[0]))
return [alloc(constant_zero, y.shape[1])]
elif x.ndim == 2 and y.ndim == 1:
constant_zero = assert_op(constant_zero, eq(x.shape[1], y.shape[0]))
return [alloc(constant_zero, x.shape[0])]
elif x.ndim == 1 and y.ndim == 1:
constant_zero = assert_op(constant_zero, eq(x.shape[0], y.shape[0]))
return [constant_zero]
@register_canonicalize
@node_rewriter([DimShuffle])
def local_lift_transpose_through_dot(fgraph, node):
r"""Perform the rewrite ``dot(x,y).T -> dot(y.T, x.T)``.
These rewrites "lift" (propagate towards the inputs) `DimShuffle`
through dot product. It allows to put the graph in a more standard shape,
and to later merge consecutive `DimShuffle`\s.
The transformation should be apply whether or not the transpose is
inplace. The newly-introduced transpositions are not inplace, this will
be taken care of in a later rewrite phase.
"""
if not (isinstance(node.op, DimShuffle) and node.op.new_order == (1, 0)):
return False
if not (node.inputs[0].owner and isinstance(node.inputs[0].owner.op, Dot)):
return False
x, y = node.inputs[0].owner.inputs
if x.ndim == y.ndim == 2:
# Output is dot product of transposed inputs in reverse order
ret = [dot(y.T, x.T)]
# Copy over stack trace to output from result of dot-product
copy_stack_trace(node.inputs[0], ret)
return ret
@register_stabilize
@register_specialize
@node_rewriter(tracks=[Blockwise])
def local_batched_matmul_to_core_matmul(fgraph, node):
"""Rewrite matmul where only one of the inputs has batch dimensions to a reshaped core matmul.
Example, if x has batch dimensions, but y not:
x @ y -> (x.reshape(-1, x.shape[-1]) @ y).reshape(*x.shape[:-1] + y.shape[-1])
It also works when y has batch dimensions, but x not.
"""
# Check whether we have a matmul operation in this node
if not (
isinstance(node.op.core_op, Dot)
and len(node.op.inputs_sig[0]) == 2
and len(node.op.inputs_sig[1]) == 2
):
return None
x, y = node.inputs
batch_ndim = node.op.batch_ndim(node)
# Check if x has batch dimensions, but y not (or only broadcastable dimensions)
if any(not b_dim for b_dim in x.type.broadcastable[:-2]) and all(
y.type.broadcastable[:-2]
):
x_stacked = x.reshape((-1, x.shape[-1]))
out_stacked = x_stacked @ y.squeeze(tuple(range(batch_ndim)))
out = out_stacked.reshape((*x.shape[:-1], y.shape[-1]))
return [out]
# Otherwise, check if y has batch dimension, but x not
elif any(not b_dim for b_dim in y.type.broadcastable[:-2]) and all(
x.type.broadcastable[:-2]
):
# For the y batch case we need to first move the batch axes and then reshape
# y.shape == (*b, k, n)
y_tr = moveaxis(y, -2, 0) # (k, *b, n)
y_stacked = y_tr.reshape((y.shape[-2], -1)) # (k, *b * n)
out_stacked = x.squeeze(tuple(range(batch_ndim))) @ y_stacked # (m, *b * n)
out_stacked_tr = out_stacked.reshape(
(x.shape[-2], *y.shape[:-2], y.shape[-1])
) # (m, *b, n)
out = moveaxis(out_stacked_tr, 0, -2) # (*b, m, n)
return [out]
# Both x and y have batch dimensions, nothing to do here
return None
def is_inverse_pair(node_op, prev_op, inv_pair):
"""
Given two consecutive operations, check if they are the
provided pair of inverse functions.
"""
node_is_op0 = isinstance(node_op, inv_pair[0])
node_is_op1 = isinstance(node_op, inv_pair[1])
prev_is_op0 = isinstance(prev_op, inv_pair[0])
prev_is_op1 = isinstance(prev_op, inv_pair[1])
return (node_is_op0 and prev_is_op1) or (node_is_op1 and prev_is_op0)
@register_canonicalize
@register_specialize
@node_rewriter([Elemwise])
def local_func_inv(fgraph, node):
"""
Check for two consecutive operations that are functional inverses
and remove them from the function graph.
"""
inv_pairs = (
(ps.Deg2Rad, ps.Rad2Deg),
(ps.Cosh, ps.ArcCosh),
(ps.Tanh, ps.ArcTanh),
(ps.Sinh, ps.ArcSinh),
(ps.Conj, ps.Conj),
(ps.Neg, ps.Neg),
(ps.Reciprocal, ps.Reciprocal),
)
x = node.inputs[0]
if not isinstance(node.op, Elemwise):
return
if not x.owner or not isinstance(x.owner.op, Elemwise):
return
prev_op = x.owner.op.scalar_op
node_op = node.op.scalar_op
for inv_pair in inv_pairs:
if is_inverse_pair(node_op, prev_op, inv_pair):
# We don't need to copy stack trace, because the rewrite
# is trivial and maintains the earlier stack trace
ottype = node.out.dtype
inp = x.owner.inputs[0]
# Functions may have casted integer input to float
if inp.dtype != ottype:
inp = cast(inp, ottype)
return [inp]
return
@register_canonicalize
@register_specialize
@node_rewriter([Elemwise])
def local_exp_log(fgraph, node):
x = node.inputs[0]
if not isinstance(node.op, Elemwise):
return
if not x.owner or not isinstance(x.owner.op, Elemwise):
return
prev_op = x.owner.op.scalar_op
node_op = node.op.scalar_op
# Case for log(exp(x)) -> x
if isinstance(prev_op, ps.Exp) and isinstance(node_op, ps.Log):
new_out = x.owner.inputs[0]
old_out = node.outputs[0]
# Exp may have cast integer input to float
if new_out.dtype != old_out.dtype:
new_out = cast(new_out, old_out.dtype)
return [new_out]
# Case for log1p(expm1(x)) -> x
if isinstance(prev_op, ps.Expm1) and isinstance(node_op, ps.Log1p):
new_out = x.owner.inputs[0]
old_out = node.outputs[0]
# Expm1 may have cast integer input to float
if new_out.dtype != old_out.dtype:
new_out = cast(new_out, old_out.dtype)
return [new_out]
# Case for exp(softplus(x)) aka exp(log1pexp) -> 1 + exp(x)
if isinstance(prev_op, ps_math.Softplus) and isinstance(node_op, ps.Exp):
x = x.owner.inputs[0]
return [add(1, exp(x))]
# Case for expm1(softplus(x)) aka expm1(log1pexp) -> exp(x)
if isinstance(prev_op, ps_math.Softplus) and isinstance(node_op, ps.Expm1):
x = x.owner.inputs[0]
return [exp(x)]
@register_specialize
@node_rewriter([Elemwise])
def local_exp_log_nan_switch(fgraph, node):
# Rewrites of the kind exp(log...(x)) that require a `nan` switch
x = node.inputs[0]
if not isinstance(node.op, Elemwise):
return
if not x.owner or not isinstance(x.owner.op, Elemwise):
return
prev_op = x.owner.op.scalar_op
node_op = node.op.scalar_op
# Case for exp(log(x)) -> x
if isinstance(prev_op, ps.Log) and isinstance(node_op, ps.Exp):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(ge(x, 0), x, np.asarray(np.nan, old_out.dtype))
return [new_out]
# Case for exp(log1p(x)) -> x + 1
if isinstance(prev_op, ps.Log1p) and isinstance(node_op, ps.Exp):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(ge(x, -1), add(1, x), np.asarray(np.nan, old_out.dtype))
return [new_out]
# Case for expm1(log(x)) -> x - 1
if isinstance(prev_op, ps.Log) and isinstance(node_op, ps.Expm1):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(ge(x, 0), sub(x, 1), np.asarray(np.nan, old_out.dtype))
return [new_out]
# Case for expm1(log1p(x)) -> x
if isinstance(prev_op, ps.Log1p) and isinstance(node_op, ps.Expm1):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(ge(x, -1), x, np.asarray(np.nan, old_out.dtype))
return [new_out]
# Case for exp(log1mexp(x)) -> 1 - exp(x)
if isinstance(prev_op, ps_math.Log1mexp) and isinstance(node_op, ps.Exp):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(le(x, 0), sub(1, exp(x)), np.asarray(np.nan, old_out.dtype))
return [new_out]
# Case for expm1(log1mexp(x)) -> -exp(x)
if isinstance(prev_op, ps_math.Log1mexp) and isinstance(node_op, ps.Expm1):
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = switch(le(x, 0), neg(exp(x)), np.asarray(np.nan, old_out.dtype))
return [new_out]
@register_canonicalize
@register_specialize
@node_rewriter([Sum])
def local_sumsqr2dot(fgraph, node):
"""
This rewrite detects
``pt.sqr(W.dimshuffle("x", 0, 1) * G.dimshuffle(0, "x", 1) ).sum(axis=(1, 2))``
and converts it to ``pt.dot(pt.sqr(G), pt.sqr(W).sum(axis=0))``.
"""
if (
isinstance(node.op, Sum)
and isinstance(node.op.scalar_op, ps.Add)
and node.op.axis == (1, 2)
):
in1 = node.inputs[0]
out = node.outputs[0]
if (
in1.owner
and isinstance(in1.owner.op, Elemwise)
and isinstance(in1.owner.op.scalar_op, ps.Sqr)
):
in_sqr = in1.owner.inputs[0]
if (
in_sqr.owner
and isinstance(in_sqr.owner.op, Elemwise)
and isinstance(in_sqr.owner.op.scalar_op, ps.Mul)
and len(in_sqr.owner.inputs) == 2
):
in_mul1, in_mul2 = in_sqr.owner.inputs
if (
isinstance(in_mul1.owner.op, DimShuffle)
and in_mul1.owner.op.new_order == ("x", 0, 1)
and isinstance(in_mul2.owner.op, DimShuffle)
and in_mul2.owner.op.new_order == (0, "x", 1)
):
W = in_mul1.owner.inputs[0]
G = in_mul2.owner.inputs[0]
new_out = dot(sqr(G), sqr(W).sum(axis=0))
if new_out.dtype != out.dtype:
new_out = cast(new_out, dtype=out.dtype)
return [new_out]
@register_specialize
@node_rewriter([mul, true_div])
def local_mul_exp_to_exp_add(fgraph, node):
"""
This rewrite detects e^x * e^y and converts it to e^(x+y).
Similarly, e^x / e^y becomes e^(x-y).
"""
exps = [
n.owner.inputs[0]
for n in node.inputs
if n.owner
and hasattr(n.owner.op, "scalar_op")
and isinstance(n.owner.op.scalar_op, ps.Exp)
]
# Can only do any rewrite if there are at least two exp-s
if len(exps) >= 2:
# Mul -> add; TrueDiv -> sub
orig_op, new_op = mul, add
if isinstance(node.op.scalar_op, ps.TrueDiv):
orig_op, new_op = true_div, sub
new_out = exp(new_op(*exps))
if new_out.dtype != node.outputs[0].dtype:
new_out = cast(new_out, dtype=node.outputs[0].dtype)
# The original Mul may have more than two factors, some of which may not be exp nodes.
# If so, we keep multiplying them with the new exp(sum) node.
# E.g.: e^x * y * e^z * w --> e^(x+z) * y * w
rest = [
n
for n in node.inputs
if not n.owner
or not hasattr(n.owner.op, "scalar_op")
or not isinstance(n.owner.op.scalar_op, ps.Exp)
]
if len(rest) > 0:
new_out = orig_op(new_out, *rest)
if new_out.dtype != node.outputs[0].dtype:
new_out = cast(new_out, dtype=node.outputs[0].dtype)
return [new_out]
@register_specialize
@node_rewriter([mul, true_div])
def local_mul_pow_to_pow_add(fgraph, node):
"""
This rewrite detects a^x * a^y and converts it to a^(x+y).
Similarly, a^x / a^y becomes a^(x-y).
"""
# search for pow-s and group them by their bases
pow_nodes = defaultdict(list)
rest = []
for n in node.inputs:
if (
n.owner
and hasattr(n.owner.op, "scalar_op")
and isinstance(n.owner.op.scalar_op, ps.Pow)
):
base_node = n.owner.inputs[0]
# exponent is at n.owner.inputs[1], but we need to store the full node
# in case this particular power node remains alone and can't be rewritten
pow_nodes[base_node].append(n)
else:
rest.append(n)
# Can only do any rewrite if there are at least two pow-s with the same base
can_rewrite = [k for k, v in pow_nodes.items() if len(v) >= 2]
if len(can_rewrite) >= 1:
# Mul -> add; TrueDiv -> sub
orig_op, new_op = mul, add
if isinstance(node.op.scalar_op, ps.TrueDiv):
orig_op, new_op = true_div, sub
pow_factors = []
# Rewrite pow-s having the same base for each different base
# E.g.: a^x * a^y --> a^(x+y)
for base in can_rewrite:
exponents = [n.owner.inputs[1] for n in pow_nodes[base]]
new_node = base ** new_op(*exponents)
if new_node.dtype != node.outputs[0].dtype:
new_node = cast(new_node, dtype=node.outputs[0].dtype)
pow_factors.append(new_node)
# Don't forget about those sole pow-s that couldn't be rewriten
sole_pows = [v[0] for k, v in pow_nodes.items() if k not in can_rewrite]
# Combine the rewritten pow-s and other, non-pow factors of the original Mul
# E.g.: a^x * y * b^z * a^w * v * b^t --> a^(x+z) * b^(z+t) * y * v
if len(pow_factors) > 1 or len(sole_pows) > 0 or len(rest) > 0:
new_out = orig_op(*pow_factors, *sole_pows, *rest)
if new_out.dtype != node.outputs[0].dtype:
new_out = cast(new_out, dtype=node.outputs[0].dtype)
else:
# if all factors of the original mul were pows-s with the same base,
# we can get rid of the mul completely.
new_out = pow_factors[0]
return [new_out]
@register_stabilize
@register_specialize
@register_canonicalize
@node_rewriter([Elemwise])
def local_expm1(fgraph, node):
"""Detect ``exp(a) - 1`` and convert them to ``expm1(a)``."""
if isinstance(node.op, Elemwise) and isinstance(node.op.scalar_op, ps.Sub):
in1, in2 = node.inputs
out = node.outputs[0]
if (
in1.owner
and isinstance(in1.owner.op, Elemwise)
and isinstance(in1.owner.op.scalar_op, ps.Exp)
and extract_constant(in2, only_process_constants=False) == 1
):
in11 = in1.owner.inputs[0]
new_out = expm1(in11)
if new_out.dtype != out.dtype:
new_out = cast(new_out, dtype=out.dtype)
if not out.type.is_super(new_out.type):
return
return [new_out]
@register_specialize
@register_canonicalize
@node_rewriter([mul])
def local_mul_switch_sink(fgraph, node):
"""
This rewrite makes the following changes in the graph:
pt.mul(A, pt.switch(cond, 0, iff), B) -> pt.switch(cond, 0, pt.mul(A, B, iff))
pt.mul(A, pt.switch(cond, ift, 0), B) -> pt.switch(cond, pt.mul(A, B, ift), 0)
``A`` and ``B`` being several (or none) symbolic variables.
This is useful because ``A`` and ``B`` may not be numerically stable and give
NaN or inf values for cases where the switch returns 0.
With this rewrite ``pt.grad(pt.switch(...))`` has the right behavior.
Examples
--------
x -> f(x)
x -> g(x)
y = pt.switch(cond, f(x), g(x))
without the rewrite:
pt.grad(y, x) -> grad(f(x), x) * grad(y, f(x)) + grad(g(x), x) * grad(y, g(x))
with the rewrite
pt.grad(y, x) -> switch(cond, grad(f(x), x), 0) + switch(cond, 0, grad(g(x), x))
This will be particularly useful for the lazy ``if`` because we skip an entire
part of the graph.
"""
if node.op != mul:
return False
for idx, i in enumerate(node.inputs):
if i.owner and i.owner.op == switch:
switch_node = i.owner
try:
if (
get_underlying_scalar_constant_value(
switch_node.inputs[1], only_process_constants=True
)
== 0.0
):
listmul = node.inputs[:idx] + node.inputs[idx + 1 :]
fmul = mul(*(listmul + [switch_node.inputs[2]]))
# Copy over stacktrace for elementwise multiplication op
# from previous elementwise multiplication op.
# An error in the multiplication (e.g. errors due to
# inconsistent shapes), will point to the
# multiplication op.
copy_stack_trace(node.outputs, fmul)
fct = [switch(switch_node.inputs[0], 0, fmul)]
fct[0].tag.values_eq_approx = values_eq_approx_remove_nan
# Copy over stacktrace for switch op from both previous
# elementwise multiplication op and previous switch op,
# because an error in this part can be caused by either
# of the two previous ops.
copy_stack_trace(node.outputs + switch_node.outputs, fct)
return fct
except NotScalarConstantError:
pass
try:
if (
get_underlying_scalar_constant_value(
switch_node.inputs[2], only_process_constants=True
)
== 0.0
):
listmul = node.inputs[:idx] + node.inputs[idx + 1 :]
fmul = mul(*(listmul + [switch_node.inputs[1]]))
# Copy over stacktrace for elementwise multiplication op
# from previous elementwise multiplication op.
# An error in the multiplication (e.g. errors due to
# inconsistent shapes), will point to the
# multiplication op.
copy_stack_trace(node.outputs, fmul)
fct = [switch(switch_node.inputs[0], fmul, 0)]
fct[0].tag.values_eq_approx = values_eq_approx_remove_nan
# Copy over stacktrace for switch op from both previous
# elementwise multiplication op and previous switch op,
# because an error in this part can be caused by either
# of the two previous ops.
copy_stack_trace(node.outputs + switch_node.outputs, fct)
return fct
except NotScalarConstantError:
pass
return False
@register_canonicalize
@node_rewriter([true_div, int_div])
def local_div_switch_sink(fgraph, node):
"""
This rewrite makes the following changes in the graph:
pt.div(pt.switch(cond, 0, iff), A) -> pt.switch(cond, 0, pt.div(iff, A))
pt.div(pt.switch(cond, ift, 0), A) -> pt.switch(cond, pt.div(ift, A), 0)
where ``A`` is a symbolic variable.
This is useful because ``A`` may not be numerically stable and give
``nan`` or ``inf`` values for cases where the switch returns 0.
See `local_mul_switch_sink` for more details.
"""
if node.op != true_div and node.op != int_div:
return False
op = node.op
if node.inputs[0].owner and node.inputs[0].owner.op == switch:
switch_node = node.inputs[0].owner
try:
if (
get_underlying_scalar_constant_value(
switch_node.inputs[1], only_process_constants=True
)
== 0.0
):
fdiv = op(switch_node.inputs[2], node.inputs[1])
# Copy over stacktrace for elementwise division op
# from previous elementwise multiplication op.
# An error in the division (e.g. errors due to
# inconsistent shapes or division by zero),
# will point to the new division op.
copy_stack_trace(node.outputs, fdiv)
fct = [switch(switch_node.inputs[0], 0, fdiv)]
fct[0].tag.values_eq_approx = values_eq_approx_remove_nan
# Copy over stacktrace for switch op from both previous
# elementwise division op and previous switch op,
# because an error in this part can be caused by either
# of the two previous ops.
copy_stack_trace(node.outputs + switch_node.outputs, fct)
return fct
except NotScalarConstantError:
pass
try:
if (
get_underlying_scalar_constant_value(
switch_node.inputs[2], only_process_constants=True
)
== 0.0
):
fdiv = op(switch_node.inputs[1], node.inputs[1])
# Copy over stacktrace for elementwise division op
# from previous elementwise multiplication op.
# An error in the division (e.g. errors due to
# inconsistent shapes or division by zero),
# will point to the new division op.
copy_stack_trace(node.outputs, fdiv)
fct = [switch(switch_node.inputs[0], fdiv, 0)]
fct[0].tag.values_eq_approx = values_eq_approx_remove_nan
# Copy over stacktrace for switch op from both previous
# elementwise division op and previous switch op,
# because an error in this part can be caused by either
# of the two previous ops.
copy_stack_trace(node.outputs + switch_node.outputs, fct)
return fct
except NotScalarConstantError:
pass
return False
class AlgebraicCanonizer(NodeRewriter):
r"""A `Rewriter` that rewrites algebraic expressions.
The variable is a `node_rewriter`. It is best used
with a `WalkingGraphRewriter` in in-to-out order.
Usage: ``AlgebraicCanonizer(main, inverse, reciprocal, calculate)``
Parameters
----------
main
A suitable `Op` class that is commutative, associative and
takes one to an arbitrary number of inputs, e.g. add or
mul
inverse
An `Op` class such that ``inverse(main(x, y), y) == x``
(e.g. `sub` or `true_div`).
reciprocal
A function such that ``main(x, reciprocal(y)) == inverse(x, y)``
(e.g. `neg` or `reciprocal`).
calculate
Function that takes a list of `numpy.ndarray` instances
for the numerator, another list for the denumerator,
and calculates ``inverse(main(\*num), main(\*denum))``. It
takes a keyword argument, `aslist`. If ``True``, the value
should be returned as a list of one element, unless
the value is such that ``value = main()``. In that case,
the return value should be an empty list.
Examples
--------
>>> import pytensor.tensor as pt
>>> from pytensor.tensor.rewriting.math import AlgebraicCanonizer
>>> add_canonizer = AlgebraicCanonizer(add, sub, neg, \\
... lambda n, d: sum(n) - sum(d))
>>> mul_canonizer = AlgebraicCanonizer(mul, true_div, inv, \\
... lambda n, d: prod(n) / prod(d))
Examples of rewrites `mul_canonizer` can perform:
| x / x -> 1
| (x * y) / x -> y
| x / y / x -> 1 / y
| x / y / z -> x / (y * z)
| x / (y / z) -> (x * z) / y
| (a / b) * (b / c) * (c / d) -> a / d
| (2.0 * x) / (4.0 * y) -> (0.5 * x) / y
| 2 * x / 2 -> x
| x * y * z -> Elemwise(mul){x,y,z} #only one pass over the memory.
| !-> Elemwise(mul){x,Elemwise(mul){y,z}}
"""
def __init__(self, main, inverse_fn, reciprocal_fn, calculate, use_reciprocal=True):
self.main = main
self.inverse = inverse_fn
self.reciprocal = reciprocal_fn
self.calculate = calculate
self.use_reciprocal = use_reciprocal
self.external_simplifiers = []
def add_simplifier(self, simplifier, reason):
self.external_simplifiers.append((reason, simplifier))
def tracks(self):
return [self.main, self.inverse, self.reciprocal]
def get_num_denum(self, inp):
r"""
This extract two lists, ``num`` and ``denum``, such that the input is:
``self.inverse(self.main(\*num), self.main(\*denum))``. It returns
the two lists in a ``(num, denum)`` pair.
For example, for main, inverse and ``reciprocal = \*, / and inv()``,
| input -> returned value (num, denum)
| x*y -> ([x, y], [])
| inv(x) -> ([], [x])
| inv(x) * inv(y) -> ([], [x, y])
| x*y/z -> ([x, y], [z])
| log(x) / y * (z + x) / y -> ([log(x), z + x], [y, y])
| (((a / b) * c) / d) -> ([a, c], [b, d])
| a / (b / c) -> ([a, c], [b])
| log(x) -> ([log(x)], [])
| x**y -> ([x**y], [])
| x * y * z -> ([x, y, z], [])
"""
# This function is recursive. The idea is that there is a
# get_num_denum recursion in which the internal ops are all
# one of (main, inverse, reciprocal, DimShuffle) and the
# internal data nodes all have the dtype of the 'input'
# argument. The leaf-Variables of the graph covered by the
# recursion may be of any Variable type.
if inp.owner is None or inp.owner.op not in [
self.main,
self.inverse,
self.reciprocal,
]:
if inp.owner and isinstance(inp.owner.op, DimShuffle):
# If input is a DimShuffle of some input which does
# something like this:
# * change a vector of length N into a 1xN row matrix
# * change a scalar into a 1x1x1 tensor
# * in general, complete the shape of a tensor
# with broadcastable 1s to the *left*
# Then we will simply discard the DimShuffle and return
# the num/denum of its input
dsn = inp.owner # dimshuffle node
dsop = dsn.op # dimshuffle op
# the first input of the dimshuffle i.e. the ndarray to redim
dsi0 = dsn.inputs[0]
# The compatible order is a DimShuffle "new_order" of the form:
# ('x', ..., 'x', 0, 1, 2, ..., dimshuffle_input.type.ndim)
# That kind of DimShuffle only adds broadcastable
# dimensions on the left, without discarding any
# existing broadcastable dimension and is inserted
# automatically by Elemwise when the inputs have
# different numbers of dimensions (hence why we can
# discard its information - we know we can retrieve it
# later on).
compatible_order = ("x",) * (inp.type.ndim - dsi0.type.ndim) + tuple(
range(dsi0.type.ndim)
)
if dsop.new_order == compatible_order:
# If the "new_order" is the one we recognize,
# we return the num_denum of the dimshuffled input.
return self.get_num_denum(inp.owner.inputs[0])
else:
# This is when the input isn't produced by main,
# inverse or reciprocal.
return [inp], []
else:
return [inp], []
num = []
denum = []
parent = inp.owner
# We get the (num, denum) pairs for each input
# pairs = [self.get_num_denum(input2) if input2.type.dtype ==
# input.type.dtype else ([input2], []) for input2 in
# parent.inputs]
pairs = [self.get_num_denum(input2) for input2 in parent.inputs]
if parent.op == self.main:
# If we have main(x, y, ...), numx, denumx, numy, denumy, ...
# then num is concat(numx, numy, num...) and denum is
# concat(denumx, denumy, denum...) note that main() can have any
# number of arguments >= 0 concat is list concatenation
num = reduce(list.__iadd__, map(operator.itemgetter(0), pairs))
denum = reduce(list.__iadd__, map(operator.itemgetter(1), pairs))
elif parent.op == self.inverse:
# If we have inverse(x, y), numx, denumx, numy and denumy
# then num is concat(numx, denumy) and denum is
# concat(denumx, numy) note that inverse() is binary
num = pairs[0][0] + pairs[1][1]
denum = pairs[0][1] + pairs[1][0]
elif parent.op == self.reciprocal:
# If we have reciprocal(x), numx, denumx
# then num is denumx and denum is numx
# note that reciprocal() is unary
num = pairs[0][1]
denum = pairs[0][0]
return num, denum
def merge_num_denum(self, num, denum):
r"""
Utility function which takes two lists, num and denum, and
returns something which is equivalent to inverse(main(\*num),
main(\*denum)), but depends on the length of num and the length
of denum (in order to minimize the number of operations).
Let n = len(num) and d = len(denum):
| n=0, d=0: neutral element (given by self.calculate([], []))
| (for example, this would be 0 if main is addition
| and 1 if main is multiplication)
| n=1, d=0: num[0]
| n=0, d=1: reciprocal(denum[0])
| n=1, d=1: inverse(num[0], denum[0])
| n=0, d>1: reciprocal(main(\*denum))
| n>1, d=0: main(\*num)
| n=1, d>1: inverse(num[0], main(\*denum))
| n>1, d=1: inverse(main(\*num), denum[0])
| n>1, d>1: inverse(main(\*num), main(\*denum))
Given the values of n and d to which they are associated, all
of the above are equivalent to:
inverse(main(\*num), main(\*denum))
"""
ln, ld = len(num), len(denum)
if not ln and not ld:
return as_tensor_variable(self.calculate([], []))
if not ln:
if self.use_reciprocal:
return self.reciprocal(self.merge_num_denum(denum, []))
else:
ln = [self.calculate([], [], aslist=False)]
if not ld:
if ln == 1:
# num[0] should always be a variable
assert isinstance(num[0], Variable)
return num[0]
else:
return self.main(*num)
return self.inverse(
self.merge_num_denum(num, []), self.merge_num_denum(denum, [])
)
def simplify(self, num, denum, out_type):
"""
Shorthand for:
.. code-block:: python
self.simplify_constants(*self.simplify_factors(num, denum))
"""
rval = self.simplify_constants(
*self.simplify_factors(num, denum), out_type=out_type
)
for reason, simplifier in self.external_simplifiers: