-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathhypothesis_testlib.py
1653 lines (1436 loc) · 66.2 KB
/
hypothesis_testlib.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 property-based testing for TFP distributions."""
import collections
import functools
import inspect
from absl import logging
import hypothesis as hp
from hypothesis import strategies as hps
import numpy as np
import six
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import distributions as tfd
from tensorflow_probability.python import util as tfp_util
from tensorflow_probability.python.bijectors import ascending
from tensorflow_probability.python.bijectors import hypothesis_testlib as bijector_hps
from tensorflow_probability.python.distributions import distribution
from tensorflow_probability.python.experimental import distributions as tfed
from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps
from tensorflow_probability.python.internal import tensorshape_util
JAX_MODE = False
# 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
TF2_UNFRIENDLY_DISTS = (
# TODO(b/183723782): Enable these tests.
'MultivariateNormalDiag',
'MultivariateNormalFullCovariance',
'MultivariateNormalTriL',
)
# SPECIAL_DISTS are distributions that should not be drawn by
# `base_distributions`, because they are parameterized by one or more
# sub-distributions themselves. This list is used to suppress warnings from
# `_instantiable_base_dists`, below.
SPECIAL_DISTS = (
'Autoregressive',
'BatchBroadcast', # (has strategy)
'BatchConcat',
'BatchReshape', # (has strategy)
'Blockwise',
'Distribution', # Base class; not a distribution at all
'Empirical', # Base distribution with custom instantiation; (has strategy)
'HiddenMarkovModel',
'Inflated',
'JointDistribution',
'JointDistributionCoroutine',
'JointDistributionCoroutineAutoBatched',
'JointDistributionNamed',
'JointDistributionNamedAutoBatched',
'JointDistributionSequential',
'JointDistributionSequentialAutoBatched',
'GaussianProcess', # PSDKernel strategy not implemented.
'GaussianProcessRegressionModel', # PSDKernel strategy not implemented.
'Independent', # (has strategy)
'LambertWDistribution',
'MatrixNormalLinearOperator',
'MatrixTLinearOperator',
'MarkovChain',
'Masked', # (has strategy)
'Mixture', # (has strategy)
'MixtureSameFamily', # (has strategy)
'MultivariateNormalLinearOperator',
'MultivariateNormalLowRankUpdateLinearOperatorCovariance',
'MultivariateNormalDiagPlusLowRank', # Some batch shapes fail (b/177958275)
'MultivariateStudentTLinearOperator',
'Sample', # (has strategy)
'StudentTProcess',
'TransformedDistribution', # (has strategy)
'QuantizedDistribution', # (has strategy)
'VariationalGaussianProcess', # PSDKernel strategy not implemented.
'WishartLinearOperator',
'ZeroInflatedNegativeBinomial', # b/244737961
)
# MUTEX_PARAMS are mutually exclusive parameters that cannot be drawn together
# in broadcasting_params.
MUTEX_PARAMS = (
set(['logits', 'probs']),
set(['probits', 'probs']),
set(['rate', 'log_rate']),
set(['rate1', 'log_rate1']),
set(['rate2', 'log_rate2']),
set(['scale', 'log_scale']),
set(['scale', 'scale_tril', 'scale_diag']),
)
# Allowlist of underlying distributions for QuantizedDistribution (must have
# continuous, infinite support -- QuantizedDistribution also works for finite-
# support distributions for which the length of the support along each dimension
# is at least 1, though it is difficult to construct draws of these
# distributions in general, and wouldn't contribute much to test coverage.)
QUANTIZED_BASE_DISTS = (
'Chi2',
'Exponential',
'LogNormal',
'Logistic',
'Normal',
'Pareto',
'Poisson',
'StudentT',
)
# Functions used to constrain randomly sampled parameter ndarrays.
# TODO(b/128518790): Eliminate / minimize the fudge factors in here.
def constrain_between_eps_and_one_minus_eps(eps0=1e-6, eps1=1e-6):
return lambda x: eps0 + (1 - (eps0 + eps1)) * tf.sigmoid(x)
def fix_finite_discrete(d):
size = d.get('probs', d.get('logits', None)).shape[-1]
return dict(d, outcomes=tf.linspace(-1.0, 1.0, size))
def fix_lkj(d):
return dict(d, concentration=d['concentration'] + 1, dimension=3)
def fix_normal_inverse_gaussian(d):
tailweight = tfp_hps.ensure_high_gt_low(
tf.math.abs(d['skewness']), d['tailweight'])
# Make sure that |skewness| < tailweight
return dict(d, tailweight=(tailweight + 1.))
def fix_spherical_uniform(d):
return dict(d, dimension=5, batch_shape=[])
def fix_pert(d):
peak = tfp_hps.ensure_high_gt_low(d['low'], d['peak'])
high = tfp_hps.ensure_high_gt_low(peak, d['high'])
temperature = tfp_hps.ensure_high_gt_low(
np.zeros(d['temperature'].shape, dtype=np.float32), d['temperature'])
return dict(d, peak=peak, high=high, temperature=temperature)
def fix_triangular(d):
peak = tfp_hps.ensure_high_gt_low(d['low'], d['peak'])
high = tfp_hps.ensure_high_gt_low(peak, d['high'])
return dict(d, peak=peak, high=high)
def fix_truncated_normal(params):
new_params = dict(params, high=tfp_hps.ensure_high_gt_low(
params['low'], params['high']))
max_low = params['loc'] + 5 * params['scale']
min_high = params['loc'] - 5 * params['scale']
new_params['high'] = tfp_hps.ensure_high_gt_low(min_high, new_params['high'])
new_params['low'] = tfp_hps.ensure_low_lt_high(new_params['low'], max_low)
return new_params
def fix_wishart(d):
df = d['df']
scale = d.get('scale', d.get('scale_tril'))
return dict(d, df=tf.maximum(df, tf.cast(scale.shape[-1], df.dtype)))
def fix_bates(d):
total_count = tf.math.maximum(
tf.math.minimum(
d['total_count'],
tfd.bates.BATES_TOTAL_COUNT_STABILITY_LIMITS[ # pylint: disable=protected-access
d['total_count'].dtype]),
1.)
high = tfp_hps.ensure_high_gt_low(d['low'], d['high'])
return dict(d, total_count=total_count, high=high)
CONSTRAINTS = {
'atol': tf.math.softplus,
'rtol': tf.math.softplus,
'Dirichlet.concentration': tfp_hps.softplus_plus_eps(),
'concentration': tfp_hps.softplus_plus_eps(),
'GeneralizedPareto.concentration': ( # Permits +ve and -ve concentrations.
lambda x: tf.math.tanh(x) * 0.24
),
'concentration0': tfp_hps.softplus_plus_eps(),
'concentration1': tfp_hps.softplus_plus_eps(),
'concentration0_numerator': tfp_hps.softplus_plus_eps(),
'concentration1_numerator': tfp_hps.softplus_plus_eps(1.0),
'concentration0_denominator': tfp_hps.softplus_plus_eps(),
'concentration1_denominator': tfp_hps.softplus_plus_eps(1.0),
'covariance_matrix': tfp_hps.positive_definite,
'df': tfp_hps.softplus_plus_eps(),
'DeterminantalPointProcess.eigenvalues': tfp_hps.softplus_plus_eps(),
'eigenvectors': tfp_hps.orthonormal,
'InverseGaussian.loc': tfp_hps.softplus_plus_eps(),
'JohnsonSU.tailweight': tfp_hps.softplus_plus_eps(),
'PowerSpherical.mean_direction': lambda x: tf.math.l2_normalize(
tf.math.sigmoid(x) + 1e-6, -1
),
'VonMisesFisher.mean_direction': ( # max ndims is 3 to avoid instability.
lambda x: tf.math.l2_normalize(tf.math.sigmoid(x[..., :3]) + 1e-6, -1)
),
'Categorical.probs': tf.math.softmax,
'ExpRelaxedOneHotCategorical.probs': tf.math.softmax,
'RelaxedOneHotCategorical.probs': tf.math.softmax,
'FiniteDiscrete.probs': tf.math.softmax,
'Multinomial.probs': tf.math.softmax,
'OneHotCategorical.probs': tf.math.softmax,
'RelaxedCategorical.probs': tf.math.softmax,
'Zipf.power':
# Strictly > 1. See also b/175929563 (rejection sampler
# iterates too much and emits `nan` for powers too close to 1).
tfp_hps.softplus_plus_eps(1 + 1e-4),
'ContinuousBernoulli.probs': tf.sigmoid,
'Geometric.logits': # TODO(b/128410109): re-enable down to -50
# Capping at 15. so that probability is less than 1, and entropy is
# defined. b/147394924
lambda x: tf.minimum(tf.maximum(x, -16.0), 15.0), # works around the bug
'Geometric.probs': constrain_between_eps_and_one_minus_eps(),
'Binomial.probs': tf.sigmoid,
# Constrain probs away from 0 to avoid immense samples.
# See b/178842153.
'NegativeBinomial.logits': lambda x: tf.minimum(x, 15.0),
'NegativeBinomial.probs': constrain_between_eps_and_one_minus_eps(
eps0=0.0, eps1=1e-6
),
'Bernoulli.probs': tf.sigmoid,
'PlackettLuce.scores': tfp_hps.softplus_plus_eps(),
'ProbitBernoulli.probs': tf.sigmoid,
'RelaxedBernoulli.probs': tf.sigmoid,
'cutpoints':
# Permit values that aren't too large
lambda x: ascending.Ascending().forward(10 * tf.math.tanh(x)),
# Capping log_rate because of weird semantics of Poisson with very
# large rates (see b/178842153).
'log_rate': lambda x: tf.minimum(tf.maximum(x, -16.0), 15.0),
# Capping log_rate1 and log_rate2 to 15. This is because if both are large
# (meaning the rates are `inf`), then the Skellam distribution is undefined.
'log_rate1': lambda x: tf.minimum(tf.maximum(x, -16.0), 15.0),
'log_rate2': lambda x: tf.minimum(tf.maximum(x, -16.0), 15.0),
'log_scale': lambda x: tf.maximum(x, -16.0),
'mixing_concentration': tfp_hps.softplus_plus_eps(),
'mixing_rate': tfp_hps.softplus_plus_eps(),
'rate': tfp_hps.softplus_plus_eps(),
'rate1': tfp_hps.softplus_plus_eps(),
'rate2': tfp_hps.softplus_plus_eps(),
'scale': tfp_hps.softplus_plus_eps(),
'GeneralizedPareto.scale': ( # Avoid underflow in support bijector.
tfp_hps.softplus_plus_eps(1e-2)
),
'Wishart.scale': tfp_hps.positive_definite,
'scale_diag': tfp_hps.softplus_plus_eps(),
'scale_tril': tfp_hps.lower_tril_positive_definite,
'tailweight': tfp_hps.softplus_plus_eps(),
'temperature': tfp_hps.softplus_plus_eps(),
'total_count': lambda x: tf.floor(tf.sigmoid(x / 100) * 100) + 1,
'concentration_shape': tfp_hps.shapes(min_ndims=1, min_lastdimsize=2),
'Bates': fix_bates,
'Bernoulli': lambda d: dict(d, dtype=tf.float32),
'CholeskyLKJ': fix_lkj,
'LKJ': fix_lkj,
'MultivariateNormalDiagPlusLowRank.scale_diag':
# Ensure that the diagonal component is large enough to avoid being
# overwhelmed by the (singular) low-rank perturbation.
tfp_hps.softplus_plus_eps(1.0 + 1e-6),
'MultivariateNormalDiagPlusLowRank.scale_perturb_diag': (
tfp_hps.softplus_plus_eps()
),
'MultivariateNormalDiagPlusLowRank.scale_perturb_factor':
# Prevent large low-rank perturbations from creating numerically
# singular matrices.
tf.math.tanh,
'MultivariateNormalDiagPlusLowRankCovariance.cov_diag_factor':
# Ensure that the diagonal component is large enough to avoid being
# overwhelmed by the (singular) low-rank perturbation.
tfp_hps.softplus_plus_eps(1.0 + 1e-6),
'MultivariateNormalDiagPlusLowRankCovariance.cov_perturb_factor':
# Prevent large low-rank perturbations from creating numerically
# singular matrices.
tf.math.tanh,
'NormalInverseGaussian': fix_normal_inverse_gaussian,
'OrderedLogistic': lambda d: dict(d, dtype=tf.float32),
'OnehotCategorical': lambda d: dict(d, dtype=tf.float32),
'PERT': fix_pert,
'StoppingRatioLogistic': lambda d: dict(d, dtype=tf.float32),
'Triangular': fix_triangular,
'TruncatedCauchy': lambda d: dict( # pylint:disable=g-long-lambda
d, high=tfp_hps.ensure_high_gt_low(d['low'], d['high'])
),
'TruncatedNormal': fix_truncated_normal,
'Uniform': lambda d: dict( # pylint:disable=g-long-lambda
d, high=tfp_hps.ensure_high_gt_low(d['low'], d['high'])
),
'SphericalUniform': fix_spherical_uniform,
'Wishart': fix_wishart,
'WishartTriL': fix_wishart,
'Zipf': lambda d: dict(d, dtype=tf.float32),
'FiniteDiscrete': fix_finite_discrete,
'GeneralizedNormal.power': tfp_hps.softplus_plus_eps(),
'TwoPieceNormal.skewness': tfp_hps.softplus_plus_eps(),
'TwoPieceStudentT.skewness': tfp_hps.softplus_plus_eps(),
'NoncentralChi2.noncentrality': tf.math.softplus,
}
def constraint_for(dist=None, param=None):
if param is not None:
return CONSTRAINTS.get('{}.{}'.format(dist, param),
CONSTRAINTS.get(param, tfp_hps.identity_fn))
return CONSTRAINTS.get(dist, tfp_hps.identity_fn)
class DistInfo(collections.namedtuple(
'DistInfo', ['cls', 'params_event_ndims'])):
"""Sufficient information to instantiate a Distribution.
To wit
- The Python class `cls` giving the class, and
- A Python dict `params_event_ndims` giving the event dimensions for the
parameters (so that parameters can be built with predictable batch shapes).
Specifically, the `params_event_ndims` dict maps string parameter names to
Python integers. Each integer gives how many (trailing) dimensions of that
parameter are part of the event.
"""
__slots__ = ()
def _instantiable_base_dists():
"""Computes the table of mechanically instantiable base Distributions.
A Distribution is mechanically instantiable if
- The class appears as a symbol binding in `tfp.distributions`;
- The class defines a `_params_event_ndims` method (necessary
to generate parameter Tensors with predictable batch shapes); and
- The name is not blocklisted in `SPECIAL_DISTS`.
Additionally, the Empricial distribution is hardcoded with special
instantiation rules for each choice of event_ndims among 0, 1, and 2.
Compound distributions like TransformedDistribution have their own
instantiation rules hard-coded in the `distributions` strategy.
Returns:
instantiable_base_dists: A Python dict mapping distribution name
(as a string) to a `DistInfo` carrying the information necessary to
instantiate it.
"""
result = {}
for dist_name in dir(tfd):
dist_class = getattr(tfd, dist_name)
if (not inspect.isclass(dist_class) or
not issubclass(dist_class, tfd.Distribution) or
dist_name in SPECIAL_DISTS):
continue
try:
params_event_ndims = {
k: p.event_ndims
for (k, p) in dist_class.parameter_properties().items()
if p.is_tensor and p.event_ndims is not None
}
has_concrete_event_ndims = all(
isinstance(nd, int) for nd in params_event_ndims.values())
except NotImplementedError:
has_concrete_event_ndims = False
if has_concrete_event_ndims:
result[dist_name] = DistInfo(dist_class, params_event_ndims)
else:
logging.warning(
'Unable to test tfd.%s: `parameter_properties()` is not '
'implemented or does not define concrete (integer) `event_ndims` '
'for all parameters.',
dist_name)
# Empirical._params_event_ndims depends on `self.event_ndims`, so we have to
# explicitly list these entries.
result['Empirical|event_ndims=0'] = DistInfo( #
functools.partial(tfd.Empirical, event_ndims=0), dict(samples=1))
result['Empirical|event_ndims=1'] = DistInfo( #
functools.partial(tfd.Empirical, event_ndims=1), dict(samples=2))
result['Empirical|event_ndims=2'] = DistInfo( #
functools.partial(tfd.Empirical, event_ndims=2), dict(samples=3))
# We use a special strategy for instantiating this, so event_dims is set to a
# dummy value.
result['IncrementLogProb'] = DistInfo(tfed.IncrementLogProb, None)
return result
# INSTANTIABLE_BASE_DISTS is a map from str->(DistClass, params_event_ndims)
INSTANTIABLE_BASE_DISTS = _instantiable_base_dists()
del _instantiable_base_dists
def _discrete_dists():
"""Computes the table of Discrete Distributions.
Returns:
discrete_dists: A Python list of discrete distributions.
"""
result = []
for dist_name in dir(tfd):
dist_class = getattr(tfd, dist_name)
if (not inspect.isclass(dist_class) or
not issubclass(dist_class, tfd.Distribution)):
continue
if issubclass(dist_class, distribution.DiscreteDistributionMixin):
result.append(dist_name)
return result
DISCRETE_DISTS = _discrete_dists()
del _discrete_dists
INSTANTIABLE_META_DISTS = (
'BatchBroadcast',
'BatchReshape',
'Independent',
'Masked',
'Mixture',
'MixtureSameFamily',
'Sample',
'TransformedDistribution',
'QuantizedDistribution',
)
def _report_non_instantiable_meta_dists():
for dist_name in SPECIAL_DISTS:
if dist_name in ['Distribution', 'Empirical']: continue
if dist_name in INSTANTIABLE_META_DISTS: continue
msg = 'Unable to test tfd.%s: no instantiation strategy.'
logging.warning(msg, dist_name)
_report_non_instantiable_meta_dists()
del _report_non_instantiable_meta_dists
def prime_factors(v):
"""Compute the prime factors of v."""
factors = []
primes = []
factor = 2
while v > 1:
while any(factor % p == 0 for p in primes):
factor += 1
primes.append(factor)
while v % factor == 0:
factors.append(factor)
v //= factor
return factors
@hps.composite
def reshapes_of(draw, shape, max_ndims=4):
"""Strategy for valid reshapes of the given shape, rank at most max_ndims."""
factors = draw(hps.permutations(
prime_factors(tensorshape_util.num_elements(shape))))
split_points = sorted(draw(
hps.lists(hps.integers(min_value=0, max_value=len(factors)),
min_size=0, max_size=max_ndims - 1)))
result = ()
for start, stop in zip([0] + split_points, split_points + [len(factors)]):
result += (int(np.prod(factors[start:stop])),)
return result
def assert_shapes_unchanged(target_shaped_dict, possibly_bcast_dict):
for param, target_param_val in six.iteritems(target_shaped_dict):
np.testing.assert_array_equal(
tensorshape_util.as_list(target_param_val.shape),
tensorshape_util.as_list(possibly_bcast_dict[param].shape))
@hps.composite
def base_distribution_unconstrained_params(draw,
dist_name,
batch_shape=None,
event_dim=None,
enable_vars=False,
param_strategy_fn=None,
params=None):
"""Strategy for drawing unconstrained parameters of a base Distribution.
This does not draw parameters for compound distributions like `Independent`,
`MixtureSameFamily`, or `TransformedDistribution`; only base Distributions
that do not accept other Distributions as arguments.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
dist_name: Optional Python `str`. If given, the produced distributions
will all have this type.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
Distribution. Hypothesis will pick a batch shape if omitted.
event_dim: Optional Python int giving the size of each of the
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
param_strategy_fn: Optional callable with signature
`strategy = param_strategy_fn(shape, dtype, constraint_fn)`. If provided,
overrides the default strategy for generating float-valued parameters.
Default value: `None`.
params: An optional set of Distribution parameters. If params are not
provided, Hypothesis will choose a set of parameters.
Returns:
dists: A strategy for drawing Distribution parameters with the specified
`batch_shape` (or an arbitrary one if omitted).
"""
if params is not None:
assert batch_shape is not None, ('Need to pass in valid `batch_shape` when'
' passing in `params`.')
return params, batch_shape
if batch_shape is None:
batch_shape = draw(tfp_hps.shapes())
# Draw raw parameters
if dist_name not in INSTANTIABLE_BASE_DISTS:
raise ValueError('Unknown Distribution name {}'.format(dist_name))
params_event_ndims = INSTANTIABLE_BASE_DISTS[dist_name].params_event_ndims
params_kwargs = draw(
tfp_hps.broadcasting_params(
batch_shape,
params_event_ndims,
event_dim=event_dim,
enable_vars=enable_vars,
constraint_fn_for=lambda param: constraint_for(dist_name, param),
mutex_params=MUTEX_PARAMS,
param_strategy_fn=param_strategy_fn))
hp.note('Forming dist {} with raw parameters {}'.format(dist_name,
params_kwargs))
return params_kwargs, batch_shape
def constrain_params(params_unconstrained, dist_name):
"""Constrains a parameters dictionary to a distribution's parameter space."""
# Constrain them to legal values
params_constrained = constraint_for(dist_name)(params_unconstrained)
# Sometimes the "distribution constraint" fn may replace c2t-tracking
# DeferredTensor params with Tensor params (e.g. fix_triangular). In such
# cases, we preserve the c2t-tracking DeferredTensors by wrapping them but
# ignoring the value. We similarly reinstate raw tf.Variables, so they
# appear in the distribution's `variables` list and can be initialized.
for k in params_constrained:
if (k in params_unconstrained and
isinstance(params_unconstrained[k],
(tfp_util.DeferredTensor, tf.Variable))
and params_unconstrained[k] is not params_constrained[k]):
def constrained_value(v, val=params_constrained[k]): # pylint: disable=cell-var-from-loop
# While the gradient to v will be 0, we only care about the c2t
# counts.
return v * 0 + val
params_constrained[k] = tfp_util.DeferredTensor(
params_unconstrained[k], constrained_value)
assert_shapes_unchanged(params_unconstrained, params_constrained)
hp.note('Forming dist {} with constrained parameters {}'.format(
dist_name, params_constrained))
return params_constrained
def modify_params(params, dist_name, validate_args):
params = dict(params)
params['validate_args'] = validate_args
if dist_name in ['Wishart', 'WishartTriL']:
# With the default `input_output_cholesky = False`, Wishart occasionally
# produces samples for which the Cholesky decompositions fail, causing
# an error in testDistribution when `log_prob` is called on a sample.
params['input_output_cholesky'] = True
return params
@hps.composite
def base_distributions(draw,
dist_name=None,
batch_shape=None,
event_dim=None,
enable_vars=False,
eligibility_filter=lambda name: True,
params=None,
param_strategy_fn=None,
validate_args=True):
"""Strategy for drawing arbitrary base Distributions.
This does not draw compound distributions like `Independent`,
`MixtureSameFamily`, or `TransformedDistribution`; only base Distributions
that do not accept other Distributions as arguments.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
dist_name: Optional Python `str`. If given, the produced distributions
will all have this type.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
Distribution. Hypothesis will pick a batch shape if omitted.
event_dim: Optional Python int giving the size of each of the
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
eligibility_filter: Optional Python callable. Blocks some Distribution
class names so they will not be drawn at the top level.
params: An optional set of Distribution parameters. If params are not
provided, Hypothesis will choose a set of parameters.
param_strategy_fn: Optional callable with signature
`strategy = param_strategy_fn(shape, dtype, constraint_fn)`. If provided,
overrides the default strategy for generating float-valued parameters.
Default value: `None`.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing Distributions with the specified `batch_shape`
(or an arbitrary one if omitted).
"""
if dist_name is None:
names = [k for k in INSTANTIABLE_BASE_DISTS if eligibility_filter(k)]
dist_name = draw(hps.sampled_from(sorted(names)))
if dist_name == 'Empirical':
variants = [k for k in INSTANTIABLE_BASE_DISTS
if eligibility_filter(k) and 'Empirical' in k]
dist_name = draw(hps.sampled_from(sorted(variants)))
if dist_name == 'SphericalUniform':
return draw(spherical_uniforms(
batch_shape=batch_shape, event_dim=event_dim,
validate_args=validate_args))
elif dist_name == 'IncrementLogProb':
return draw(
increment_log_probs(
batch_shape=batch_shape,
enable_vars=enable_vars,
validate_args=validate_args))
elif dist_name == 'ZeroInflatedNegativeBinomial':
# We need a custom strategy for ZeroInflatedNegativeBinomial because
# it currently isn't able to handle parameters with non-identical
# batch dimensions.
return draw(
zero_inflated_negative_binomial(
batch_shape=batch_shape,
enable_vars=enable_vars,
validate_args=validate_args))
if params is None:
params_unconstrained, batch_shape = draw(
base_distribution_unconstrained_params(
dist_name,
batch_shape=batch_shape,
event_dim=event_dim,
enable_vars=enable_vars,
param_strategy_fn=param_strategy_fn))
params = constrain_params(params_unconstrained, dist_name)
params = modify_params(params, dist_name, validate_args=validate_args)
# Actually construct the distribution
dist_cls = INSTANTIABLE_BASE_DISTS[dist_name].cls
result_dist = dist_cls(**params)
# Check that the batch shape came out as expected
if batch_shape != result_dist.batch_shape:
msg = ('Distributions strategy generated a bad batch shape '
'for {}, should have been {}.').format(result_dist, batch_shape)
raise AssertionError(msg)
return result_dist
def depths():
return hps.integers(min_value=0, max_value=4)
def params_used(dist):
return [k for k, v in six.iteritems(dist.parameters) if v is not None]
@hps.composite
def spherical_uniforms(
draw, batch_shape=None, event_dim=None, validate_args=True):
"""Strategy for drawing `SphericalUniform` distributions.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`SphericalUniform` distribution.
event_dim: Optional Python int giving the size of the
distribution's event dimension.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `SphericalUniform` distributions with the
specified `batch_shape` (or an arbitrary one if omitted).
"""
if batch_shape is None:
batch_shape = draw(tfp_hps.shapes(min_ndims=0, max_side=4))
if event_dim is None:
event_dim = draw(hps.integers(min_value=1, max_value=10))
result_dist = tfd.SphericalUniform(
dimension=event_dim, batch_shape=batch_shape, validate_args=validate_args)
return result_dist
@hps.composite
def increment_log_probs(draw,
batch_shape=None,
enable_vars=False,
validate_args=True):
"""Strategy for drawing `IncrementLogProb` distributions.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`IncrementLogProb` distribution.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `IncrementLogProb` distributions with the
specified `batch_shape` (or an arbitrary one if omitted).
"""
if batch_shape is None:
batch_shape = draw(tfp_hps.shapes(min_ndims=0, max_side=4))
log_prob_value = draw(
tfp_hps.maybe_variable(
tfp_hps.constrained_tensors(tfp_hps.identity_fn,
tensorshape_util.as_list(batch_shape)),
enable_vars=enable_vars))
if draw(hps.booleans()):
return tfed.IncrementLogProb(log_prob_value, validate_args=validate_args)
else:
return tfed.IncrementLogProb(
lambda v: v,
validate_args=validate_args,
log_prob_increment_kwargs={'v': log_prob_value})
@hps.composite
def batch_broadcasts(
draw, batch_shape=None, event_dim=None,
enable_vars=False, depth=None,
eligibility_filter=lambda name: True, validate_args=True):
"""Strategy for drawing `BatchBroadcast` distributions.
The underlying distribution is drawn from the `distributions` strategy.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`BatchBroadcast` distribution. Note that the underlying distribution will
in general have a different batch shape, to make the broadcast
non-trivial. Hypothesis will pick one if omitted.
event_dim: Optional Python int giving the size of each of the underlying
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
depth: Python `int` giving maximum nesting depth of compound Distributions.
eligibility_filter: Optional Python callable. Blocks some Distribution
class names so they will not be drawn.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `BatchBroadcast` distributions with the
specified `batch_shape` (or an arbitrary one if omitted).
"""
if depth is None:
depth = draw(depths())
if batch_shape is None:
batch_shape = draw(tfp_hps.shapes(min_ndims=1, max_side=13))
arg_name = draw(hps.sampled_from(['to_shape', 'with_shape']))
underlying_batch_shape, broadcast_with = draw(
tfp_hps.broadcasting_shapes(batch_shape, 2))
if arg_name == 'to_shape':
kwargs = dict(to_shape=batch_shape)
else:
kwargs = dict(with_shape=broadcast_with)
# Cannot put a BatchReshape into a BatchBroadcast, because the former
# doesn't support broadcasting, and the latter relies on it. b/161984806.
def nested_eligibility_filter(dist_name):
if dist_name == 'BatchReshape':
return False
return eligibility_filter(dist_name)
underlying = draw(
distributions(
batch_shape=underlying_batch_shape,
event_dim=event_dim,
enable_vars=enable_vars,
depth=depth - 1,
eligibility_filter=nested_eligibility_filter,
validate_args=validate_args))
hp.note('Forming BatchBroadcast with underlying dist {}; '
'parameters {}; kwargs {}'.format(
underlying, params_used(underlying), kwargs))
result_dist = tfd.BatchBroadcast(underlying, validate_args=validate_args,
**kwargs)
return result_dist
@hps.composite
def batch_reshapes(
draw, batch_shape=None, event_dim=None,
enable_vars=False, depth=None,
eligibility_filter=lambda name: True, validate_args=True):
"""Strategy for drawing `BatchReshape` distributions.
The underlying distribution is drawn from the `distributions` strategy.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`BatchReshape` distribution. Note that the underlying distribution will
in general have a different batch shape, to make the reshaping
non-trivial. Hypothesis will pick one if omitted.
event_dim: Optional Python int giving the size of each of the underlying
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
depth: Python `int` giving maximum nesting depth of compound Distributions.
eligibility_filter: Optional Python callable. Blocks some Distribution
class names so they will not be drawn.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `BatchReshape` distributions with the
specified `batch_shape` (or an arbitrary one if omitted).
"""
if depth is None:
depth = draw(depths())
if batch_shape is None:
batch_shape = draw(tfp_hps.shapes(min_ndims=1, max_side=13))
underlying_batch_shape = draw(reshapes_of(batch_shape))
underlying = draw(
distributions(
batch_shape=underlying_batch_shape,
event_dim=event_dim,
enable_vars=enable_vars,
depth=depth - 1,
eligibility_filter=eligibility_filter,
validate_args=validate_args))
hp.note('Forming BatchReshape with underlying dist {}; '
'parameters {}; batch_shape {}'.format(
underlying, params_used(underlying), batch_shape))
result_dist = tfd.BatchReshape(
underlying, batch_shape=batch_shape, validate_args=True)
return result_dist
@hps.composite
def independents(
draw, batch_shape=None, event_dim=None,
enable_vars=False, depth=None, eligibility_filter=lambda name: True,
validate_args=True):
"""Strategy for drawing `Independent` distributions.
The underlying distribution is drawn from the `distributions` strategy.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`Independent` distribution. Note that the underlying distribution will in
general have a higher-rank batch shape, to make room for reinterpreting
some of those dimensions as the `Independent`'s event. Hypothesis will
pick one if omitted.
event_dim: Optional Python int giving the size of each of the underlying
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
depth: Python `int` giving maximum nesting depth of compound Distributions.
eligibility_filter: Optional Python callable. Blocks some Distribution
class names so they will not be drawn.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `Independent` distributions with the specified
`batch_shape` (or an arbitrary one if omitted).
"""
if depth is None:
depth = draw(depths())
reinterpreted_batch_ndims = draw(hps.integers(min_value=0, max_value=2))
if batch_shape is None:
batch_shape = draw(
tfp_hps.shapes(min_ndims=reinterpreted_batch_ndims))
else: # This independent adds some batch dims to its underlying distribution.
batch_shape = tensorshape_util.concatenate(
batch_shape,
draw(tfp_hps.shapes(
min_ndims=reinterpreted_batch_ndims,
max_ndims=reinterpreted_batch_ndims)))
underlying = draw(
distributions(
batch_shape=batch_shape,
event_dim=event_dim,
enable_vars=enable_vars,
depth=depth - 1,
eligibility_filter=eligibility_filter,
validate_args=validate_args))
hp.note('Forming Independent with underlying dist {}; '
'parameters {}; reinterpreted_batch_ndims {}'.format(
underlying, params_used(underlying), reinterpreted_batch_ndims))
result_dist = tfd.Independent(
underlying,
reinterpreted_batch_ndims=reinterpreted_batch_ndims,
validate_args=validate_args)
expected_shape = batch_shape[:len(batch_shape) - reinterpreted_batch_ndims]
if expected_shape != result_dist.batch_shape:
msg = ('Independent strategy generated a bad batch shape '
'for {}, should have been {}.').format(result_dist, expected_shape)
raise AssertionError(msg)
return result_dist
@hps.composite
def samples(
draw, batch_shape=None, event_dim=None,
enable_vars=False, depth=None, eligibility_filter=lambda name: True,
validate_args=True):
"""Strategy for drawing `Sample` distributions.
The underlying distribution is drawn from the `distributions` strategy.
Args:
draw: Hypothesis strategy sampler supplied by `@hps.composite`.
batch_shape: An optional `TensorShape`. The batch shape of the resulting
`Sample` distribution. Hypothesis will pick one if omitted.
event_dim: Optional Python int giving the size of each of the underlying
distribution's parameters' event dimensions. This is shared across all
parameters, permitting square event matrices, compatible location and
scale Tensors, etc. If omitted, Hypothesis will choose one.
enable_vars: TODO(b/181859346): Make this `True` all the time and put
variable initialization in slicing_test. If `False`, the returned
parameters are all `tf.Tensor`s and not {`tf.Variable`,
`tfp.util.DeferredTensor` `tfp.util.TransformedVariable`}
depth: Python `int` giving maximum nesting depth of compound Distributions.
eligibility_filter: Optional Python callable. Blocks some Distribution
class names so they will not be drawn.
validate_args: Python `bool`; whether to enable runtime assertions.
Returns:
dists: A strategy for drawing `Sample` distributions with the specified
`batch_shape` (or an arbitrary one if omitted).
"""
if depth is None: