-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_util.py
2056 lines (1726 loc) · 77.1 KB
/
test_util.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.
# ============================================================================
"""Utilities for testing TFP code."""
import contextlib
import functools
import math
import os
import random
import re
import sys
import unittest
from absl import flags
from absl import logging
from absl.testing import parameterized
import numpy as np
import six
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector
from tensorflow_probability.python.internal import distribution_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import empirical_statistical_testing
from tensorflow_probability.python.internal import samplers
from tensorflow_probability.python.internal import test_combinations
from tensorflow_probability.python.util.deferred_tensor import DeferredTensor
from tensorflow_probability.python.util.deferred_tensor import TransformedVariable
from tensorflow_probability.python.util.seed_stream import SeedStream
from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import
from absl.testing import absltest
__all__ = [
'substrate_disable_stateful_random_test',
'numpy_disable_gradient_test',
'numpy_disable_variable_test',
'jax_disable_variable_test',
'jax_disable_test_missing_functionality',
'disable_test_for_backend',
'main',
'test_all_tf_execution_regimes',
'test_graph_and_eager_modes',
'test_graph_mode_only',
'test_seed',
'test_seed_stream',
'floats_near',
'DiscreteScalarDistributionTestHelpers',
'TestCase',
'VectorDistributionTestHelpers',
]
JAX_MODE = False
NUMPY_MODE = False
TF_MODE = not (JAX_MODE or NUMPY_MODE)
flags.DEFINE_string('test_regex', '',
('If set, only run test cases for which this regex '
'matches "<TestCase>.<test_method>".'),
allow_override=True)
# Flags for controlling test_teed behavior.
flags.DEFINE_bool('vary_seed', False,
('Whether to vary the PRNG seed unpredictably. '
'With --runs_per_test=N, produces N iid runs.'),
allow_override=True)
flags.DEFINE_string('fixed_seed', None,
('PRNG seed to initialize every test with. '
'Takes precedence over --vary_seed when both appear.'),
allow_override=True,
allow_override_cpp=False,
allow_hide_cpp=True)
flags.DEFINE_enum('analyze_calibration', 'none',
['none', 'brief', 'full'],
('If set, auto-fails assertAllMeansClose and prints '
'a report of how failure-prone the test is.'),
allow_override=True)
FLAGS = flags.FLAGS
_TEST_BASE_CLASSES = (parameterized.TestCase,)
if TF_MODE:
_TEST_BASE_CLASSES = _TEST_BASE_CLASSES + (tf.test.TestCase,)
_DEFAULT_SEED = 87654321
class TestCase(*_TEST_BASE_CLASSES):
"""Class to provide TensorFlow Probability specific test features."""
def setUp(self):
if TF_MODE:
super(TestCase, self).setUp()
else:
# Fix the numpy and math random seeds.
np.random.seed(_DEFAULT_SEED)
random.seed(_DEFAULT_SEED)
def tearDown(self):
if TF_MODE:
super(TestCase, self).tearDown()
def maybe_static(self, x, is_static):
"""If `not is_static`, return placeholder_with_default with unknown shape.
Args:
x: A `Tensor`
is_static: a Python `bool`; if True, x is returned unchanged. If False, x
is wrapped with a tf1.placeholder_with_default with fully dynamic shape.
Returns:
maybe_static_x: `x`, possibly wrapped with in a
`placeholder_with_default` of unknown shape.
"""
if is_static:
return x
else:
return tf1.placeholder_with_default(x, shape=None)
@contextlib.contextmanager
def cached_session(self):
if TF_MODE:
with super(TestCase, self).cached_session() as sess:
yield sess
else:
with contextlib.nullcontext():
yield
@contextlib.contextmanager
def session(self):
if TF_MODE:
with super(TestCase, self).session() as sess:
yield sess
else:
with contextlib.nullcontext():
yield
def evaluate(self, x):
if TF_MODE:
return super(TestCase, self).evaluate(x)
if JAX_MODE:
import jax # pylint: disable=g-import-not-at-top
def _evaluate(x):
if x is None:
return x
# TODO(b/223267515): Improve handling of JAX typed PRNG keys.
if (
JAX_MODE
and hasattr(x, 'dtype')
and jax.dtypes.issubdtype(x.dtype, jax.dtypes.prng_key)
):
return x
return np.array(x)
return tf.nest.map_structure(_evaluate, x, expand_composites=True)
def _GetNdArray(self, a):
if TF_MODE:
return super(TestCase, self)._GetNdArray(a)
return np.array(a)
def _evaluateTensors(self, a, b):
if JAX_MODE:
import jax # pylint: disable=g-import-not-at-top
# HACK: In assertions (like self.assertAllClose), convert typed PRNG keys
# to raw arrays so they can be compared with our existing machinery.
if hasattr(a, 'dtype') and jax.dtypes.issubdtype(
a.dtype, jax.dtypes.prng_key
):
a = jax.random.key_data(a)
if hasattr(b, 'dtype') and jax.dtypes.issubdtype(
b.dtype, jax.dtypes.prng_key
):
b = jax.random.key_data(b)
if tf.is_tensor(a) and tf.is_tensor(b):
(a, b) = self.evaluate([a, b])
elif tf.is_tensor(a) and not tf.is_tensor(b):
a = self.evaluate(a)
elif not tf.is_tensor(a) and tf.is_tensor(b):
b = self.evaluate(b)
return a, b
def assertDTypeEqual(self, target, expected_dtype):
"""Assert ndarray data type is equal to expected.
Args:
target: The numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor).
expected_dtype: Expected data type.
"""
target = self._GetNdArray(target)
if not isinstance(target, list):
arrays = [target]
for arr in arrays:
self.assertEqual(arr.dtype, expected_dtype)
# pylint: disable=g-doc-return-or-yield
@contextlib.contextmanager
def assertRaisesWithPredicateMatch(self, exception_type,
expected_err_re_or_predicate):
"""Returns a context manager to enclose code expected to raise an exception.
If the exception is an OpError, the op stack is also included in the message
predicate search.
Args:
exception_type: The expected type of exception that should be raised.
expected_err_re_or_predicate: If this is callable, it should be a function
of one argument that inspects the passed-in exception and returns True
(success) or False (please fail the test). Otherwise, the error message
is expected to match this regular expression partially.
Returns:
A context manager to surround code that is expected to raise an
exception.
"""
if callable(expected_err_re_or_predicate):
predicate = expected_err_re_or_predicate
else:
def predicate(e):
err_str = e.message if isinstance(e, tf.errors.OpError) else str(e)
op = e.op if isinstance(e, tf.errors.OpError) else None
while op is not None:
err_str += '\nCaused by: ' + op.name
op = op._original_op # pylint: disable=protected-access
logging.info('Searching within error strings: "%s" within "%s"',
expected_err_re_or_predicate, err_str)
return re.search(expected_err_re_or_predicate, err_str)
try:
yield
self.fail(exception_type.__name__ + ' not raised')
except Exception as e: # pylint: disable=broad-except
if not isinstance(e, exception_type) or not predicate(e):
raise AssertionError('Exception of type %s: %s' %
(str(type(e)), str(e))) from e
@contextlib.contextmanager
def assertRaisesOpError(self, msg):
if TF_MODE:
with super(TestCase, self).assertRaisesOpError(msg):
yield
else:
try:
yield
self.fail('No exception raised. Expected exception similar to '
'tf.errors.OpError with message: %s' % msg)
except Exception as e: # pylint: disable=broad-except
err_str = str(e)
if re.search(msg, err_str):
return
logging.error('Expected exception to match `%s`!', msg)
raise
def assertNear(self, f1, f2, err, msg=None):
"""Asserts that two floats are near each other.
Checks that |f1 - f2| < err and asserts a test failure
if not.
Args:
f1: A float value.
f2: A float value.
err: A float value.
msg: An optional string message to append to the failure message.
"""
# f1 == f2 is needed here as we might have: f1, f2 = inf, inf
self.assertTrue(
f1 == f2 or math.fabs(f1 - f2) <= err, '%f != %f +/- %f%s' %
(f1, f2, err, ' (%s)' % msg if msg is not None else ''))
def assertArrayNear(self, farray1, farray2, err, msg=None):
"""Asserts that two float arrays are near each other.
Checks that for all elements of farray1 and farray2
|f1 - f2| < err. Asserts a test failure if not.
Args:
farray1: a list of float values.
farray2: a list of float values.
err: a float value.
msg: Optional message to report on failure.
"""
self.assertEqual(len(farray1), len(farray2), msg=msg)
for f1, f2 in zip(farray1, farray2):
self.assertNear(float(f1), float(f2), err, msg=msg)
def assertNotAllEqual(self, a, b, msg=None):
"""Asserts that two numpy arrays or Tensors do not have the same values.
Args:
a: the expected numpy ndarray or anything can be converted to one.
b: the actual numpy ndarray or anything can be converted to one.
msg: Optional message to report on failure.
"""
try:
self.assertAllEqual(a, b)
except AssertionError:
return
msg = msg or ''
raise AssertionError('The two values are equal at all elements. %s' % msg)
def assertNotAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):
"""Assert that two numpy arrays, or Tensors, do not have near values.
Args:
a: The expected numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor), or any arbitrarily nested of
structure of these.
b: The actual numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor), or any arbitrarily nested of
structure of these.
rtol: relative tolerance.
atol: absolute tolerance.
msg: Optional message to report on failure.
Raises:
AssertionError: If `a` and `b` are unexpectedly close at all elements.
"""
try:
self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)
except AssertionError:
return
msg = msg or ''
raise AssertionError('The two values are close at all elements. %s' % msg)
def assertEqual(self, first, second, msg=None):
if isinstance(first, list) and isinstance(second, tuple):
first = tuple(first)
if isinstance(first, tuple) and isinstance(second, list):
second = tuple(second)
return super(TestCase, self).assertEqual(first, second, msg)
def assertAllCloseAccordingToType(self,
a,
b,
rtol=1e-6,
atol=1e-6,
float_rtol=1e-6,
float_atol=1e-6,
half_rtol=1e-3,
half_atol=1e-3,
bfloat16_rtol=1e-2,
bfloat16_atol=1e-2,
msg=None):
"""Like assertAllClose, but also suitable for comparing fp16 arrays.
In particular, the tolerance is reduced to 1e-3 if at least
one of the arguments is of type float16.
Args:
a: the expected numpy ndarray or anything can be converted to one.
b: the actual numpy ndarray or anything can be converted to one.
rtol: relative tolerance.
atol: absolute tolerance.
float_rtol: relative tolerance for float32.
float_atol: absolute tolerance for float32.
half_rtol: relative tolerance for float16.
half_atol: absolute tolerance for float16.
bfloat16_rtol: relative tolerance for bfloat16.
bfloat16_atol: absolute tolerance for bfloat16.
msg: Optional message to report on failure.
"""
(a, b) = self._evaluateTensors(a, b)
a = self._GetNdArray(a)
b = self._GetNdArray(b)
# types with lower tol are put later to overwrite previous ones.
if (a.dtype == np.float32 or b.dtype == np.float32 or
a.dtype == np.complex64 or b.dtype == np.complex64):
rtol = max(rtol, float_rtol)
atol = max(atol, float_atol)
if a.dtype == np.float16 or b.dtype == np.float16:
rtol = max(rtol, half_rtol)
atol = max(atol, half_atol)
if not NUMPY_MODE:
if a.dtype == tf.bfloat16 or b.dtype == tf.bfloat16:
rtol = max(rtol, bfloat16_rtol)
atol = max(atol, bfloat16_atol)
self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)
def assertAllEqual(self, a, b, msg=None):
"""Asserts that two numpy arrays or Tensors have the same values.
Args:
a: the expected numpy ndarray or anything can be converted to one.
b: the actual numpy ndarray or anything can be converted to one.
msg: Optional message to report on failure.
"""
msg = msg if msg else ''
(a, b) = self._evaluateTensors(a, b)
a = self._GetNdArray(a)
b = self._GetNdArray(b)
# Arbitrary bounds so that we don't print giant tensors.
if (b.ndim <= 3 or b.size < 500):
self.assertEqual(
a.shape, b.shape, 'Shape mismatch: expected %s, got %s.'
' Contents: %r. \n%s.' % (a.shape, b.shape, b, msg))
else:
self.assertEqual(
a.shape, b.shape, 'Shape mismatch: expected %s, got %s.'
' %s' % (a.shape, b.shape, msg))
same = (a == b)
dtype_list = [np.float16, np.float32, np.float64]
if not NUMPY_MODE:
dtype_list += [tf.bfloat16]
if a.dtype in dtype_list:
same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b)))
msgs = [msg]
if not np.all(same):
# Adds more details to np.testing.assert_array_equal.
diff = np.logical_not(same)
if a.ndim:
x = a[np.where(diff)]
y = b[np.where(diff)]
msgs.append('not equal where = {}'.format(np.where(diff)))
else:
# np.where is broken for scalars
x, y = a, b
msgs.append('not equal lhs = %r' % x)
msgs.append('not equal rhs = %r' % y)
if (a.dtype.kind != b.dtype.kind and
{a.dtype.kind, b.dtype.kind}.issubset({'U', 'S', 'O'})):
a_list = []
b_list = []
# OK to flatten `a` and `b` because they are guaranteed to have the
# same shape.
for out_list, flat_arr in [(a_list, a.flat), (b_list, b.flat)]:
for item in flat_arr:
if isinstance(item, str):
out_list.append(item.encode('utf-8'))
else:
out_list.append(item)
a = np.array(a_list)
b = np.array(b_list)
np.testing.assert_array_equal(a, b, err_msg='\n'.join(msgs))
def assertAllGreater(self, a, comparison_target):
"""Assert element values are all greater than a target value.
Args:
a: The numpy `ndarray`, or anything that can be converted into a numpy
`ndarray` (including Tensor).
comparison_target: The target value of comparison.
"""
(a, comparison_target) = self._evaluateTensors(a, comparison_target)
a = self._GetNdArray(a)
self.assertGreater(np.min(a), comparison_target)
def assertAllLess(self, a, comparison_target):
"""Assert element values are all less than a target value.
Args:
a: The numpy `ndarray`, or anything that can be converted into a numpy
`ndarray` (including Tensor).
comparison_target: The target value of comparison.
"""
(a, comparison_target) = self._evaluateTensors(a, comparison_target)
a = self._GetNdArray(a)
self.assertLess(np.max(a), comparison_target)
def assertAllGreaterEqual(self, a, comparison_target):
"""Assert element values are all greater than or equal to a target value.
Args:
a: The numpy `ndarray`, or anything that can be converted into a numpy
`ndarray` (including Tensor).
comparison_target: The target value of comparison.
"""
(a, comparison_target) = self._evaluateTensors(a, comparison_target)
a = self._GetNdArray(a)
self.assertGreaterEqual(np.min(a), comparison_target)
def assertAllLessEqual(self, a, comparison_target):
"""Assert element values are all less than or equal to a target value.
Args:
a: The numpy `ndarray`, or anything that can be converted into a numpy
`ndarray` (including Tensor).
comparison_target: The target value of comparison.
"""
(a, comparison_target) = self._evaluateTensors(a, comparison_target)
a = self._GetNdArray(a)
self.assertLessEqual(np.max(a), comparison_target)
def assertShapeEqual(self, input_a, input_b, msg=None):
if TF_MODE:
super(TestCase, self).assertShapeEqual(input_a, input_b, msg=msg)
else:
self.assertTupleEqual(input_a.shape, input_b.shape, msg=msg)
def assertAllAssertsNested(self, assert_fn, *structure, **kwargs):
"""Run `assert_fn` on `structure` and report which elements errored.
This function will run `assert_fn` on each element of `structure` as
`assert_fn(structure[0], structure[1], ...)`, collecting any exceptions
raised in the process. Afterward, it will report which elements of
`structure` triggered an assertion, as well as the assertions themselves.
Args:
assert_fn: A callable that accepts as many arguments as there are
structures.
*structure: A list of nested structures.
**kwargs: Valid keyword args are:
* `shallow`: If not None, uses this as the shared tree prefix of
`structure` for the purpose of being able to use `structure` which
only share that tree prefix (e.g. `[1, 2]` and `[[1], 2]` share the
`[., .]` tree prefix).
* `msg`: Used as the message when a failure happened. Default:
`"AllAssertsNested failed"`.
* `check_types`: If `True`, types of sequences are checked as well,
including the keys of dictionaries. If `False`, for example a list and
a tuple of objects may be equivalent. Default: `False`.
Raises:
AssertionError: If the structures are mismatched, or at `assert_fn` raised
an exception at least once.
"""
shallow = kwargs.pop('shallow', None)
if shallow is None:
shallow = structure[0]
msg = kwargs.pop('msg', 'AllAssertsNested failed')
def _one_part(*structure):
try:
assert_fn(*structure)
except Exception as part_e: # pylint: disable=broad-except
return part_e
try:
maybe_exceptions = nest.map_structure_up_to(shallow, _one_part,
*structure, **kwargs)
overall_exception = None
exceptions_with_paths = [
(p, e)
for p, e in nest.flatten_with_joined_string_paths(maybe_exceptions)
if e is not None
]
except Exception as e: # pylint: disable=broad-except
overall_exception = e
exceptions_with_paths = []
final_msg = '{}:\n\n'.format(msg)
if overall_exception:
final_msg += str(overall_exception)
raise AssertionError(final_msg)
if exceptions_with_paths:
for i, one_structure in enumerate(structure):
final_msg += 'Structure {}:\n{}\n\n'.format(i, one_structure)
final_msg += 'Exceptions:\n\n'
for p, exception in exceptions_with_paths:
final_msg += 'Path: {}\nException: {}\n{}\n\n'.format(
p,
type(exception).__name__, exception)
# Drop the final two newlines.
raise AssertionError(final_msg[:-2])
def assertAllInRange(self,
target,
lower_bound,
upper_bound,
open_lower_bound=False,
open_upper_bound=False):
"""Assert that elements in a Tensor are all in a given range.
Args:
target: The numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor).
lower_bound: lower bound of the range
upper_bound: upper bound of the range
open_lower_bound: (`bool`) whether the lower bound is open (i.e., > rather
than the default >=)
open_upper_bound: (`bool`) whether the upper bound is open (i.e., < rather
than the default <=)
Raises:
AssertionError:
if the value tensor does not have an ordered numeric type (float* or
int*), or
if there are nan values, or
if any of the elements do not fall in the specified range.
"""
target = self._GetNdArray(target)
if not (np.issubdtype(target.dtype, np.floating) or
np.issubdtype(target.dtype, np.integer)):
raise AssertionError(
'The value of %s does not have an ordered numeric type, instead it '
'has type: %s' % (target, target.dtype))
nan_subscripts = np.where(np.isnan(target))
if np.size(nan_subscripts):
raise AssertionError(
'%d of the %d element(s) are NaN. '
'Subscripts(s) and value(s) of the NaN element(s):\n' %
(len(nan_subscripts[0]), np.size(target)) +
'\n'.join(self._format_subscripts(nan_subscripts, target)))
range_str = (('(' if open_lower_bound else '[') + str(lower_bound) + ', ' +
str(upper_bound) + (')' if open_upper_bound else ']'))
violations = (
np.less_equal(target, lower_bound) if open_lower_bound else np.less(
target, lower_bound))
violations = np.logical_or(
violations,
np.greater_equal(target, upper_bound)
if open_upper_bound else np.greater(target, upper_bound))
violation_subscripts = np.where(violations)
if np.size(violation_subscripts):
raise AssertionError(
'%d of the %d element(s) are outside the range %s. ' %
(len(violation_subscripts[0]), np.size(target), range_str) +
'Subscript(s) and value(s) of the offending elements:\n' +
'\n'.join(self._format_subscripts(violation_subscripts, target)))
def assertAllEqualNested(self, a, b, check_types=False, shallow=None):
"""Assert that analogous entries in two nested structures are equivalent.
Args:
a: A nested structure.
b: A nested structure.
check_types: If `True`, types of sequences are checked as well, including
the keys of dictionaries. If `False`, for example a list and a tuple of
objects may be equivalent.
shallow: If not None, uses this as the shared tree prefix of `a` and `b`
for the purpose of being able to use `a` and `b` which only share that
tree prefix (e.g. `[1, 2]` and `[[1], 2]` share the `[., .]` tree
prefix).
"""
self.assertAllAssertsNested(
self.assertAllEqual,
a,
b,
check_types=check_types,
msg='AllEqualNested failed',
shallow=shallow)
def assertAllClose(self, a, b, rtol=1e-06, atol=1e-06, msg=None, path=None):
path = [] if path is None else path
path_str = ''
msg = msg if msg else ''
if isinstance(a, (list, tuple)):
# Try to directly compare a, b as ndarrays; if not work, then traverse
# through the sequence, which is more expensive.
try:
(a, b) = self._evaluateTensors(a, b)
a_as_ndarray = self._GetNdArray(a)
b_as_ndarray = self._GetNdArray(b)
self.assertAllClose(
a_as_ndarray,
b_as_ndarray,
rtol=rtol,
atol=atol,
msg='Mismatched value: a%s is different from b%s. %s' %
(path_str, path_str, msg))
except (ValueError, TypeError, NotImplementedError) as e:
if len(a) != len(b):
raise ValueError(
'Mismatched length: a%s has %d items, but b%s has %d items. %s' %
(path_str, len(a), path_str, len(b), msg)) from e
for idx, (a_ele, b_ele) in enumerate(zip(a, b)):
path.append(str(idx))
self.assertAllClose(
a_ele, b_ele, rtol=rtol, atol=atol, path=path, msg=msg)
del path[-1]
else:
(a, b) = self._evaluateTensors(a, b)
a = self._GetNdArray(a)
b = self._GetNdArray(b)
# When the array rank is small, print its contents. Numpy array printing
# is implemented using inefficient recursion so prints can cause tests to
# time out.
if a.shape != b.shape and (b.ndim <= 3 or b.size < 500):
shape_mismatch_msg = (
'Shape mismatch: expected %s, got %s with contents '
'%s.') % (a.shape, b.shape, b)
else:
shape_mismatch_msg = 'Shape mismatch: expected %s, got %s.' % (a.shape,
b.shape)
self.assertEqual(a.shape, b.shape, shape_mismatch_msg)
msgs = [msg]
a_dtype = a.dtype
if not np.allclose(a, b, rtol=rtol, atol=atol):
# Adds more details to np.testing.assert_allclose.
#
# NOTE: numpy.allclose (and numpy.testing.assert_allclose)
# checks whether two arrays are element-wise equal within a
# tolerance. The relative difference (rtol * abs(b)) and the
# absolute difference atol are added together to compare against
# the absolute difference between a and b. Here, we want to
# tell user which elements violate such conditions.
cond = np.logical_or(
np.abs(a - b) > atol + rtol * np.abs(b),
np.isnan(a) != np.isnan(b))
if a.ndim:
x = a[np.where(cond)]
y = b[np.where(cond)]
msgs.append('not close where = {}'.format(np.where(cond)))
else:
# np.where is broken for scalars
x, y = a, b
msgs.append('not close lhs = {}'.format(x))
msgs.append('not close rhs = {}'.format(y))
msgs.append('not close dif = {}'.format(np.abs(x - y)))
msgs.append('not close tol = {}'.format(atol + rtol * np.abs(y)))
msgs.append('dtype = {}, shape = {}'.format(a_dtype, a.shape))
np.testing.assert_allclose(
a, b, rtol=rtol, atol=atol, err_msg='\n'.join(msgs), equal_nan=True)
def assertAllCloseNested(
self, a, b, rtol=1e-06, atol=1e-06, check_types=False):
"""Assert that analogous entries in two nested structures have near values.
Args:
a: A nested structure.
b: A nested structure.
rtol: scalar relative tolerance.
Default value: `1e-6`.
atol: scalar absolute tolerance.
Default value: `1e-6`.
check_types: If `True`, types of sequences are checked as well, including
the keys of dictionaries. If `False`, for example a list and a tuple of
objects may be equivalent.
"""
self.assertAllAssertsNested(
lambda x, y: self.assertAllClose(x, y, rtol=rtol, atol=atol),
a,
b,
check_types=check_types,
msg='AllCloseNested failed')
def assertAllTrue(self, a):
"""Assert that all entries in a boolean `Tensor` are True."""
a_ = self._GetNdArray(a)
all_true = np.ones_like(a_, dtype=np.bool_)
self.assertAllEqual(all_true, a_)
def assertAllFalse(self, a):
"""Assert that all entries in a boolean `Tensor` are False."""
a_ = self._GetNdArray(a)
all_false = np.zeros_like(a_, dtype=np.bool_)
self.assertAllEqual(all_false, a_)
def assertAllFinite(self, a):
"""Assert that all entries in a `Tensor` are finite.
Args:
a: A `Tensor` whose entries are checked for finiteness.
"""
is_finite = np.isfinite(self._GetNdArray(a))
all_true = np.ones_like(is_finite, dtype=np.bool_)
self.assertAllEqual(all_true, is_finite)
def assertAllPositiveInf(self, a):
"""Assert that all entries in a `Tensor` are equal to positive infinity.
Args:
a: A `Tensor` whose entries must be verified as positive infinity.
"""
is_positive_inf = np.isposinf(self._GetNdArray(a))
all_true = np.ones_like(is_positive_inf, dtype=np.bool_)
self.assertAllEqual(all_true, is_positive_inf)
def assertAllNegativeInf(self, a):
"""Assert that all entries in a `Tensor` are negative infinity.
Args:
a: A `Tensor` whose entries must be verified as negative infinity.
"""
is_negative_inf = np.isneginf(self._GetNdArray(a))
all_true = np.ones_like(is_negative_inf, dtype=np.bool_)
self.assertAllEqual(all_true, is_negative_inf)
def assertNotAllZero(self, a):
"""Assert that all entries in a `Tensor` are nonzero.
Args:
a: A `Tensor` whose entries must be verified as nonzero.
"""
self.assertNotAllEqual(a, tf.nest.map_structure(tf.zeros_like, a))
def assertAllNotNan(self, a):
"""Assert that every entry in a `Tensor` is not NaN.
Args:
a: A `Tensor` whose entries must be verified as not NaN.
"""
is_not_nan = ~np.isnan(self._GetNdArray(a))
all_true = np.ones_like(is_not_nan, dtype=np.bool_)
self.assertAllEqual(all_true, is_not_nan)
def assertAllNan(self, a):
"""Assert that every entry in a `Tensor` is NaN.
Args:
a: A `Tensor` whose entries must be verified as NaN.
"""
is_nan = np.isnan(self._GetNdArray(a))
all_true = np.ones_like(is_nan, dtype=np.bool_)
self.assertAllEqual(all_true, is_nan)
def assertAllNotNone(self, a):
"""Assert that no entry in a collection is None.
Args:
a: A Python iterable collection, whose entries must be verified as not
being `None`.
"""
each_not_none = [x is not None for x in a]
if all(each_not_none):
return
msg = (
'Expected no entry to be `None` but found `None` in positions {}'
.format([i for i, x in enumerate(each_not_none) if not x]))
raise AssertionError(msg)
def assertAllIs(self, a, b):
"""Assert that each element of `a` `is` `b`.
Args:
a: A Python iterable collection, whose entries must be elementwise `is b`.
b: A Python iterable collection, whose entries must be elementwise `is a`.
"""
if len(a) != len(b):
raise AssertionError(
'Arguments `a` and `b` must have the same number of elements '
'but found len(a)={} and len(b)={}.'.format(len(a), len(b)))
each_is = [a is b for a, b in zip(a, b)]
if all(each_is):
return
msg = (
'For each element expected `a is b` but found `not is` in positions {}'
.format([i for i, x in enumerate(each_is) if not x]))
raise AssertionError(msg)
def assertAllMeansClose(
self, to_reduce, expected, axis, atol=1e-6, rtol=1e-6, msg=None):
"""Assert means of `to_reduce` along `axis` as `expected`, with diagnostics.
Operationally, this is equivalent to
```
means = tf.reduce_mean(to_reduce, axis)
assertAllClose(means, expected, atol, rtol, msg)
```
except that by intercepting samples before the reduction is
carried out, `assertAllMeansClose` can diagnose the statistical
significance of failures.
Specifically, `to_reduce` is assumed to be sampled IID along
`axis`. Based on this, it's possible to estimate the probability
of `assertAllMeansClose` failing as the upstream PRNG seed is
varied, and suggest parameter changes to control that probability.
To assess a particular test statistically, run it with
```
--test_arg=--vary_seed --test_arg=--analyze_calibration=brief
```
or
```
--test_arg=--vary_seed --test_arg=--analyze_calibration=full
```
To avoid bias in the reported diagnostics, either value of
`--analyze_calibration` force-fails the assertion; diagnostics are
reported independently of whether the current sample's mean is
close to `expected` or not.
Caveats:
- `--vary_seed` is important to prevent bias: if
`--analyze_calibration` is not passed, `assertAllMeansClose`
only fails if the mean of `to_reduce` is far from `expected`. A
seed that is brought to your attention by this happening is by
construction unlucky, and diagnostics reported from it (e.g., by
passing `--analyze_calibration` but not `--vary_seed`) will be
overly pessimistic.
- The report produced by `assertAllMeansClose` only assesses
significance; i.e., assuming the test and the code under test
are correct, how should the parameters of the test be set to
control accidental failures. Sometimes, a bug will manifest as
absurd suggestions for making the test pass---it's up to the
user to notice this happening.
- The report makes assumptions it does not test:
- that the elements of `to_reduce` actually are IID along `axis`;
- that there are enough of them that the empirical distribution
observed by one call to `assertAllMeansClose` is a good
approximation to the true generating distribution; and
- in the case of the Gaussian extrapolation, that there are
enough samples that the distribution on means is approximately
Gaussian.
- The suggestions in the report are extrapolations based on a
random sample. They may vary across runs and are not guaranteed
to be accurate. In particular, if increasing the number of
samples a test draws, it's reasonable to rerun the diagnostics,
because they now have more information to work with.
Args:
to_reduce: Tensor of samples, presumed IID along `axis`.
Other dimensions are taken to be batch dimensions.
expected: Tensor of expected mean values. Must broadcast
with the reduction of `to_reduce` along `axis`.
axis: Python `int` giving the reduction axis.
atol: Tensor of absolute tolerances for the means. Must
broadcast with the reduction of `to_reduce` along `axis`.
rtol: Tensor of relative tolerances for the means. Must
broadcast with the reduction of `to_reduce` along `axis`.
msg: Optional string to insert into the failure message,
if any.
"""
mean = tf.reduce_mean(to_reduce, axis=axis)
if FLAGS.analyze_calibration == 'none':
msg = (msg or '') + '\nTo assess statistically, run with'
msg += '\n --test_arg=--vary_seed --test_arg=--analyze_calibration=brief'
msg += '\nor'
msg += '\n --test_arg=--vary_seed --test_arg=--analyze_calibration=full'
self.assertAllClose(mean, expected, atol=atol, rtol=rtol, msg=msg)
else:
to_reduce = self._GetNdArray(to_reduce)
expected = self._GetNdArray(expected)
if msg is None:
msg = ''
else:
msg += '\n'
if FLAGS.analyze_calibration == 'brief':
msg += empirical_statistical_testing.brief_report(
to_reduce, expected, axis, atol, rtol)
msg += ('\nFor more information, run with '
'--test_arg=--analyze_calibration=full.')
else:
msg += empirical_statistical_testing.full_report(
to_reduce, expected, axis, atol, rtol)
if not FLAGS.vary_seed and FLAGS.fixed_seed is None:
msg += '\nWARNING: Above report may be biased as --vary_seed='
msg += 'False and --fixed_seed is not set. '
msg += 'See docstring of `assertAllMeansClose`.'
raise AssertionError(msg)
def assertConvertVariablesToTensorsWorks(self, obj):
"""Checks that Variables are correctly converted to Tensors inside CTs."""
self.assertIsInstance(obj, tf.__internal__.CompositeTensor)
tensor_obj = obj._convert_variables_to_tensors() # pylint: disable=protected-access
self.assertIs(type(obj), type(tensor_obj))
self.assertEmpty(tensor_obj.variables)
self._check_tensors_equal_variables(obj, tensor_obj)
def _check_tensors_equal_variables(self, obj, tensor_obj):
"""Checks that Variables in `obj` have equivalent Tensors in `tensor_obj."""
if isinstance(obj, (tf.Variable, DeferredTensor)):
self.assertAllClose(tf.convert_to_tensor(obj),
tf.convert_to_tensor(tensor_obj))
if isinstance(obj, TransformedVariable):
self.assertIsInstance(tensor_obj, DeferredTensor)
self.assertNotIsInstance(tensor_obj, TransformedVariable)
if isinstance(obj, DeferredTensor):
if isinstance(obj._transform_fn, bijector.Bijector): # pylint: disable=protected-access
self._check_tensors_equal_variables(
obj._transform_fn, tensor_obj._transform_fn) # pylint: disable=protected-access
else:
self.assertIsInstance(tensor_obj, tf.Tensor)
elif isinstance(obj, tf.__internal__.CompositeTensor):
params = getattr(obj, 'parameters', {})