forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_distributions.py
4575 lines (4149 loc) · 215 KB
/
test_distributions.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
"""
Note [Randomized statistical tests]
-----------------------------------
This note describes how to maintain tests in this file as random sources
change. This file contains two types of randomized tests:
1. The easier type of randomized test are tests that should always pass but are
initialized with random data. If these fail something is wrong, but it's
fine to use a fixed seed by inheriting from common.TestCase.
2. The trickier tests are statistical tests. These tests explicitly call
set_rng_seed(n) and are marked "see Note [Randomized statistical tests]".
These statistical tests have a known positive failure rate
(we set failure_rate=1e-3 by default). We need to balance strength of these
tests with annoyance of false alarms. One way that works is to specifically
set seeds in each of the randomized tests. When a random generator
occasionally changes (as in #4312 vectorizing the Box-Muller sampler), some
of these statistical tests may (rarely) fail. If one fails in this case,
it's fine to increment the seed of the failing test (but you shouldn't need
to increment it more than once; otherwise something is probably actually
wrong).
"""
import math
import numbers
import unittest
from collections import namedtuple
from itertools import product
from random import shuffle
import torch
from torch._six import inf
from common_utils import TestCase, run_tests, set_rng_seed, TEST_WITH_UBSAN, load_tests
from common_cuda import TEST_CUDA
from torch.autograd import grad, gradcheck
from torch.distributions import (Bernoulli, Beta, Binomial, Categorical,
Cauchy, Chi2, Dirichlet, Distribution,
Exponential, ExponentialFamily,
FisherSnedecor, Gamma, Geometric, Gumbel,
HalfCauchy, HalfNormal,
Independent, Laplace, LogisticNormal,
LogNormal, LowRankMultivariateNormal,
Multinomial, MultivariateNormal,
NegativeBinomial, Normal, OneHotCategorical, Pareto,
Poisson, RelaxedBernoulli, RelaxedOneHotCategorical,
StudentT, TransformedDistribution, Uniform,
Weibull, constraints, kl_divergence)
from torch.distributions.constraint_registry import biject_to, transform_to
from torch.distributions.constraints import Constraint, is_dependent
from torch.distributions.dirichlet import _Dirichlet_backward
from torch.distributions.kl import _kl_expfamily_expfamily
from torch.distributions.transforms import (AbsTransform, AffineTransform,
CatTransform, ComposeTransform, ExpTransform,
LowerCholeskyTransform,
PowerTransform, SigmoidTransform,
SoftmaxTransform,
StickBreakingTransform,
identity_transform, StackTransform)
from torch.distributions.utils import probs_to_logits, lazy_property
from torch.nn.functional import softmax
# load_tests from common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
TEST_NUMPY = True
try:
import numpy as np
import scipy.stats
import scipy.special
except ImportError:
TEST_NUMPY = False
def pairwise(Dist, *params):
"""
Creates a pair of distributions `Dist` initialzed to test each element of
param with each other.
"""
params1 = [torch.tensor([p] * len(p)) for p in params]
params2 = [p.transpose(0, 1) for p in params1]
return Dist(*params1), Dist(*params2)
def is_all_nan(tensor):
"""
Checks if all entries of a tensor is nan.
"""
return (tensor != tensor).all()
# Register all distributions for generic tests.
Example = namedtuple('Example', ['Dist', 'params'])
EXAMPLES = [
Example(Bernoulli, [
{'probs': torch.tensor([0.7, 0.2, 0.4], requires_grad=True)},
{'probs': torch.tensor([0.3], requires_grad=True)},
{'probs': 0.3},
{'logits': torch.tensor([0.], requires_grad=True)},
]),
Example(Geometric, [
{'probs': torch.tensor([0.7, 0.2, 0.4], requires_grad=True)},
{'probs': torch.tensor([0.3], requires_grad=True)},
{'probs': 0.3},
]),
Example(Beta, [
{
'concentration1': torch.randn(2, 3).exp().requires_grad_(),
'concentration0': torch.randn(2, 3).exp().requires_grad_(),
},
{
'concentration1': torch.randn(4).exp().requires_grad_(),
'concentration0': torch.randn(4).exp().requires_grad_(),
},
]),
Example(Categorical, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True)},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True)},
{'logits': torch.tensor([[0.0, 0.0], [0.0, 0.0]], requires_grad=True)},
]),
Example(Binomial, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True), 'total_count': 10},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True), 'total_count': 10},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True), 'total_count': torch.tensor([10])},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True), 'total_count': torch.tensor([10, 8])},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True),
'total_count': torch.tensor([[10., 8.], [5., 3.]])},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True),
'total_count': torch.tensor(0.)},
]),
Example(NegativeBinomial, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True), 'total_count': 10},
{'probs': torch.tensor([[0.9, 0.0], [0.0, 0.9]], requires_grad=True), 'total_count': 10},
{'probs': torch.tensor([[0.9, 0.0], [0.0, 0.9]], requires_grad=True), 'total_count': torch.tensor([10])},
{'probs': torch.tensor([[0.9, 0.0], [0.0, 0.9]], requires_grad=True), 'total_count': torch.tensor([10, 8])},
{'probs': torch.tensor([[0.9, 0.0], [0.0, 0.9]], requires_grad=True),
'total_count': torch.tensor([[10., 8.], [5., 3.]])},
{'probs': torch.tensor([[0.9, 0.0], [0.0, 0.9]], requires_grad=True),
'total_count': torch.tensor(0.)},
]),
Example(Multinomial, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True), 'total_count': 10},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True), 'total_count': 10},
]),
Example(Cauchy, [
{'loc': 0.0, 'scale': 1.0},
{'loc': torch.tensor([0.0]), 'scale': 1.0},
{'loc': torch.tensor([[0.0], [0.0]]),
'scale': torch.tensor([[1.0], [1.0]])}
]),
Example(Chi2, [
{'df': torch.randn(2, 3).exp().requires_grad_()},
{'df': torch.randn(1).exp().requires_grad_()},
]),
Example(StudentT, [
{'df': torch.randn(2, 3).exp().requires_grad_()},
{'df': torch.randn(1).exp().requires_grad_()},
]),
Example(Dirichlet, [
{'concentration': torch.randn(2, 3).exp().requires_grad_()},
{'concentration': torch.randn(4).exp().requires_grad_()},
]),
Example(Exponential, [
{'rate': torch.randn(5, 5).abs().requires_grad_()},
{'rate': torch.randn(1).abs().requires_grad_()},
]),
Example(FisherSnedecor, [
{
'df1': torch.randn(5, 5).abs().requires_grad_(),
'df2': torch.randn(5, 5).abs().requires_grad_(),
},
{
'df1': torch.randn(1).abs().requires_grad_(),
'df2': torch.randn(1).abs().requires_grad_(),
},
{
'df1': torch.tensor([1.0]),
'df2': 1.0,
}
]),
Example(Gamma, [
{
'concentration': torch.randn(2, 3).exp().requires_grad_(),
'rate': torch.randn(2, 3).exp().requires_grad_(),
},
{
'concentration': torch.randn(1).exp().requires_grad_(),
'rate': torch.randn(1).exp().requires_grad_(),
},
]),
Example(Gumbel, [
{
'loc': torch.randn(5, 5, requires_grad=True),
'scale': torch.randn(5, 5).abs().requires_grad_(),
},
{
'loc': torch.randn(1, requires_grad=True),
'scale': torch.randn(1).abs().requires_grad_(),
},
]),
Example(HalfCauchy, [
{'scale': 1.0},
{'scale': torch.tensor([[1.0], [1.0]])}
]),
Example(HalfNormal, [
{'scale': torch.randn(5, 5).abs().requires_grad_()},
{'scale': torch.randn(1).abs().requires_grad_()},
{'scale': torch.tensor([1e-5, 1e-5], requires_grad=True)}
]),
Example(Independent, [
{
'base_distribution': Normal(torch.randn(2, 3, requires_grad=True),
torch.randn(2, 3).abs().requires_grad_()),
'reinterpreted_batch_ndims': 0,
},
{
'base_distribution': Normal(torch.randn(2, 3, requires_grad=True),
torch.randn(2, 3).abs().requires_grad_()),
'reinterpreted_batch_ndims': 1,
},
{
'base_distribution': Normal(torch.randn(2, 3, requires_grad=True),
torch.randn(2, 3).abs().requires_grad_()),
'reinterpreted_batch_ndims': 2,
},
{
'base_distribution': Normal(torch.randn(2, 3, 5, requires_grad=True),
torch.randn(2, 3, 5).abs().requires_grad_()),
'reinterpreted_batch_ndims': 2,
},
{
'base_distribution': Normal(torch.randn(2, 3, 5, requires_grad=True),
torch.randn(2, 3, 5).abs().requires_grad_()),
'reinterpreted_batch_ndims': 3,
},
]),
Example(Laplace, [
{
'loc': torch.randn(5, 5, requires_grad=True),
'scale': torch.randn(5, 5).abs().requires_grad_(),
},
{
'loc': torch.randn(1, requires_grad=True),
'scale': torch.randn(1).abs().requires_grad_(),
},
{
'loc': torch.tensor([1.0, 0.0], requires_grad=True),
'scale': torch.tensor([1e-5, 1e-5], requires_grad=True),
},
]),
Example(LogNormal, [
{
'loc': torch.randn(5, 5, requires_grad=True),
'scale': torch.randn(5, 5).abs().requires_grad_(),
},
{
'loc': torch.randn(1, requires_grad=True),
'scale': torch.randn(1).abs().requires_grad_(),
},
{
'loc': torch.tensor([1.0, 0.0], requires_grad=True),
'scale': torch.tensor([1e-5, 1e-5], requires_grad=True),
},
]),
Example(LogisticNormal, [
{
'loc': torch.randn(5, 5).requires_grad_(),
'scale': torch.randn(5, 5).abs().requires_grad_(),
},
{
'loc': torch.randn(1).requires_grad_(),
'scale': torch.randn(1).abs().requires_grad_(),
},
{
'loc': torch.tensor([1.0, 0.0], requires_grad=True),
'scale': torch.tensor([1e-5, 1e-5], requires_grad=True),
},
]),
Example(LowRankMultivariateNormal, [
{
'loc': torch.randn(5, 2, requires_grad=True),
'cov_factor': torch.randn(5, 2, 1, requires_grad=True),
'cov_diag': torch.tensor([2.0, 0.25], requires_grad=True),
},
{
'loc': torch.randn(4, 3, requires_grad=True),
'cov_factor': torch.randn(3, 2, requires_grad=True),
'cov_diag': torch.tensor([5.0, 1.5, 3.], requires_grad=True),
}
]),
Example(MultivariateNormal, [
{
'loc': torch.randn(5, 2, requires_grad=True),
'covariance_matrix': torch.tensor([[2.0, 0.3], [0.3, 0.25]], requires_grad=True),
},
{
'loc': torch.randn(2, 3, requires_grad=True),
'precision_matrix': torch.tensor([[2.0, 0.1, 0.0],
[0.1, 0.25, 0.0],
[0.0, 0.0, 0.3]], requires_grad=True),
},
{
'loc': torch.randn(5, 3, 2, requires_grad=True),
'scale_tril': torch.tensor([[[2.0, 0.0], [-0.5, 0.25]],
[[2.0, 0.0], [0.3, 0.25]],
[[5.0, 0.0], [-0.5, 1.5]]], requires_grad=True),
},
{
'loc': torch.tensor([1.0, -1.0]),
'covariance_matrix': torch.tensor([[5.0, -0.5], [-0.5, 1.5]]),
},
]),
Example(Normal, [
{
'loc': torch.randn(5, 5, requires_grad=True),
'scale': torch.randn(5, 5).abs().requires_grad_(),
},
{
'loc': torch.randn(1, requires_grad=True),
'scale': torch.randn(1).abs().requires_grad_(),
},
{
'loc': torch.tensor([1.0, 0.0], requires_grad=True),
'scale': torch.tensor([1e-5, 1e-5], requires_grad=True),
},
]),
Example(OneHotCategorical, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True)},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]], requires_grad=True)},
{'logits': torch.tensor([[0.0, 0.0], [0.0, 0.0]], requires_grad=True)},
]),
Example(Pareto, [
{
'scale': 1.0,
'alpha': 1.0
},
{
'scale': torch.randn(5, 5).abs().requires_grad_(),
'alpha': torch.randn(5, 5).abs().requires_grad_()
},
{
'scale': torch.tensor([1.0]),
'alpha': 1.0
}
]),
Example(Poisson, [
{
'rate': torch.randn(5, 5).abs().requires_grad_(),
},
{
'rate': torch.randn(3).abs().requires_grad_(),
},
{
'rate': 0.2,
}
]),
Example(RelaxedBernoulli, [
{
'temperature': torch.tensor([0.5], requires_grad=True),
'probs': torch.tensor([0.7, 0.2, 0.4], requires_grad=True),
},
{
'temperature': torch.tensor([2.0]),
'probs': torch.tensor([0.3]),
},
{
'temperature': torch.tensor([7.2]),
'logits': torch.tensor([-2.0, 2.0, 1.0, 5.0])
}
]),
Example(RelaxedOneHotCategorical, [
{
'temperature': torch.tensor([0.5], requires_grad=True),
'probs': torch.tensor([[0.1, 0.2, 0.7], [0.5, 0.3, 0.2]], requires_grad=True)
},
{
'temperature': torch.tensor([2.0]),
'probs': torch.tensor([[1.0, 0.0], [0.0, 1.0]])
},
{
'temperature': torch.tensor([7.2]),
'logits': torch.tensor([[-2.0, 2.0], [1.0, 5.0]])
}
]),
Example(TransformedDistribution, [
{
'base_distribution': Normal(torch.randn(2, 3, requires_grad=True),
torch.randn(2, 3).abs().requires_grad_()),
'transforms': [],
},
{
'base_distribution': Normal(torch.randn(2, 3, requires_grad=True),
torch.randn(2, 3).abs().requires_grad_()),
'transforms': ExpTransform(),
},
{
'base_distribution': Normal(torch.randn(2, 3, 5, requires_grad=True),
torch.randn(2, 3, 5).abs().requires_grad_()),
'transforms': [AffineTransform(torch.randn(3, 5), torch.randn(3, 5)),
ExpTransform()],
},
{
'base_distribution': Normal(torch.randn(2, 3, 5, requires_grad=True),
torch.randn(2, 3, 5).abs().requires_grad_()),
'transforms': AffineTransform(1, 2),
},
]),
Example(Uniform, [
{
'low': torch.zeros(5, 5, requires_grad=True),
'high': torch.ones(5, 5, requires_grad=True),
},
{
'low': torch.zeros(1, requires_grad=True),
'high': torch.ones(1, requires_grad=True),
},
{
'low': torch.tensor([1.0, 1.0], requires_grad=True),
'high': torch.tensor([2.0, 3.0], requires_grad=True),
},
]),
Example(Weibull, [
{
'scale': torch.randn(5, 5).abs().requires_grad_(),
'concentration': torch.randn(1).abs().requires_grad_()
}
])
]
BAD_EXAMPLES = [
Example(Bernoulli, [
{'probs': torch.tensor([1.1, 0.2, 0.4], requires_grad=True)},
{'probs': torch.tensor([-0.5], requires_grad=True)},
{'probs': 1.00001},
]),
Example(Beta, [
{
'concentration1': torch.tensor([0.0], requires_grad=True),
'concentration0': torch.tensor([0.0], requires_grad=True),
},
{
'concentration1': torch.tensor([-1.0], requires_grad=True),
'concentration0': torch.tensor([-2.0], requires_grad=True),
},
]),
Example(Geometric, [
{'probs': torch.tensor([1.1, 0.2, 0.4], requires_grad=True)},
{'probs': torch.tensor([-0.3], requires_grad=True)},
{'probs': 1.00000001},
]),
Example(Categorical, [
{'probs': torch.tensor([[-0.1, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True)},
{'probs': torch.tensor([[-1.0, 10.0], [0.0, -1.0]], requires_grad=True)},
]),
Example(Binomial, [
{'probs': torch.tensor([[-0.0000001, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True),
'total_count': 10},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 2.0]], requires_grad=True),
'total_count': 10},
]),
Example(NegativeBinomial, [
{'probs': torch.tensor([[-0.0000001, 0.2, 0.3], [0.5, 0.3, 0.2]], requires_grad=True),
'total_count': 10},
{'probs': torch.tensor([[1.0, 0.0], [0.0, 2.0]], requires_grad=True),
'total_count': 10},
]),
Example(Cauchy, [
{'loc': 0.0, 'scale': -1.0},
{'loc': torch.tensor([0.0]), 'scale': 0.0},
{'loc': torch.tensor([[0.0], [-2.0]]),
'scale': torch.tensor([[-0.000001], [1.0]])}
]),
Example(Chi2, [
{'df': torch.tensor([0.], requires_grad=True)},
{'df': torch.tensor([-2.], requires_grad=True)},
]),
Example(StudentT, [
{'df': torch.tensor([0.], requires_grad=True)},
{'df': torch.tensor([-2.], requires_grad=True)},
]),
Example(Dirichlet, [
{'concentration': torch.tensor([0.], requires_grad=True)},
{'concentration': torch.tensor([-2.], requires_grad=True)}
]),
Example(Exponential, [
{'rate': torch.tensor([0., 0.], requires_grad=True)},
{'rate': torch.tensor([-2.], requires_grad=True)}
]),
Example(FisherSnedecor, [
{
'df1': torch.tensor([0., 0.], requires_grad=True),
'df2': torch.tensor([-1., -100.], requires_grad=True),
},
{
'df1': torch.tensor([1., 1.], requires_grad=True),
'df2': torch.tensor([0., 0.], requires_grad=True),
}
]),
Example(Gamma, [
{
'concentration': torch.tensor([0., 0.], requires_grad=True),
'rate': torch.tensor([-1., -100.], requires_grad=True),
},
{
'concentration': torch.tensor([1., 1.], requires_grad=True),
'rate': torch.tensor([0., 0.], requires_grad=True),
}
]),
Example(Gumbel, [
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([0., 1.], requires_grad=True),
},
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([1., -1.], requires_grad=True),
},
]),
Example(HalfCauchy, [
{'scale': -1.0},
{'scale': 0.0},
{'scale': torch.tensor([[-0.000001], [1.0]])}
]),
Example(HalfNormal, [
{'scale': torch.tensor([0., 1.], requires_grad=True)},
{'scale': torch.tensor([1., -1.], requires_grad=True)},
]),
Example(Laplace, [
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([0., 1.], requires_grad=True),
},
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([1., -1.], requires_grad=True),
},
]),
Example(LogNormal, [
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([0., 1.], requires_grad=True),
},
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([1., -1.], requires_grad=True),
},
]),
Example(MultivariateNormal, [
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'covariance_matrix': torch.tensor([[1.0, 0.0], [0.0, -2.0]], requires_grad=True),
},
]),
Example(Normal, [
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([0., 1.], requires_grad=True),
},
{
'loc': torch.tensor([1., 1.], requires_grad=True),
'scale': torch.tensor([1., -1.], requires_grad=True),
},
{
'loc': torch.tensor([1.0, 0.0], requires_grad=True),
'scale': torch.tensor([1e-5, -1e-5], requires_grad=True),
},
]),
Example(OneHotCategorical, [
{'probs': torch.tensor([[0.1, 0.2, 0.3], [0.1, -10.0, 0.2]], requires_grad=True)},
{'probs': torch.tensor([[0.0, 0.0], [0.0, 0.0]], requires_grad=True)},
]),
Example(Pareto, [
{
'scale': 0.0,
'alpha': 0.0
},
{
'scale': torch.tensor([0.0, 0.0], requires_grad=True),
'alpha': torch.tensor([-1e-5, 0.0], requires_grad=True)
},
{
'scale': torch.tensor([1.0]),
'alpha': -1.0
}
]),
Example(Poisson, [
{
'rate': torch.tensor([0.0], requires_grad=True),
},
{
'rate': -1.0,
}
]),
Example(RelaxedBernoulli, [
{
'temperature': torch.tensor([1.5], requires_grad=True),
'probs': torch.tensor([1.7, 0.2, 0.4], requires_grad=True),
},
{
'temperature': torch.tensor([2.0]),
'probs': torch.tensor([-1.0]),
}
]),
Example(RelaxedOneHotCategorical, [
{
'temperature': torch.tensor([0.5], requires_grad=True),
'probs': torch.tensor([[-0.1, 0.2, 0.7], [0.5, 0.3, 0.2]], requires_grad=True)
},
{
'temperature': torch.tensor([2.0]),
'probs': torch.tensor([[-1.0, 0.0], [-1.0, 1.1]])
}
]),
Example(TransformedDistribution, [
{
'base_distribution': Normal(0, 1),
'transforms': lambda x: x,
},
{
'base_distribution': Normal(0, 1),
'transforms': [lambda x: x],
},
]),
Example(Uniform, [
{
'low': torch.tensor([2.0], requires_grad=True),
'high': torch.tensor([2.0], requires_grad=True),
},
{
'low': torch.tensor([0.0], requires_grad=True),
'high': torch.tensor([0.0], requires_grad=True),
},
{
'low': torch.tensor([1.0], requires_grad=True),
'high': torch.tensor([0.0], requires_grad=True),
}
]),
Example(Weibull, [
{
'scale': torch.tensor([0.0], requires_grad=True),
'concentration': torch.tensor([0.0], requires_grad=True)
},
{
'scale': torch.tensor([1.0], requires_grad=True),
'concentration': torch.tensor([-1.0], requires_grad=True)
}
])
]
class TestDistributions(TestCase):
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = False
def _gradcheck_log_prob(self, dist_ctor, ctor_params):
# performs gradient checks on log_prob
distribution = dist_ctor(*ctor_params)
s = distribution.sample()
if s.is_floating_point():
s = s.detach().requires_grad_()
expected_shape = distribution.batch_shape + distribution.event_shape
self.assertEqual(s.size(), expected_shape)
def apply_fn(s, *params):
return dist_ctor(*params).log_prob(s)
gradcheck(apply_fn, (s,) + tuple(ctor_params), raise_exception=True)
def _check_log_prob(self, dist, asset_fn):
# checks that the log_prob matches a reference function
s = dist.sample()
log_probs = dist.log_prob(s)
log_probs_data_flat = log_probs.view(-1)
s_data_flat = s.view(len(log_probs_data_flat), -1)
for i, (val, log_prob) in enumerate(zip(s_data_flat, log_probs_data_flat)):
asset_fn(i, val.squeeze(), log_prob)
def _check_sampler_sampler(self, torch_dist, ref_dist, message, multivariate=False,
num_samples=10000, failure_rate=1e-3):
# Checks that the .sample() method matches a reference function.
torch_samples = torch_dist.sample((num_samples,)).squeeze()
torch_samples = torch_samples.cpu().numpy()
ref_samples = ref_dist.rvs(num_samples).astype(np.float64)
if multivariate:
# Project onto a random axis.
axis = np.random.normal(size=torch_samples.shape[-1])
axis /= np.linalg.norm(axis)
torch_samples = np.dot(torch_samples, axis)
ref_samples = np.dot(ref_samples, axis)
samples = [(x, +1) for x in torch_samples] + [(x, -1) for x in ref_samples]
shuffle(samples) # necessary to prevent stable sort from making uneven bins for discrete
samples.sort(key=lambda x: x[0])
samples = np.array(samples)[:, 1]
# Aggregate into bins filled with roughly zero-mean unit-variance RVs.
num_bins = 10
samples_per_bin = len(samples) // num_bins
bins = samples.reshape((num_bins, samples_per_bin)).mean(axis=1)
stddev = samples_per_bin ** -0.5
threshold = stddev * scipy.special.erfinv(1 - 2 * failure_rate / num_bins)
message = '{}.sample() is biased:\n{}'.format(message, bins)
for bias in bins:
self.assertLess(-threshold, bias, message)
self.assertLess(bias, threshold, message)
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def _check_sampler_discrete(self, torch_dist, ref_dist, message,
num_samples=10000, failure_rate=1e-3):
"""Runs a Chi2-test for the support, but ignores tail instead of combining"""
torch_samples = torch_dist.sample((num_samples,)).squeeze()
torch_samples = torch_samples.cpu().numpy()
unique, counts = np.unique(torch_samples, return_counts=True)
pmf = ref_dist.pmf(unique)
msk = (counts > 5) & ((pmf * num_samples) > 5)
self.assertGreater(pmf[msk].sum(), 0.9, "Distribution is too sparse for test; try increasing num_samples")
chisq, p = scipy.stats.chisquare(counts[msk], pmf[msk] * num_samples)
self.assertGreater(p, failure_rate, message)
def _check_enumerate_support(self, dist, examples):
for params, expected in examples:
params = {k: torch.tensor(v) for k, v in params.items()}
expected = torch.tensor(expected)
d = dist(**params)
actual = d.enumerate_support(expand=False)
self.assertEqual(actual, expected)
actual = d.enumerate_support(expand=True)
expected_with_expand = expected.expand((-1,) + d.batch_shape + d.event_shape)
self.assertEqual(actual, expected_with_expand)
def test_repr(self):
for Dist, params in EXAMPLES:
for param in params:
dist = Dist(**param)
self.assertTrue(repr(dist).startswith(dist.__class__.__name__))
def test_sample_detached(self):
for Dist, params in EXAMPLES:
for i, param in enumerate(params):
variable_params = [p for p in param.values() if getattr(p, 'requires_grad', False)]
if not variable_params:
continue
dist = Dist(**param)
sample = dist.sample()
self.assertFalse(sample.requires_grad,
msg='{} example {}/{}, .sample() is not detached'.format(
Dist.__name__, i + 1, len(params)))
def test_rsample_requires_grad(self):
for Dist, params in EXAMPLES:
for i, param in enumerate(params):
if not any(getattr(p, 'requires_grad', False) for p in param.values()):
continue
dist = Dist(**param)
if not dist.has_rsample:
continue
sample = dist.rsample()
self.assertTrue(sample.requires_grad,
msg='{} example {}/{}, .rsample() does not require grad'.format(
Dist.__name__, i + 1, len(params)))
def test_enumerate_support_type(self):
for Dist, params in EXAMPLES:
for i, param in enumerate(params):
dist = Dist(**param)
try:
self.assertTrue(type(dist.sample()) is type(dist.enumerate_support()),
msg=('{} example {}/{}, return type mismatch between ' +
'sample and enumerate_support.').format(Dist.__name__, i + 1, len(params)))
except NotImplementedError:
pass
def test_lazy_property_grad(self):
x = torch.randn(1, requires_grad=True)
class Dummy(object):
@lazy_property
def y(self):
return x + 1
def test():
x.grad = None
Dummy().y.backward()
self.assertEqual(x.grad, torch.ones(1))
test()
with torch.no_grad():
test()
mean = torch.randn(2)
cov = torch.eye(2, requires_grad=True)
distn = MultivariateNormal(mean, cov)
with torch.no_grad():
distn.scale_tril
distn.scale_tril.sum().backward()
self.assertIsNotNone(cov.grad)
def test_has_examples(self):
distributions_with_examples = {e.Dist for e in EXAMPLES}
for Dist in globals().values():
if isinstance(Dist, type) and issubclass(Dist, Distribution) \
and Dist is not Distribution and Dist is not ExponentialFamily:
self.assertIn(Dist, distributions_with_examples,
"Please add {} to the EXAMPLES list in test_distributions.py".format(Dist.__name__))
def test_distribution_expand(self):
shapes = [torch.Size(), torch.Size((2,)), torch.Size((2, 1))]
for Dist, params in EXAMPLES:
for param in params:
for shape in shapes:
d = Dist(**param)
expanded_shape = shape + d.batch_shape
original_shape = d.batch_shape + d.event_shape
expected_shape = shape + original_shape
expanded = d.expand(batch_shape=list(expanded_shape))
sample = expanded.sample()
actual_shape = expanded.sample().shape
self.assertEqual(expanded.__class__, d.__class__)
self.assertEqual(d.sample().shape, original_shape)
self.assertEqual(expanded.log_prob(sample), d.log_prob(sample))
self.assertEqual(actual_shape, expected_shape)
self.assertEqual(expanded.batch_shape, expanded_shape)
try:
self.assertEqual(expanded.mean,
d.mean.expand(expanded_shape + d.event_shape),
allow_inf=True)
self.assertEqual(expanded.variance,
d.variance.expand(expanded_shape + d.event_shape),
allow_inf=True)
except NotImplementedError:
pass
def test_distribution_subclass_expand(self):
expand_by = torch.Size((2,))
for Dist, params in EXAMPLES:
class SubClass(Dist):
pass
for param in params:
d = SubClass(**param)
expanded_shape = expand_by + d.batch_shape
original_shape = d.batch_shape + d.event_shape
expected_shape = expand_by + original_shape
expanded = d.expand(batch_shape=expanded_shape)
sample = expanded.sample()
actual_shape = expanded.sample().shape
self.assertEqual(expanded.__class__, d.__class__)
self.assertEqual(d.sample().shape, original_shape)
self.assertEqual(expanded.log_prob(sample), d.log_prob(sample))
self.assertEqual(actual_shape, expected_shape)
def test_bernoulli(self):
p = torch.tensor([0.7, 0.2, 0.4], requires_grad=True)
r = torch.tensor(0.3, requires_grad=True)
s = 0.3
self.assertEqual(Bernoulli(p).sample((8,)).size(), (8, 3))
self.assertFalse(Bernoulli(p).sample().requires_grad)
self.assertEqual(Bernoulli(r).sample((8,)).size(), (8,))
self.assertEqual(Bernoulli(r).sample().size(), ())
self.assertEqual(Bernoulli(r).sample((3, 2)).size(), (3, 2,))
self.assertEqual(Bernoulli(s).sample().size(), ())
self._gradcheck_log_prob(Bernoulli, (p,))
def ref_log_prob(idx, val, log_prob):
prob = p[idx]
self.assertEqual(log_prob, math.log(prob if val else 1 - prob))
self._check_log_prob(Bernoulli(p), ref_log_prob)
self._check_log_prob(Bernoulli(logits=p.log() - (-p).log1p()), ref_log_prob)
self.assertRaises(NotImplementedError, Bernoulli(r).rsample)
# check entropy computation
self.assertEqual(Bernoulli(p).entropy(), torch.tensor([0.6108, 0.5004, 0.6730]), prec=1e-4)
self.assertEqual(Bernoulli(torch.tensor([0.0])).entropy(), torch.tensor([0.0]))
self.assertEqual(Bernoulli(s).entropy(), torch.tensor(0.6108), prec=1e-4)
def test_bernoulli_enumerate_support(self):
examples = [
({"probs": [0.1]}, [[0], [1]]),
({"probs": [0.1, 0.9]}, [[0], [1]]),
({"probs": [[0.1, 0.2], [0.3, 0.4]]}, [[[0]], [[1]]]),
]
self._check_enumerate_support(Bernoulli, examples)
def test_bernoulli_3d(self):
p = torch.full((2, 3, 5), 0.5).requires_grad_()
self.assertEqual(Bernoulli(p).sample().size(), (2, 3, 5))
self.assertEqual(Bernoulli(p).sample(sample_shape=(2, 5)).size(),
(2, 5, 2, 3, 5))
self.assertEqual(Bernoulli(p).sample((2,)).size(), (2, 2, 3, 5))
def test_geometric(self):
p = torch.tensor([0.7, 0.2, 0.4], requires_grad=True)
r = torch.tensor(0.3, requires_grad=True)
s = 0.3
self.assertEqual(Geometric(p).sample((8,)).size(), (8, 3))
self.assertEqual(Geometric(1).sample(), 0)
self.assertEqual(Geometric(1).log_prob(torch.tensor(1.)), -inf, allow_inf=True)
self.assertEqual(Geometric(1).log_prob(torch.tensor(0.)), 0)
self.assertFalse(Geometric(p).sample().requires_grad)
self.assertEqual(Geometric(r).sample((8,)).size(), (8,))
self.assertEqual(Geometric(r).sample().size(), ())
self.assertEqual(Geometric(r).sample((3, 2)).size(), (3, 2))
self.assertEqual(Geometric(s).sample().size(), ())
self._gradcheck_log_prob(Geometric, (p,))
self.assertRaises(ValueError, lambda: Geometric(0))
self.assertRaises(NotImplementedError, Geometric(r).rsample)
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def test_geometric_log_prob_and_entropy(self):
p = torch.tensor([0.7, 0.2, 0.4], requires_grad=True)
s = 0.3
def ref_log_prob(idx, val, log_prob):
prob = p[idx].detach()
self.assertEqual(log_prob, scipy.stats.geom(prob, loc=-1).logpmf(val))
self._check_log_prob(Geometric(p), ref_log_prob)
self._check_log_prob(Geometric(logits=p.log() - (-p).log1p()), ref_log_prob)
# check entropy computation
self.assertEqual(Geometric(p).entropy(), scipy.stats.geom(p.detach().numpy(), loc=-1).entropy(), prec=1e-3)
self.assertEqual(float(Geometric(s).entropy()), scipy.stats.geom(s, loc=-1).entropy().item(), prec=1e-3)
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def test_geometric_sample(self):
set_rng_seed(0) # see Note [Randomized statistical tests]
for prob in [0.01, 0.18, 0.8]:
self._check_sampler_discrete(Geometric(prob),
scipy.stats.geom(p=prob, loc=-1),
'Geometric(prob={})'.format(prob))
def test_binomial(self):
p = torch.arange(0.05, 1, 0.1).requires_grad_()
for total_count in [1, 2, 10]:
self._gradcheck_log_prob(lambda p: Binomial(total_count, p), [p])
self._gradcheck_log_prob(lambda p: Binomial(total_count, None, p.log()), [p])
self.assertRaises(NotImplementedError, Binomial(10, p).rsample)
self.assertRaises(NotImplementedError, Binomial(10, p).entropy)
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def test_binomial_log_prob(self):
probs = torch.arange(0.05, 1, 0.1)
for total_count in [1, 2, 10]:
def ref_log_prob(idx, x, log_prob):
p = probs.view(-1)[idx].item()
expected = scipy.stats.binom(total_count, p).logpmf(x)
self.assertAlmostEqual(log_prob, expected, places=3)
self._check_log_prob(Binomial(total_count, probs), ref_log_prob)
logits = probs_to_logits(probs, is_binary=True)
self._check_log_prob(Binomial(total_count, logits=logits), ref_log_prob)
def test_binomial_stable(self):
logits = torch.tensor([-100., 100.], dtype=torch.float)
total_count = 1.
x = torch.tensor([0., 0.], dtype=torch.float)
log_prob = Binomial(total_count, logits=logits).log_prob(x)
self.assertTrue(torch.isfinite(log_prob).all())
# make sure that the grad at logits=0, value=0 is 0.5
x = torch.tensor(0., requires_grad=True)
y = Binomial(total_count, logits=x).log_prob(torch.tensor(0.))
self.assertEqual(grad(y, x)[0], torch.tensor(-0.5))
@unittest.skipIf(not TEST_NUMPY, "NumPy not found")
def test_binomial_log_prob_vectorized_count(self):
probs = torch.tensor([0.2, 0.7, 0.9])
for total_count, sample in [(torch.tensor([10]), torch.tensor([7., 3., 9.])),
(torch.tensor([1, 2, 10]), torch.tensor([0., 1., 9.]))]:
log_prob = Binomial(total_count, probs).log_prob(sample)
expected = scipy.stats.binom(total_count.cpu().numpy(), probs.cpu().numpy()).logpmf(sample)
self.assertAlmostEqual(log_prob, expected, places=4)
def test_binomial_enumerate_support(self):
examples = [
({"probs": [0.1], "total_count": 2}, [[0], [1], [2]]),
({"probs": [0.1, 0.9], "total_count": 2}, [[0], [1], [2]]),
({"probs": [[0.1, 0.2], [0.3, 0.4]], "total_count": 3}, [[[0]], [[1]], [[2]], [[3]]]),
]
self._check_enumerate_support(Binomial, examples)
def test_binomial_extreme_vals(self):
total_count = 100
bin0 = Binomial(total_count, 0)
self.assertEqual(bin0.sample(), 0)
self.assertAlmostEqual(bin0.log_prob(torch.tensor([0.]))[0], 0, places=3)
self.assertEqual(float(bin0.log_prob(torch.tensor([1.])).exp()), 0, allow_inf=True)
bin1 = Binomial(total_count, 1)
self.assertEqual(bin1.sample(), total_count)
self.assertAlmostEqual(bin1.log_prob(torch.tensor([float(total_count)]))[0], 0, places=3)
self.assertEqual(float(bin1.log_prob(torch.tensor([float(total_count - 1)])).exp()), 0, allow_inf=True)
zero_counts = torch.zeros(torch.Size((2, 2)))
bin2 = Binomial(zero_counts, 1)
self.assertEqual(bin2.sample(), zero_counts)
self.assertEqual(bin2.log_prob(zero_counts), zero_counts)