/
numpy_test.py
2010 lines (1791 loc) · 75.8 KB
/
numpy_test.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
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for internal.backend.numpy."""
import functools
# Dependency imports
from absl import flags
from absl import logging
from absl.testing import parameterized
import hypothesis as hp
import hypothesis.extra.numpy as hnp
import hypothesis.strategies as hps
import mock
import numpy as np # Rewritten by script to import jax.numpy
import numpy as onp # pylint: disable=reimported
import scipy.special as scipy_special
import six
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps
from tensorflow_probability.python.internal import test_util
from tensorflow_probability.python.internal.backend import numpy as nptf
from tensorflow_probability.python.internal.backend.numpy import functional_ops as np_pfor
from tensorflow.python.ops import parallel_for as tf_pfor # pylint: disable=g-direct-tensorflow-import
# Allows us to test low-level TF:XLA match.
flags.DEFINE_enum('test_mode', 'numpy', ['numpy', 'xla'],
'Set to `"xla"` to compare TF with TF-XLA. '
'Default compares tf to nptf.')
flags.DEFINE_bool('only_disabled', False, 'Only test disabled XLA tests')
flags.DEFINE_bool('use_tpu', False, 'Verifies numerics on TPU.')
flags.DEFINE_list('xla_disabled', [],
'List of endpoints to skip. Allows us per-device blocklists.')
FLAGS = flags.FLAGS
ALLOW_NAN = False
ALLOW_INFINITY = False
ALLOW_SUBNORMAL = False
JAX_MODE = False
NUMPY_MODE = not JAX_MODE
# pylint is unable to handle @hps.composite (e.g. complains "No value for
# argument 'batch_shape' in function call"), so disable this lint for the file.
# pylint: disable=no-value-for-parameter
class Kwargs(dict):
"""Sentinel to indicate a single item arg is actually a **kwargs."""
# See usage with raw_ops.MatrixDiagPartV2.
pass
def _add_jax_prng_key_as_seed():
import jax.random as jaxrand # pylint: disable=g-import-not-at-top
return dict(seed=jaxrand.PRNGKey(123))
def _getattr(obj, name):
names = name.split('.')
return functools.reduce(getattr, names, obj)
def _maybe_get_subnormal_kwarg(allow_subnormal=ALLOW_SUBNORMAL):
if hp.__version_info__ >= (6, 30):
return {'allow_subnormal': allow_subnormal}
return {}
class TestCase(dict):
"""`dict` object containing test strategies for a single function."""
def __init__(self, name, strategy_list, **kwargs):
self.name = name
tensorflow_function = kwargs.pop('tensorflow_function', None)
if not tensorflow_function:
tensorflow_function = _getattr(tf, name)
numpy_function = kwargs.pop('numpy_function', None)
if not numpy_function:
numpy_function = _getattr(
nptf,
name.replace('random.', 'random.stateless_'
).replace('random.stateless_gamma', 'random.gamma'))
super(TestCase, self).__init__(
testcase_name='_' + name.replace('.', '_'),
tensorflow_function=tensorflow_function,
numpy_function=numpy_function,
strategy_list=strategy_list,
name=name,
**kwargs)
def __repr__(self):
return 'TestCase(\'{}\', {})'.format(self.name, self['strategy_list'])
# Below we define several test strategies. Each describes the valid inputs for
# different TensorFlow and numpy functions. See hypothesis.readthedocs.io for
# mode detail.
@hps.composite
def floats(draw,
min_value=-1e16,
max_value=1e16,
allow_nan=ALLOW_NAN,
allow_infinity=ALLOW_INFINITY,
allow_subnormal=ALLOW_SUBNORMAL,
dtype=None):
if dtype is None:
dtype = np.float32 if FLAGS.use_tpu else np.float64
if min_value is not None:
min_value = onp.array(min_value, dtype=dtype).item()
if max_value is not None:
max_value = onp.array(max_value, dtype=dtype).item()
subnormal_kwarg = _maybe_get_subnormal_kwarg(allow_subnormal)
return draw(hps.floats(min_value=min_value,
max_value=max_value,
allow_nan=allow_nan,
allow_infinity=allow_infinity,
width=np.dtype(dtype).itemsize * 8,
**subnormal_kwarg))
def integers(min_value=-2**30, max_value=2**30):
return hps.integers(min_value, max_value)
def complex_numbers(min_magnitude=0.,
max_magnitude=1e16,
allow_nan=ALLOW_NAN,
allow_infinity=ALLOW_INFINITY,
dtype=np.complex64):
# TODO(jburnim): In the np.complex64 case, directly build np.complex64 values
# with Hypothesis instead of building np.complex128 and casting.
return hps.builds(
dtype,
hps.complex_numbers(
min_magnitude=min_magnitude,
max_magnitude=max_magnitude,
allow_nan=allow_nan,
allow_infinity=allow_infinity))
@hps.composite
def non_zero_floats(draw, *args, **kwargs):
return draw(floats(*args, **kwargs).filter(lambda x: np.all(x != 0.)))
positive_floats = functools.partial(floats, min_value=1e-6)
def shapes(min_dims=0, max_dims=4, min_side=1, max_side=5):
strategy = hnp.array_shapes(
min_dims=max(1, min_dims),
max_dims=max_dims,
min_side=min_side,
max_side=max_side)
if min_dims < 1:
strategy = hps.one_of(hps.just(()), strategy)
return strategy
def fft_shapes(fft_dim, max_fft_size=32):
sizes = [s for s in [2, 4, 8, 16, 32] if s <= max_fft_size]
return hps.tuples(
shapes(max_dims=2), # batch portion
hps.lists(min_size=fft_dim, max_size=fft_dim,
elements=hps.sampled_from(sizes))).map(
lambda t: t[0] + tuple(t[1]))
@hps.composite
def n_same_shape(draw, n, shape=shapes(), dtype=None, elements=None,
as_tuple=True, batch_shape=(), unique=False,
allow_nan=ALLOW_NAN):
if dtype is None:
dtype = np.float32 if FLAGS.use_tpu else np.float64
if elements is None:
if dtype in (np.float32, np.float64):
if allow_nan:
elements = floats(min_value=None, max_value=None,
allow_nan=allow_nan, dtype=dtype)
else:
elements = floats(dtype=dtype)
elif dtype in (np.int32, np.int64):
elements = integers()
elif dtype in (np.complex64, np.complex128):
elements = complex_numbers(dtype=dtype)
elif dtype == np.bool_:
elements = hps.booleans()
else:
raise ValueError('Unexpected dtype: {}'.format(dtype))
shape = tuple(batch_shape) + draw(shape)
ensure_array = lambda x: onp.array(x, dtype=dtype)
if isinstance(elements, (list, tuple)):
return tuple([
draw(hnp.arrays(
dtype, shape, unique=unique, elements=e).map(ensure_array))
for e in elements
])
array_strategy = hnp.arrays(
dtype, shape, unique=unique, elements=elements).map(ensure_array)
if n == 1 and not as_tuple:
return draw(array_strategy)
return draw(hps.tuples(*([array_strategy] * n)))
single_arrays = functools.partial(n_same_shape, n=1, as_tuple=False)
@hps.composite
def array_axis_tuples(draw, strategy=None, elements=None, dtype=None,
allow_nan=ALLOW_NAN, allow_multi_axis=False):
x = draw(strategy or single_arrays(shape=shapes(min_dims=1),
elements=elements,
dtype=dtype,
allow_nan=allow_nan))
rank = len(x.shape)
if allow_multi_axis:
if draw(hps.booleans()): # Use None axis.
axis = None
else:
# Pick a set of distinct axes, then decide whether to index each one from
# the front or from the back.
axis = draw(hps.sets(hps.integers(-rank, -1)))
indexed_from_front = draw(hps.tuples(*[hps.booleans() for _ in axis]))
axis = tuple((ax + rank) if from_front else ax
for (ax, from_front) in zip(axis, indexed_from_front))
else:
axis = draw(hps.integers(-rank, rank - 1))
return x, axis
@hps.composite
def sliceable_and_slices(draw, strategy=None):
x = draw(strategy or single_arrays(shape=shapes(min_dims=1)))
starts = []
sizes = []
for dim in x.shape:
starts.append(draw(hps.integers(0, dim - 1)))
sizes.append(
draw(hps.one_of(hps.just(-1), hps.integers(0, dim - starts[-1]))))
return x, starts, sizes
@hps.composite
def one_hot_params(draw):
indices = draw(single_arrays(dtype=np.int32, elements=hps.integers(0, 8)))
depth = np.maximum(1, np.max(indices)).astype(np.int32)
dtype = draw(hps.sampled_from((onp.int32, onp.float32, onp.complex64)))
on_value = draw(hps.sampled_from((None, 1, 2)))
on_value = on_value if on_value is None else dtype(on_value)
off_value = draw(hps.sampled_from((None, 3, 7)))
off_value = off_value if off_value is None else dtype(off_value)
rank = indices.ndim
axis = draw(hps.one_of(hps.just(None), hps.integers(-1, rank - 1)))
return indices, depth, on_value, off_value, axis, dtype
@hps.composite
def array_and_diagonal(draw):
side = draw(hps.integers(1, 10))
shape = draw(shapes(min_dims=2, min_side=side, max_side=side))
array = draw(hnp.arrays(np.float64, shape, elements=floats(dtype=np.float64)))
diag = draw(hnp.arrays(np.float64, shape[:-1],
elements=floats(dtype=np.float64)))
return array, diag
@hps.composite
def matmul_compatible_pairs(draw,
dtype=np.float64,
x_strategy=None,
elements=None):
elements = elements or floats(dtype=dtype)
x_strategy = x_strategy or single_arrays(
shape=shapes(min_dims=2, max_dims=5), dtype=dtype, elements=elements)
x = draw(x_strategy)
x_shape = tuple(map(int, x.shape))
y_shape = x_shape[:-2] + x_shape[-1:] + (draw(hps.integers(1, 10)),)
y = draw(hnp.arrays(dtype, y_shape, elements=elements))
return x, y
@hps.composite
def pd_matrices(draw, eps=1.):
x = draw(
single_arrays(
shape=shapes(min_dims=2),
elements=floats(min_value=-1e3, max_value=1e3)))
y = np.swapaxes(x, -1, -2)
if x.shape[-1] < x.shape[-2]: # Ensure resultant matrix not rank-deficient.
x, y = y, x
psd = np.matmul(x, y)
return psd + eps * np.eye(psd.shape[-1])
@hps.composite
def nonsingular_matrices(draw):
mat = draw(pd_matrices())
signs = draw(
hnp.arrays(
mat.dtype,
tuple(int(dim) for dim in mat.shape[:-2]) + (1, 1),
elements=hps.sampled_from([-1., 1.])))
return mat * signs
@hps.composite
def batched_probabilities(draw, batch_shape, num_classes):
probs = draw(single_arrays(
batch_shape=batch_shape,
shape=hps.just((num_classes,)),
dtype=np.float32, elements=floats(dtype=np.float32)))
probs = onp.exp(probs - onp.max(
probs, axis=-1, keepdims=True))
return probs / probs.sum(keepdims=True, axis=-1)
def tensorshapes_to_tuples(tensorshapes):
return tuple(tuple(tensorshape.as_list()) for tensorshape in tensorshapes)
@hps.composite
def where_params(draw, version=2):
shape = draw(shapes())
if version == 2:
cond_shape, x_shape, y_shape = draw(
tfp_hps.broadcasting_shapes(shape, 3).map(tensorshapes_to_tuples))
elif version == 1:
max_cond_ndim = min(1, len(shape))
cond_dims = draw(hps.sampled_from(onp.arange(max_cond_ndim + 1)))
cond_shape = shape[:cond_dims]
x_shape, y_shape = shape, shape
else:
raise ValueError('unexpected tf.where version {}'.format(version))
condition = draw(single_arrays(shape=hps.just(cond_shape), dtype=np.bool_))
x = draw(single_arrays(shape=hps.just(x_shape)))
y = draw(single_arrays(shape=hps.just(y_shape), dtype=x.dtype))
return condition, x, y
@hps.composite
def normal_params(draw):
shape = draw(shapes())
arg_shapes = draw(
tfp_hps.broadcasting_shapes(shape, 3).map(tensorshapes_to_tuples))
include_arg = draw(hps.lists(hps.booleans(), min_size=2, max_size=2))
dtype = draw(hps.sampled_from([np.float32, np.float64]))
mean = (
draw(single_arrays(shape=hps.just(arg_shapes[1]), dtype=dtype,
elements=floats(dtype=dtype)))
if include_arg[0] else 0)
stddev = (
draw(single_arrays(shape=hps.just(arg_shapes[2]), dtype=dtype,
elements=positive_floats(dtype=dtype)))
if include_arg[1] else 1)
return (arg_shapes[0], mean, stddev, dtype)
@hps.composite
def uniform_params(draw):
shape = draw(shapes())
arg_shapes = draw(
tfp_hps.broadcasting_shapes(shape, 3).map(tensorshapes_to_tuples))
include_arg = draw(hps.lists(hps.booleans(), min_size=2, max_size=2))
dtype = draw(hps.sampled_from([np.int32, np.int64, np.float32, np.float64]))
if dtype == np.int32 or dtype == np.int64:
# TF RandomUniformInt only supports scalar min/max.
arg_shapes = (arg_shapes[0], (), ())
elements = integers(), integers(min_value=1)
else:
elements = floats(dtype=dtype), positive_floats(dtype=dtype)
minval = (
draw(single_arrays(shape=hps.just(arg_shapes[1]), dtype=dtype,
elements=elements[0]))
if include_arg[0] else dtype(0))
maxval = minval + (
draw(single_arrays(shape=hps.just(arg_shapes[2]), dtype=dtype,
elements=elements[1]))
if include_arg[1] else dtype(10))
return (arg_shapes[0], minval, maxval, dtype)
def gamma_params():
def dict_to_params(d):
return (d['shape'], # sample shape
d['params'][0].astype(d['dtype']), # alpha
(d['params'][1].astype(d['dtype']) # beta (or None)
if d['include_beta'] else None),
d['dtype']) # dtype
return hps.fixed_dictionaries(
dict(shape=shapes(),
# TODO(jburnim): Support generating float64 params.
params=n_same_shape(n=2, elements=positive_floats(dtype=np.float32)),
include_beta=hps.booleans(),
dtype=hps.sampled_from([np.float32, np.float64]))
).map(dict_to_params) # dtype
@hps.composite
def bincount_params(draw):
num_buckets = draw(hps.integers(2, 20))
minlength = draw(hps.one_of(
hps.just(None),
hps.integers(num_buckets, num_buckets + 3),
))
arr = draw(single_arrays(dtype=np.int32,
shape=hps.just(tuple()),
batch_shape=(num_buckets,),
elements=hps.integers(
0, num_buckets - 1)))
weights = draw(hps.one_of(
hps.just(None),
single_arrays(dtype=np.int32,
shape=hps.just(tuple()),
batch_shape=(num_buckets,),
elements=hps.integers(0, 4))))
return arr, weights, minlength
@hps.composite
def confusion_matrix_params(draw):
num_labels = draw(hps.integers(1, 8))
labels = draw(single_arrays(
dtype=np.int32,
shape=hps.just(tuple()),
batch_shape=(num_labels,),
elements=hps.integers(0, num_labels - 1)))
predictions = draw(single_arrays(
dtype=np.int32,
shape=hps.just(tuple()),
batch_shape=(num_labels,),
elements=hps.integers(0, num_labels - 1)))
num_classes = draw(hps.one_of(
hps.just(None),
hps.integers(num_labels, num_labels + 3)))
weights = draw(hps.one_of(
hps.just(None),
single_arrays(dtype=np.int32,
shape=hps.just(tuple()),
batch_shape=(num_labels,),
elements=hps.integers(0, 4))))
return labels, predictions, num_classes, weights
@hps.composite
def gather_params(draw):
params_shape = shapes(min_dims=1)
params = draw(single_arrays(shape=params_shape))
rank = len(params.shape)
# Restricting batch_dims to be positive for now
# Batch dims can only be > 0 if rank > 1
batch_dims = draw(hps.integers(0, max(0, rank - 2)))
# Axis is constrained to be >= batch_dims
axis = draw(hps.one_of(
hps.integers(batch_dims, rank - 1),
hps.integers(-rank + batch_dims, -1),
))
elements = hps.integers(0, params.shape[axis] - 1)
indices_shape = shapes(min_dims=batch_dims + 1)
batch_shape = params.shape[:batch_dims]
indices = draw(single_arrays(dtype=np.int32, elements=elements,
shape=indices_shape,
batch_shape=batch_shape))
return params, indices, None, axis, batch_dims
@hps.composite
def gather_nd_params(draw):
if JAX_MODE:
# Restricting batch_dims to be positive for now
batch_dims = draw(hps.integers(min_value=0, max_value=4))
else:
batch_dims = 0
if batch_dims == 0:
batch_shape = ()
else:
batch_shape = draw(shapes(min_dims=batch_dims, max_dims=batch_dims))
params = draw(single_arrays(
shape=hps.just(batch_shape + draw(shapes(min_dims=1)))
))
params_shape = params.shape
rank = len(params_shape)
indices_shape = draw(hps.integers(min_value=1, max_value=rank - batch_dims))
indices_batch_shape = draw(shapes())
batches = []
for idx in range(indices_shape):
batches.append(
draw(single_arrays(
dtype=np.int32,
elements=hps.integers(
0, params.shape[batch_dims + idx] - 1
),
batch_shape=batch_shape + indices_batch_shape,
shape=hps.just((1,))
))
)
indices = np.concatenate(batches, -1)
return params, indices, batch_dims, None
@hps.composite
def repeat_params(draw):
input_array = draw(single_arrays())
rank = input_array.ndim
low, high = -rank, rank - 1
low, high = min(low, high), max(low, high)
axis = draw(hps.one_of(hps.just(None), hps.integers(low, high)))
if draw(hps.booleans()):
repeats = draw(hps.integers(1, 20))
if draw(hps.booleans()):
repeats = np.array([repeats])
return input_array, repeats, axis
if rank < 1:
repeats_shape = draw(hps.one_of(hps.just(()), hps.just((1,))))
else:
repeats_shape = (input_array.shape[axis] if axis is not None
else np.size(input_array),)
repeats = draw(hnp.arrays(dtype=np.int32, shape=repeats_shape,
elements=hps.integers(1, 20)))
return input_array, repeats, axis
@hps.composite
def linspace_params(draw):
shape = draw(shapes())
arg_shapes = draw(
tfp_hps.broadcasting_shapes(shape, 2).map(tensorshapes_to_tuples))
valid_dtypes = [np.int32, np.int64, np.float32, np.float64, np.complex64]
if not FLAGS.use_tpu:
valid_dtypes.append(np.complex128)
dtype = draw(hps.sampled_from(valid_dtypes))
start = draw(single_arrays(shape=hps.just(arg_shapes[0]), dtype=dtype))
stop = draw(single_arrays(shape=hps.just(arg_shapes[1]), dtype=dtype))
num = draw(hps.integers(0, 13))
axis = draw(hps.integers(-len(shape) - 1, len(shape)))
return Kwargs(start=start, stop=stop, num=num, axis=axis)
@hps.composite
def searchsorted_params(draw):
array_shape = shapes(min_dims=1)
array = draw(single_arrays(shape=array_shape))
# JAX and TF's searchsorted do not behave the same for negative zero, so we
# avoid generating inputs containing negative zero. See b/213512538 .
sorted_array = np.sort(np.where(array == -0.0, 0.0, array))
num_values = hps.integers(1, 20)
values = draw(single_arrays(
shape=shapes(min_dims=1, max_dims=1, max_side=draw(num_values)),
batch_shape=sorted_array.shape[:-1]))
values = np.where(values == -0.0, 0.0, values)
search_side = draw(hps.one_of(hps.just('left'), hps.just('right')))
return sorted_array, values, search_side
@hps.composite
def segment_ids(draw, n):
lengths = []
rsum = 0
while rsum < n:
lengths.append(draw(hps.integers(1, n-rsum)))
rsum += lengths[-1]
return np.repeat(np.arange(len(lengths)), np.array(lengths))
@hps.composite
def segment_params(draw, shape=shapes(min_dims=1), dtype=None, elements=None,
batch_shape=(), unique=False):
a = draw(single_arrays(shape=shape, dtype=dtype, elements=elements,
batch_shape=batch_shape, unique=unique))
ids = draw(segment_ids(a.shape[0]))
return (a, ids)
@hps.composite
def top_k_params(draw):
array_shape = shapes(min_dims=1)
# TODO(srvasude): The unique check can be removed once
# https://github.com/google/jax/issues/2124 is resolved.
array = draw(single_arrays(dtype=np.float32, unique=True, shape=array_shape))
k = draw(hps.integers(1, int(array.shape[-1])))
return array, k
@hps.composite
def histogram_fixed_width_bins_params(draw):
# TODO(b/187125431): the `min_side=2` and `unique` check can be removed if
# https://github.com/tensorflow/tensorflow/pull/38899 is re-implemented.
subnormal_kwarg = _maybe_get_subnormal_kwarg()
values = draw(single_arrays(
dtype=np.float32,
shape=shapes(min_dims=1, min_side=2),
unique=True,
# Avoid intervals containing 0 due to NP/TF discrepancy for bin boundaries
# near 0.
elements=hps.floats(min_value=0., max_value=1e10, width=32,
**subnormal_kwarg),
))
vmin, vmax = np.min(values), np.max(values)
value_min = draw(hps.one_of(
hps.just(vmin),
hps.just(vmin - 3))).astype(np.float32)
value_max = draw(hps.one_of(
hps.just(vmax),
hps.just(vmax + 3))).astype(np.float32)
nbins = draw(hps.integers(2, 10))
return values, [value_min, value_max], nbins
@hps.composite
def histogram_fixed_width_params(draw):
values, [value_min, value_max], nbins = draw(
histogram_fixed_width_bins_params())
return (values,
[value_min, max(value_max,
value_min + np.asarray(.1, value_min.dtype))],
nbins)
@hps.composite
def argsort_params(draw):
dtype = None
if FLAGS.test_mode == 'xla': # Double not supported by XLA TopKV2.
dtype = np.float32
return (
draw(array_axis_tuples(dtype=dtype)) +
(draw(hps.sampled_from(['ASCENDING', 'DESCENDING'])),
True)) # stable sort
@hps.composite
def conv2d_params(draw):
# NCHW is GPU-only
# data_format = draw(hps.sampled_from(['NHWC', 'NCHW']))
data_format = draw(hps.just('NHWC'))
input_shape = draw(shapes(4, 4, min_side=2, max_side=10))
if data_format.startswith('NC'):
channels = input_shape[1]
else:
channels = input_shape[3]
filter_shape = draw(shapes(3, 3, min_side=1, max_side=4))
filter_shape = filter_shape[:2] + (channels, filter_shape[-1])
input_ = draw(
single_arrays(
batch_shape=(),
shape=hps.just(input_shape),
))
filters = draw(single_arrays(
batch_shape=(),
shape=hps.just(filter_shape),
))
small = hps.integers(0, 5)
small_pos = hps.integers(1, 5)
strides = draw(hps.one_of(small_pos, hps.tuples(small_pos, small_pos)))
if isinstance(strides, tuple) and len(strides) == 2 and draw(hps.booleans()):
if data_format.startswith('NC'):
strides = (1, 1) + strides
else:
strides = (1,) + strides + (1,)
zeros = (0, 0)
explicit_padding = (
draw(hps.tuples(small, small)),
draw(hps.tuples(small, small)),
)
if data_format.startswith('NC'):
explicit_padding = (zeros, zeros) + explicit_padding
else:
explicit_padding = (zeros,) + explicit_padding + (zeros,)
padding = draw(
hps.one_of(
hps.just(explicit_padding), hps.sampled_from(['SAME', 'VALID'])))
return (input_, filters, strides, padding, data_format)
@hps.composite
def sparse_xent_params(draw):
num_classes = draw(hps.integers(1, 6))
batch_shape = draw(shapes(min_dims=1))
labels = single_arrays(
batch_shape=batch_shape,
shape=hps.just(tuple()),
dtype=np.int32,
elements=hps.integers(0, num_classes - 1))
subnormal_kwarg = _maybe_get_subnormal_kwarg()
logits = single_arrays(
batch_shape=batch_shape,
shape=hps.just((num_classes,)),
elements=hps.floats(min_value=-1e5, max_value=1e5, width=32,
**subnormal_kwarg))
return draw(
hps.fixed_dictionaries(dict(
labels=labels, logits=logits)).map(Kwargs))
@hps.composite
def xent_params(draw):
num_classes = draw(hps.integers(1, 6))
batch_shape = draw(shapes(min_dims=1))
labels = batched_probabilities(
batch_shape=batch_shape, num_classes=num_classes)
subnormal_kwarg = _maybe_get_subnormal_kwarg()
logits = single_arrays(
batch_shape=batch_shape,
shape=hps.just((num_classes,)),
elements=hps.floats(min_value=-1e5, max_value=1e5, width=32,
**subnormal_kwarg))
return draw(
hps.fixed_dictionaries(dict(
labels=labels, logits=logits)).map(Kwargs))
def _svd_post_process(vals):
# SVDs are not unique, so reconstruct input to test consistency (b/154538680).
# create_uv = False
if not isinstance(vals, tuple):
return vals
# create_uv = True
s, u, v = (np.array(x) for x in vals)
return np.matmul(
u,
s[..., None] *
# Vectorized matrix transpose.
np.swapaxes(v, -2, -1))
@hps.composite
def qr_params(draw):
full_matrices = draw(hps.booleans())
valid_dtypes = [np.float64]
if FLAGS.test_mode != 'xla': # XLA does not support complex QR.
valid_dtypes.append(np.complex128)
dtype = draw(hps.sampled_from(valid_dtypes))
if dtype == np.float64:
elements = floats(min_value=-1e6, max_value=1e6, dtype=dtype)
else:
elements = complex_numbers(min_magnitude=0., max_magnitude=1e6, dtype=dtype)
arr = draw(single_arrays(dtype=dtype, shape=shapes(min_dims=2),
elements=elements))
return arr, full_matrices
def _qr_post_process(qr):
"""Values of q corresponding to zero values of r may have arbitrary values."""
return np.matmul(qr.q, qr.r), np.float32(qr.q.shape), np.float32(qr.r.shape)
def _eig_post_process(vals):
if not isinstance(vals, tuple):
return np.sort(vals, axis=-1)
e, v = vals
return np.einsum('...ab,...b,...bc->...ac', v, e, v.swapaxes(-1, -2))
def _reduce_logsumexp_no_scipy(*args, **kwargs):
def _not_implemented(*args, **kwargs):
raise NotImplementedError()
with mock.patch.object(scipy_special, 'logsumexp', _not_implemented):
return nptf.reduce_logsumexp(*args, **kwargs)
# __Currently untested:__
# broadcast_dynamic_shape
# broadcast_static_shape
# broadcast_to
# math.accumulate_n
# math.betainc
# math.igamma
# math.igammac
# math.lbeta
# math.polyval
# math.zeta
# random.poisson
# random.set_seed
# TODO(jamieas): add tests for these functions.
NUMPY_TEST_CASES = [
TestCase(
'signal.fft', [
single_arrays(
shape=fft_shapes(fft_dim=1),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=1e-4,
rtol=1e-4,
xla_atol=5e-4),
TestCase(
'signal.fft2d', [
single_arrays(
shape=fft_shapes(fft_dim=2),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=1e-4,
rtol=1e-4),
TestCase(
'signal.fft3d', [
single_arrays(
shape=fft_shapes(fft_dim=3, max_fft_size=16),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=2e-3,
rtol=2e-3),
TestCase(
'signal.rfft', [
single_arrays(
shape=fft_shapes(fft_dim=1),
dtype=np.float32,
elements=floats(min_value=-1e3, max_value=1e3,
dtype=np.float32))
],
atol=1e-4,
rtol=1e-4,
xla_atol=3e-4),
TestCase(
'signal.rfft2d', [
single_arrays(
shape=fft_shapes(fft_dim=2),
dtype=np.float32,
elements=floats(min_value=-1e3, max_value=1e3,
dtype=np.float32))
],
atol=1e-3,
rtol=1e-3),
TestCase(
'signal.rfft3d', [
single_arrays(
shape=fft_shapes(fft_dim=3, max_fft_size=16),
dtype=np.float32,
elements=floats(min_value=-1e3, max_value=1e3,
dtype=np.float32))
],
atol=1e-2,
rtol=2e-3),
TestCase(
'signal.ifft', [
single_arrays(
shape=fft_shapes(fft_dim=1),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=1e-4,
rtol=1e-4),
TestCase(
'signal.ifft2d', [
single_arrays(
shape=fft_shapes(fft_dim=2),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=1e-4,
rtol=1e-4),
TestCase(
'signal.ifft3d', [
single_arrays(
shape=fft_shapes(fft_dim=3, max_fft_size=16),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=1e-4,
rtol=1e-4),
TestCase(
'signal.irfft', [
single_arrays(
shape=fft_shapes(fft_dim=1),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=3e-4,
rtol=3e-4),
TestCase(
'signal.irfft2d', [
single_arrays(
shape=fft_shapes(fft_dim=2),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=5e2))
],
atol=2e-4,
rtol=2e-4),
TestCase(
'signal.irfft3d', [
single_arrays(
shape=fft_shapes(fft_dim=3, max_fft_size=16),
dtype=np.complex64,
elements=complex_numbers(max_magnitude=1e3))
],
atol=4e-4,
rtol=4e-4),
# ArgSpec(args=['a', 'b', 'transpose_a', 'transpose_b', 'adjoint_a',
# 'adjoint_b', 'a_is_sparse', 'b_is_sparse', 'name'],
# varargs=None,
# keywords=None,
# defaults=(False, False, False, False, False, False, None))
TestCase('linalg.matmul', [matmul_compatible_pairs()]),
TestCase(
'linalg.eig', [pd_matrices()],
post_processor=_eig_post_process,
xla_disabled=True),
TestCase('linalg.eigh', [pd_matrices()], post_processor=_eig_post_process),
TestCase(
'linalg.eigvals', [pd_matrices()],
post_processor=_eig_post_process,
xla_disabled=True),
TestCase(
'linalg.eigvalsh', [pd_matrices()], post_processor=_eig_post_process),
TestCase(
'linalg.det', [nonsingular_matrices()], rtol=1e-3,
xla_disabled=True), # TODO(b/162937268): missing kernel.
# ArgSpec(args=['a', 'name', 'conjugate'], varargs=None, keywords=None)
TestCase('linalg.matrix_transpose',
[single_arrays(shape=shapes(min_dims=2))]),
TestCase('linalg.trace', [nonsingular_matrices()]),
# ArgSpec(args=['a', 'x', 'name'], varargs=None, keywords=None,
# defaults=(None,))
TestCase(
'math.polygamma', [
hps.tuples(hps.integers(0, 10).map(float), positive_floats()),
],
disabled=JAX_MODE,
xla_disabled=True), # TODO(b/163880625): Polygamma kernel
# ArgSpec(args=['arr', 'weights', 'minlength',
# 'maxlength', 'dtype', 'name'],
# varargs=None,
# keywords=None,
# defaults=(None, None, None, tf.int32, None))
TestCase('math.bincount', [bincount_params()],
xla_disabled=True), # missing kernel.
TestCase(
'math.confusion_matrix', [confusion_matrix_params()],
xla_disabled=True), # broken string-using assert.
TestCase('math.top_k', [top_k_params()], xla_const_args=(1,)),
# ArgSpec(args=['chol', 'rhs', 'name'], varargs=None, keywords=None,
# defaults=(None,))
TestCase('linalg.cholesky_solve', [
matmul_compatible_pairs(
x_strategy=pd_matrices().map(np.linalg.cholesky))
]),
# ArgSpec(args=['tensor', 'full_matrices', 'compute_uv', 'name'],
# varargs=None,
# keywords=None,
# defaults=(False, True, None))
TestCase(
'linalg.svd', [single_arrays(
shape=shapes(min_dims=2),
elements=floats(min_value=-1e10, max_value=1e10))],
post_processor=_svd_post_process),
TestCase(
'linalg.qr', [
qr_params(),
],
post_processor=_qr_post_process,
xla_const_args=(1,)), # full_matrices
# ArgSpec(args=['coeffs', 'x', 'name'], varargs=None, keywords=None,
# defaults=(None,))
TestCase('math.polyval', []),
# ArgSpec(args=['diagonal', 'name'], varargs=None, keywords=None,