-
Notifications
You must be signed in to change notification settings - Fork 5
/
generic.py
1351 lines (987 loc) · 27.9 KB
/
generic.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
from functools import wraps
import warnings
from types import FunctionType
from typing import Callable
import numpy as np
from plum import convert, add_conversion_method
from plum.type import VarArgs, Union
from . import dispatch, B, Dispatcher
from .control_flow import control_flow
from .types import (
Number,
Numeric,
DType,
Int,
NPNumeric,
AGNumeric,
TFNumeric,
TorchNumeric,
JAXNumeric,
)
from .util import abstract
__all__ = [
"nan",
"pi",
"log_2_pi",
"isabstract",
"jit",
"isnan",
"ActiveDevice",
"device",
"on_device",
"set_global_device",
"to_active_device",
"zeros",
"ones",
"zero",
"one",
"eye",
"linspace",
"range",
"cast",
"identity",
"negative",
"abs",
"sign",
"sqrt",
"exp",
"log",
"sin",
"arcsin",
"cos",
"arccos",
"tan",
"arctan",
"tanh",
"arctanh",
"erf",
"sigmoid",
"softplus",
"relu",
"add",
"subtract",
"multiply",
"divide",
"power",
"minimum",
"maximum",
"leaky_relu",
"min",
"argmin",
"max",
"argmax",
"sum",
"prod",
"nansum",
"mean",
"nanmean",
"std",
"nanstd",
"logsumexp",
"all",
"any",
"lt",
"le",
"gt",
"ge",
"bvn_cdf",
"cond",
"where",
"scan",
"sort",
"argsort",
"quantile",
"to_numpy",
]
_dispatch = Dispatcher()
nan = np.nan #: NaN.
pi = np.pi #: Value of pi.
log_2_pi = np.log(2 * pi) #: Value of log(2 * pi).
@dispatch
@abstract()
def isabstract(a: Numeric): # pragma: no cover
"""Check whether a tensor is abstract.
Args:
a (tensor): Tensor.
Returns:
bool: `True` if `a` is abstract, otherwise `False`.
"""
class JittedFunction:
"""A function that will be compiled just-in-time.
Args:
f_python (function): Python function to compile.
jit_kw_args (dict): Keyword arguments to pass to the JIT.
"""
def __init__(self, f_python, jit_kw_args):
self._f_python = f_python
self._compilation_cache = {}
self._jit_kw_args = jit_kw_args
def __call__(self, *args, **kw_args):
return _jit_run(
self._f_python,
self._compilation_cache,
self._jit_kw_args,
*args,
**kw_args,
)
def jit(f: FunctionType = None, **kw_args):
"""Decorator to compile a function just-in-time.
Further takes in keyword arguments which will be passed to the JIT.
Args:
f (function): Function to compile just-in-time.
"""
# Support partial setting of `**kw_args`.
if f is None:
def dec(f_):
return jit(f_, **kw_args)
return dec
# Use a control flow cache and lazy shapes to make sure that the JIT compilation
# doesn't evaluate abstract tensors.
cache = B.ControlFlowCache()
@wraps(f)
def f_safe(*args_, **kw_args_):
with cache:
with B.lazy_shapes():
return f(*args_, **kw_args_)
# The function needs to be run once before it can safe be compiled. That will be
# handled by :func:`._jit_run`.
return JittedFunction(f_safe, jit_kw_args=kw_args)
@dispatch
@abstract()
def _jit_run(
f: FunctionType,
compilation_cache: dict,
jit_kw_args: dict,
*args: Numeric,
**kw_args
): # pragma: no cover
pass
@dispatch
@abstract()
def isnan(a: Numeric): # pragma: no cover
"""Check whether a tensor is NaN.
Args:
a (tensor): Tensor.
Returns:
tensor[bool]: `a` is NaN.
"""
class ActiveDevice:
"""Context manager that tracks and changes the active device.
Args:
name (str): Name of the device.
Attributes:
active_name (str or :obj:`None`): Name of the active device.
name (str): Name of the device.
"""
active_name = None
_tf_manager = None
def __init__(self, name):
self.name = name
self._active_tf_manager = None
def __enter__(self):
# Set active name.
ActiveDevice.active_name = self.name
# Activate the TF device manager, if it is available.
if ActiveDevice._tf_manager:
self._active_tf_manager = ActiveDevice._tf_manager(self.name)
self._active_tf_manager.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Unset the active name.
ActiveDevice.active_name = None
# Exit the TF device manager, if it was entered.
if self._active_tf_manager:
self._active_tf_manager.__exit__(exc_type, exc_val, exc_tb)
@dispatch
@abstract()
def device(a: Numeric):
"""Get the device on which a tensor lives.
Args:
a (tensor): Tensor to get device of.
Returns:
str: Device of `a`.
"""
@dispatch
def device(device: str): # pragma: no cover
warnings.warn(
"The use of `device` to change the active device is deprecated. Please use "
"`on_device` instead.",
category=DeprecationWarning,
)
return on_device(device)
@dispatch
def on_device(device):
"""Create a context to change the active device.
Args:
device (device): New active device.
Returns:
:class:`.Device`: Context to change the active device.
"""
return ActiveDevice(convert(device, str))
@dispatch
def on_device(a: Numeric):
return B.on_device(device(a))
@dispatch
def set_global_device(device):
"""Change the active device globally.
Args:
device (device): New active device.
"""
on_device(device).__enter__()
@dispatch
@abstract()
def to_active_device(a: Numeric): # pragma: no cover
"""Move a tensor to the active device.
Args:
a (tensor): Tensor to move.
Returns:
tensor: `a` on the active device.
"""
@dispatch
def to_active_device(a: Number):
return a
@dispatch
@abstract()
def zeros(dtype: DType, *shape: Int): # pragma: no cover
"""Create a tensor of zeros.
Can also give a reference tensor whose data type and shape will be used to
construct a tensor of zeros.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
*shape (shape): Shape of the tensor.
Returns:
tensor: Tensor of zeros of shape `shape` and data type `dtype`.
"""
@dispatch.multi((Int,), (VarArgs(Int),)) # Single integer is not a reference.
def zeros(*shape: Int):
return zeros(B.default_dtype, *shape)
@dispatch
def zeros(ref: Numeric):
return zeros(B.dtype(ref), *B.shape(ref))
@dispatch
@abstract()
def ones(dtype: DType, *shape: Int): # pragma: no cover
"""Create a tensor of ones.
Can also give a reference tensor whose data type and shape will be used to
construct a tensor of ones.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
*shape (shape): Shape of the tensor.
Returns:
tensor: Tensor of ones of shape `shape` and data type `dtype`.
"""
@dispatch.multi((Int,), (VarArgs(Int),)) # Single integer is not a reference.
def ones(*shape: Int):
return ones(B.default_dtype, *shape)
@dispatch
def ones(ref: Numeric):
return ones(B.dtype(ref), *B.shape(ref))
@dispatch
def zero(dtype: DType):
"""Create a `0` with a particular data type.
Args:
dtype (dtype): Data type.
Returns:
scalar: `0` with data type `dtype`.
"""
return B.cast(dtype, 0)
@dispatch
def zero(ref: Numeric):
return zero(B.dtype(ref))
@dispatch
def one(dtype: DType):
"""Create a `1` with a particular data type.
Args:
dtype (dtype): Data type.
Returns:
scalar: `1` with data type `dtype`.
"""
return B.cast(dtype, 1)
@dispatch
def one(ref: Numeric):
return one(B.dtype(ref))
@dispatch
def eye(dtype: DType, *shape: Int): # pragma: no cover
"""Create an identity matrix.
Can also give a reference tensor whose data type and shape will be used to
construct an identity matrix.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
*shape (shape): Shape of the matrix.
Returns:
tensor: Identity matrix of shape `shape` and data type `dtype`.
"""
if len(shape) == 2:
return _eye2(dtype, *shape)
else:
# It must be that `len(shape) > 2`.
identity_matrix = _eye2(dtype, *shape[-2:])
batch_shape = shape[:-2]
for _ in range(len(batch_shape)):
identity_matrix = B.expand_dims(identity_matrix, axis=0)
return B.tile(identity_matrix, *batch_shape, 1, 1)
@dispatch
@abstract()
def _eye2(dtype: DType, *shape: Int): # pragma: no cover
pass
@dispatch
def eye(dtype: DType, shape: Int):
return eye(dtype, shape, shape)
@dispatch
def eye(*shape: Int):
return eye(B.default_dtype, *shape)
@dispatch
def eye(shape: Int):
return eye(B.default_dtype, shape, shape)
@dispatch
def eye(ref: Numeric):
return eye(B.dtype(ref), *B.shape(ref))
@dispatch
@abstract()
def linspace(dtype: DType, a, b, num: Int):
"""Create a vector of `c` numbers ranging from `a` to `c`, distributed
linearly.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
a (number): Lower bound.
b (number): Upper bound.
num (int): Number of numbers.
Returns:
vector: `c` numbers ranging from `a` to `c`, distributed linearly.
"""
@dispatch
def linspace(a, b, num: Int):
return linspace(B.default_dtype, a, b, num)
@dispatch
@abstract()
def range(dtype: DType, start, stop, step):
"""Create a vector of numbers ranging from `start` to `stop` with step
size `step`.
Args:
dtype (dtype, optional): Data type. Defaults to `int`.
start (number, optional): Start of range. Defaults to `0`.
stop (number): End of range.
step (number, optional): Step size. Defaults to `1`.
Returns:
vector: Numbers ranging from `start` to `stop` with step size `step`.
"""
@dispatch
def range(start, stop, step):
return range(int, start, stop, step)
@dispatch
def range(dtype: DType, start, stop):
return range(dtype, start, stop, 1)
@dispatch
def range(start, stop):
return range(int, start, stop, 1)
@dispatch
def range(dtype: DType, stop):
return range(dtype, 0, stop, 1)
@dispatch
def range(stop):
return range(int, 0, stop, 1)
@dispatch
@abstract()
def cast(dtype: Numeric, a: DType): # pragma: no cover
"""Cast an object to another data type.
Args:
dtype (dtype): New data type.
a (tensor): Tensor to cast.
Returns:
tensor: `a`, but of data type `dtype`.
"""
# Unary functions:
@dispatch
@abstract()
def identity(a: Numeric): # pragma: no cover
"""Identity function
Args:
a (tensor): Tensor.
Returns:
tensor: `a` exactly.
"""
@dispatch
@abstract()
def negative(a: Numeric): # pragma: no cover
"""Negate a tensor.
Args:
a (tensor): Tensor.
Returns:
tensor: Negative of `a`.
"""
@dispatch
@abstract()
def abs(a: Numeric): # pragma: no cover
"""Absolute value.
Args:
a (tensor): Tensor.
Returns:
tensor: Absolute value of `a`.
"""
@dispatch
@abstract()
def sign(a: Numeric): # pragma: no cover
"""Sign function.
Args:
a (tensor): Tensor.
Returns:
tensor: Sign of `a`.
"""
@dispatch
@abstract()
def sqrt(a: Numeric): # pragma: no cover
"""Square root.
Args:
a (tensor): Tensor.
Returns:
tensor: Square root of `a`.
"""
@dispatch
@abstract()
def exp(a: Numeric): # pragma: no cover
"""Exponential function.
Args:
a (tensor): Tensor.
Returns:
tensor: Exponential function evaluated at `a`.
"""
@dispatch
@abstract()
def log(a: Numeric): # pragma: no cover
"""Logarithmic function
Args:
a (tensor): Tensor.
Returns:
tensor: Logarithmic function evaluated at `a`.
"""
@dispatch
@abstract()
def sin(a: Numeric): # pragma: no cover
"""Sine function.
Args:
a (tensor): Tensor.
Returns:
tensor: Sine function evaluated at `a`.
"""
@dispatch
@abstract()
def arcsin(a: Numeric): # pragma: no cover
"""Inverse of sine function.
Args:
a (tensor): Tensor.
Returns:
tensor: Inverse of sine function evaluated at `a`.
"""
@dispatch
@abstract()
def cos(a: Numeric): # pragma: no cover
"""Cosine function.
Args:
a (tensor): Tensor.
Returns:
tensor: Cosine function evaluated at `a`.
"""
@dispatch
@abstract()
def arccos(a: Numeric): # pragma: no cover
"""Inverse of cosine function.
Args:
a (tensor): Tensor.
Returns:
tensor: Inverse of cosine function evaluated at `a`.
"""
@dispatch
@abstract()
def tan(a: Numeric): # pragma: no cover
"""Tangent function.
Args:
a (tensor): Tensor.
Returns:
tensor: Tangent function evaluated at `a`.
"""
@dispatch
@abstract()
def arctan(a: Numeric): # pragma: no cover
"""Inverse of tangent function.
Args:
a (tensor): Tensor.
Returns:
tensor: Inverse of tangent function evaluated at `a`.
"""
@dispatch
@abstract()
def tanh(a: Numeric): # pragma: no cover
"""Tangent hyperbolic function.
Args:
a (tensor): Tensor.
Returns:
tensor: Tangent hyperbolic function evaluated at `a`.
"""
@dispatch
@abstract()
def arctanh(a: Numeric): # pragma: no cover
"""Inverse of tangent hyperbolic function.
Args:
a (tensor): Tensor.
Returns:
tensor: Inverse of tangent hyperbolic function evaluated at `a`.
"""
@dispatch
@abstract()
def erf(a: Numeric): # pragma: no cover
"""Error function.
Args:
a (tensor): Tensor.
Returns:
tensor: Error function evaluated at `a`.
"""
@dispatch
def sigmoid(a):
"""Sigmoid function.
Args:
a (tensor): Tensor.
Returns:
tensor: Sigmoid function evaluated at `a`.
"""
return 1 / (1 + exp(-a))
@dispatch
def softplus(a):
"""Softplus function.
Args:
a (tensor): Tensor.
Returns:
tensor: Softplus function evaluated at `a`.
"""
zero = B.cast(B.dtype(a), 0)
return log(1 + exp(-abs(a))) + maximum(a, zero)
@dispatch
def relu(a):
"""Rectified linear unit.
Args:
a (tensor): Tensor.
Returns:
tensor: Rectified linear unit evaluated at `a`.
"""
zero = B.cast(B.dtype(a), 0)
return maximum(zero, a)
# Binary functions:
@dispatch
@abstract(promote=2)
def add(a, b): # pragma: no cover
"""Add two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: Sum of `a` and `b`.
"""
@dispatch
@abstract(promote=2)
def subtract(a, b): # pragma: no cover
"""Subtract two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: `a` minus `b`.
"""
@dispatch
@abstract(promote=2)
def multiply(a, b): # pragma: no cover
"""Multiply two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: Product of `a` and `b`.
"""
@dispatch
@abstract(promote=2)
def divide(a, b): # pragma: no cover
"""Divide two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: `a` divided by `b`.
"""
@dispatch
@abstract(promote=2)
def power(a, power): # pragma: no cover
"""Raise a tensor to a power.
Args:
a (tensor): Tensor.
power (tensor): Power.
Returns:
tensor: `a` to the power of `power`.
"""
@dispatch
@abstract(promote=2)
def minimum(a, b): # pragma: no cover
"""Take the minimum of two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: Minimum of `a` and `b`.
"""
@dispatch
@abstract(promote=2)
def maximum(a, b): # pragma: no cover
"""Take the maximum of two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: Maximum of `a` and `b`.
"""
@dispatch
def leaky_relu(a, alpha): # pragma: no cover
"""Leaky rectified linear unit.
Args:
a (tensor): Input.
alpha (tensor): Coefficient of leak.
Returns:
tensor: Activation value.
"""
return maximum(multiply(a, alpha), a)
# Reductions:
@dispatch
@abstract()
def min(a: Numeric, axis=None, squeeze=True): # pragma: no cover
"""Take the minimum of a tensor, possibly along an axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
squeeze (bool, optional): Squeeze the dimension after the reduction. Defaults
to `True`.
Returns:
tensor: Reduced tensor.
"""
@dispatch
@abstract()
def argmin(a: Numeric, axis=None): # pragma: no cover
"""Take the indices corresponding to the minimum of a tensor, possibly along an
axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
Returns:
tensor: Indices.
"""
@dispatch
@abstract()
def max(a: Numeric, axis=None, squeeze=True): # pragma: no cover
"""Take the maximum of a tensor, possibly along an axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
squeeze (bool, optional): Squeeze the dimension after the reduction. Defaults
to `True`.
Returns:
tensor: Reduced tensor.
"""
@dispatch
@abstract()
def argmax(a: Numeric, axis=None): # pragma: no cover
"""Take the indices corresponding to the maximum of a tensor, possibly along an
axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
Returns:
tensor: Indices.
"""
@dispatch
@abstract()
def sum(a: Numeric, axis=None, squeeze=True): # pragma: no cover
"""Sum a tensor, possibly along an axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
squeeze (bool, optional): Squeeze the dimension after the reduction. Defaults
to `True`.
Returns:
tensor: Reduced tensor.
"""
@abstract()
def prod(a: Numeric, axis=None, squeeze=True): # pragma: no cover
"""Product of all elements in a tensor, possibly along an axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
squeeze (bool, optional): Squeeze the dimension after the reduction. Defaults
to `True`.
Returns:
tensor: Reduced tensor.
"""
@dispatch
def nansum(x, **kw_args):
"""Like :func:`sum`, but ignores `NaN`s."""
available = ~B.isnan(x)
x = B.where(available, x, B.zero(x))
return B.sum(x, **kw_args)
@dispatch
@abstract()
def mean(a: Numeric, axis=None, squeeze=True): # pragma: no cover