-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_torch.py
12994 lines (11133 loc) · 556 KB
/
test_torch.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
import sys
import io
import os
import math
import random
import re
import copy
import shutil
import torch
import torch.cuda
import torch.backends.cuda
import tempfile
import unittest
import warnings
import pickle
import gzip
import types
import textwrap
import zipfile
from torch._utils_internal import get_file_path_2
from torch.utils.dlpack import from_dlpack, to_dlpack
from torch._utils import _rebuild_tensor
from torch._six import inf, nan, string_classes, istuple
from itertools import product, combinations, combinations_with_replacement, permutations
from functools import reduce
from random import randrange
from torch import multiprocessing as mp
from common_methods_invocations import tri_tests_args, run_additional_tri_tests, \
_compare_trilu_indices
from common_utils import TestCase, iter_indices, TEST_NUMPY, TEST_SCIPY, TEST_MKL, \
TEST_LIBROSA, run_tests, download_file, skipIfNoLapack, suppress_warnings, \
IS_WINDOWS, PY3, NO_MULTIPROCESSING_SPAWN, do_test_dtypes, do_test_empty_full, \
IS_SANDCASTLE, load_tests, brute_pdist, brute_cdist, slowTest, \
skipCUDANonDefaultStreamIf, skipCUDAMemoryLeakCheckIf
from multiprocessing.reduction import ForkingPickler
from common_device_type import instantiate_device_type_tests, \
skipCPUIfNoLapack, skipCUDAIfNoMagma, skipCUDAIfRocm, onlyCUDA, onlyCPU, \
dtypes, dtypesIfCUDA, deviceCountAtLeast
import torch.backends.quantized
# load_tests from common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
if TEST_NUMPY:
import numpy as np
if TEST_SCIPY:
from scipy import signal
if TEST_LIBROSA:
import librosa
SIZE = 100
can_retrieve_source = True
with warnings.catch_warnings(record=True) as warns:
with tempfile.NamedTemporaryFile() as checkpoint:
x = torch.save(torch.nn.Module(), checkpoint)
for warn in warns:
if "Couldn't retrieve source code" in warn.message.args[0]:
can_retrieve_source = False
break
class FilelikeMock(object):
def __init__(self, data, has_fileno=True, has_readinto=False):
if has_readinto:
self.readinto = self.readinto_opt
if has_fileno:
# Python 2's StringIO.StringIO has no fileno attribute.
# This is used to test that.
self.fileno = self.fileno_opt
self.calls = set()
self.bytesio = io.BytesIO(data)
def trace(fn, name):
def result(*args, **kwargs):
self.calls.add(name)
return fn(*args, **kwargs)
return result
for attr in ['read', 'readline', 'seek', 'tell', 'write', 'flush']:
traced_fn = trace(getattr(self.bytesio, attr), attr)
setattr(self, attr, traced_fn)
def fileno_opt(self):
raise io.UnsupportedOperation('Not a real file')
def readinto_opt(self, view):
self.calls.add('readinto')
return self.bytesio.readinto(view)
def was_called(self, name):
return name in self.calls
class BytesIOContext(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, *args):
pass
# This is intentionally prefixed by an underscore. Otherwise pytest will try to
# run its methods as test cases.
class _TestTorchMixin(object):
def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True):
float_types = [torch.double,
torch.float]
int_types = [torch.int64,
torch.int32,
torch.int16]
def make_contiguous(shape, dtype):
if dtype in float_types:
val = torch.randn(shape, dtype=dtype)
val = val * ((val_range[1] - val_range[0]) / (math.pi * 2.0))
val = val + ((val_range[1] - val_range[0]) / 2.0)
val = torch.clamp(val, min=val_range[0], max=val_range[1])
return val
result = torch.zeros(shape, dtype=dtype)
result.apply_(lambda x: random.randint(val_range[0], val_range[1]))
return result
def make_non_contiguous(shape, dtype):
contig = make_contiguous(shape, dtype)
non_contig = torch.empty(shape + (2, 2), dtype=dtype)[..., 0]
non_contig = non_contig.select(-1, -1)
non_contig.copy_(contig)
self.assertFalse(non_contig.is_contiguous())
return non_contig
def make_contiguous_slice(size, dtype):
contig = make_contiguous((1, size), dtype)
non_contig = contig[:1, 1:size - 1]
self.assertTrue(non_contig.is_contiguous())
return contig
types = []
if use_floating:
types += float_types
if use_integral:
types += int_types
tensors = {"cont": [], "noncont": [], "slice": []}
for dtype in types:
tensors["cont"].append(make_contiguous(shape, dtype))
tensors["noncont"].append(make_non_contiguous(shape, dtype))
tensors["slice"].append(make_contiguous_slice(sum(list(shape)), dtype))
return tensors
def test_dir(self):
dir(torch)
def test_type_conversion_via_dtype_name(self):
x = torch.tensor([1])
self.assertEqual(x.byte().dtype, torch.uint8)
self.assertEqual(x.bool().dtype, torch.bool)
self.assertEqual(x.char().dtype, torch.int8)
self.assertEqual(x.double().dtype, torch.float64)
self.assertEqual(x.float().dtype, torch.float32)
self.assertEqual(x.half().dtype, torch.float16)
self.assertEqual(x.int().dtype, torch.int32)
self.assertEqual(x.bfloat16().dtype, torch.bfloat16)
def test_doc_template(self):
from torch._torch_docs import __file__ as doc_file
from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args
with open(doc_file, "r") as f:
doc_strs = f.read()
for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL):
for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]:
for k, v in common_args.items():
self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be '
'replaced by {{{}}}'.format(v, doc_str[0], k))
def test_doc(self):
checked_types = (types.MethodType, types.FunctionType,
types.BuiltinFunctionType, types.BuiltinMethodType)
def test_namespace(ns, *skips):
if isinstance(ns, object):
ns_name = ns.__class__.__name__
else:
ns_name = ns.__name__
skip_regexes = []
for r in skips:
if isinstance(r, string_classes):
skip_regexes.append(re.compile('^{}$'.format(re.escape(r))))
else:
skip_regexes.append(r)
for name in dir(ns):
if name.startswith('_'):
continue
var = getattr(ns, name)
if not isinstance(var, checked_types):
continue
doc = var.__doc__
has_doc = doc is not None and len(doc.strip()) > 0
full_name = ns_name + '.' + name
if any(r.match(name) for r in skip_regexes):
self.assertFalse(has_doc,
'New docs have been added for {}, please remove '
'it from the skipped list in TestTorch.test_doc'.format(full_name))
else:
self.assertTrue(has_doc, '{} is missing documentation'.format(full_name))
# FIXME: All of the following should be marked as expected failures
# so that it is easier to tell when missing has been added.
# FIXME: fix all the skipped ones below!
test_namespace(torch.randn(1),
'as_strided_',
re.compile('^clamp_(min|max)_?$'),
'coalesce',
'is_coalesced',
'is_distributed',
'is_complex',
'is_nonzero',
'is_same_size',
'isclose',
'lgamma',
'lgamma_',
'log_softmax',
'map2_',
'new',
'polygamma',
'polygamma_',
'reinforce',
'relu',
'relu_',
'prelu',
'resize',
'resize_as',
'smm',
'softmax',
'split_with_sizes',
'sspaddmm',
'to_dense',
'sparse_resize_',
'sparse_resize_and_clear_',
'align_to', # BUILD_NAMEDTENSOR only
'align_as', # BUILD_NAMEDTENSOR only
'rename', # BUILD_NAMEDTENSOR only
'rename_', # BUILD_NAMEDTENSOR only
'has_names', # BUILD_NAMEDTENSOR only
'rename', # BUILD_NAMEDTENSOR only
'refine_names', # BUILD_NAMEDTENSOR only
'unflatten', # BUILD_NAMEDTENSOR only
)
test_namespace(torch.nn)
test_namespace(torch.nn.functional, 'assert_int_or_pair', 'feature_alpha_dropout')
# TODO: add torch.* tests when we have proper namespacing on ATen functions
# test_namespace(torch)
def test_dot(self):
types = {
'torch.DoubleTensor',
'torch.FloatTensor',
}
for tname in types:
v1 = torch.randn(100).type(tname)
v2 = torch.randn(100).type(tname)
res1 = torch.dot(v1, v2)
res2 = 0
for i, j in zip(v1, v2):
res2 += i * j
self.assertEqual(res1, res2)
out = torch.randn(()).type(tname)
torch.dot(v1, v2, out=out)
self.assertEqual(res1, out)
# Test 0-strided
for tname in types:
v1 = torch.randn(1).type(tname).expand(100)
v2 = torch.randn(100).type(tname)
res1 = torch.dot(v1, v2)
res2 = 0
for i, j in zip(v1, v2):
res2 += i * j
self.assertEqual(res1, res2)
out = torch.randn(()).type(tname)
torch.dot(v1, v2, out=out)
self.assertEqual(res1, out)
def test_ger(self):
types = {
'torch.DoubleTensor',
'torch.FloatTensor',
'torch.BFloat16Tensor',
}
for tname in types:
v1 = torch.randn(100).type(tname)
v2 = torch.randn(100).type(tname)
res1 = torch.ger(v1, v2)
res2 = torch.zeros(100, 100).type(tname)
for i in range(100):
for j in range(100):
res2[i, j] = v1[i] * v2[j]
self.assertEqual(res1, res2)
# Test 0-strided
for tname in types:
v1 = torch.randn(1).type(tname).expand(100)
v2 = torch.randn(100).type(tname)
res1 = torch.ger(v1, v2)
res2 = torch.zeros(100, 100).type(tname)
for i in range(100):
for j in range(100):
res2[i, j] = v1[i] * v2[j]
self.assertEqual(res1, res2)
def test_addr(self):
types = {
'torch.DoubleTensor',
'torch.FloatTensor',
'torch.BFloat16Tensor',
}
def run_test(m, v1, v2, m_transform=lambda x: x):
m = m_transform(m.clone())
ref = m.clone()
torch.addr(m, v1, v2, out=m)
for i in range(m.size(0)):
for j in range(m.size(1)):
ref[i, j] += v1[i] * v2[j]
self.assertEqual(m, ref)
for tname in types:
for h, w in [(100, 110), (1, 20), (200, 2)]:
m = torch.randn(h, w).type(tname)
v1 = torch.randn(h).type(tname)
v2 = torch.randn(w).type(tname)
run_test(m, v1, v2)
# test transpose
run_test(m, v2, v1, lambda x: x.transpose(0, 1))
# test 0 strided
v1 = torch.randn(1).type(tname).expand(h)
run_test(m, v1, v2)
run_test(m, v2, v1, lambda x: x.transpose(0, 1))
def test_addmv(self):
types = {
'torch.DoubleTensor': 1e-8,
'torch.FloatTensor': 1e-4,
'torch.BFloat16Tensor': 1e-0,
}
for tname, prec in types.items():
t = torch.randn(10).type(tname)
m = torch.randn(10, 100).type(tname)
v = torch.randn(100).type(tname)
res1 = torch.addmv(t, m, v)
res2 = torch.zeros(10).type(tname)
res2 += t
for i in range(10):
for j in range(100):
res2[i] += m[i, j] * v[j]
self.assertEqual(res1, res2, prec)
# Test 0-strided
for tname, prec in types.items():
t = torch.randn(1).type(tname).expand(10)
m = torch.randn(10, 1).type(tname).expand(10, 100)
v = torch.randn(100).type(tname)
res1 = torch.addmv(t, m, v)
res2 = torch.zeros(10).type(tname)
res2 += t
for i in range(10):
for j in range(100):
res2[i] += m[i, j] * v[j]
self.assertEqual(res1, res2, prec)
def test_addmm(self):
types = {
'torch.DoubleTensor': 1e-8,
'torch.FloatTensor': 1e-4,
'torch.BFloat16Tensor': 1e-1,
}
for tname, prec in types.items():
M = torch.randn(10, 25).type(tname)
m1 = torch.randn(10, 50).type(tname)
m2 = torch.randn(50, 25).type(tname)
res1 = torch.addmm(M, m1, m2)
res2 = torch.zeros(10, 25).type(tname)
res2 += M
for i in range(10):
for j in range(25):
for k in range(50):
res2[i, j] += m1[i, k] * m2[k, j]
self.assertEqual(res1, res2, prec)
# Test 0-strided
for tname, prec in types.items():
M = torch.randn(10, 1).type(tname).expand(10, 25)
m1 = torch.randn(10, 1).type(tname).expand(10, 50)
m2 = torch.randn(50, 25).type(tname)
res1 = torch.addmm(M, m1, m2)
res2 = torch.zeros(10, 25).type(tname)
res2 += M
for i in range(10):
for j in range(25):
for k in range(50):
res2[i, j] += m1[i, k] * m2[k, j]
self.assertEqual(res1, res2, prec)
def test_allclose(self):
x = torch.tensor([1.0, 2.0, 3.0])
y = torch.tensor([1.01, 2.01, 3.01])
self.assertTrue(torch.allclose(x, y, rtol=0, atol=0.02))
self.assertTrue(torch.allclose(x, y, rtol=0.01, atol=0.0))
self.assertFalse(torch.allclose(x, y))
self.assertTrue(torch.allclose(torch.tensor([0.0]), torch.tensor([1e-8])))
x = torch.tensor([2.0, 3.0, nan])
y = torch.tensor([2.01, 3.01, nan])
self.assertFalse(torch.allclose(x, y, rtol=1e-2))
self.assertTrue(torch.allclose(x, y, rtol=1e-2, equal_nan=True))
self.assertFalse(torch.allclose(x, y, rtol=1e-3, equal_nan=True))
inf_t = torch.tensor([inf])
self.assertTrue(torch.allclose(inf_t, inf_t))
self.assertTrue(torch.allclose(-inf_t, -inf_t))
self.assertFalse(torch.allclose(inf_t, -inf_t))
self.assertFalse(torch.allclose(inf_t, torch.tensor([1e20])))
self.assertFalse(torch.allclose(-inf_t, torch.tensor([-1e20])))
def test_linear_algebra_scalar_raises(self):
m = torch.randn(5, 5)
v = torch.randn(5)
s = torch.tensor(7)
self.assertRaises(RuntimeError, lambda: torch.mv(m, s))
self.assertRaises(RuntimeError, lambda: torch.addmv(v, m, s))
self.assertRaises(RuntimeError, lambda: torch.ger(v, s))
self.assertRaises(RuntimeError, lambda: torch.ger(s, v))
self.assertRaises(RuntimeError, lambda: torch.addr(m, v, s))
self.assertRaises(RuntimeError, lambda: torch.addr(m, s, v))
def _test_math(self, torchfn, mathfn, input=None, test_expand=False):
if input is None:
input = []
input.append(list(range(-5, 5)))
input.append([0 for x in range(-5, 5)])
input.append([x + 1e-6 for x in range(-5, 5)])
# Some vectorized implementations don't support large ranges
input.append([x + 1e10 for x in range(-5, 5)])
input.append([x - 1e10 for x in range(-5, 5)])
input.append(torch.randn(10).tolist())
input.append((torch.randn(10) + 1e6).tolist())
input.append([math.pi * (x / 2) for x in range(-5, 5)])
def compare_reference(input, dtype):
input = torch.tensor(input, dtype=dtype)
res1 = torchfn(input.clone())
res2 = input.clone().apply_(mathfn)
torch.testing.assert_allclose(res1, res2)
# compare against the reference math function
compare_reference(input, torch.double)
compare_reference(input, torch.float)
def check_non_contiguous(shape, dtype):
contig = torch.randn(shape, dtype=dtype)
non_contig = torch.empty(shape + (2,), dtype=dtype)[..., 0]
non_contig.copy_(contig)
self.assertFalse(non_contig.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(non_contig), 'non-contiguous')
# compare application against contiguous vs. non-contiguous
check_non_contiguous((5, 7), torch.double)
check_non_contiguous((1024,), torch.double)
check_non_contiguous((5, 7), torch.float)
check_non_contiguous((1024,), torch.float)
def check_non_contiguous_index(dtype):
contig = torch.randn((2, 2, 1, 2), dtype=dtype)
non_contig = contig[:, 1, ...]
contig = non_contig.clone()
self.assertFalse(non_contig.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(non_contig), 'non-contiguous index')
check_non_contiguous_index(torch.float)
check_non_contiguous_index(torch.double)
def check_non_contiguous_expand(shape, dtype):
contig = torch.randn(shape, dtype=dtype)
non_contig = contig.clone().expand(3, -1, -1)
self.assertFalse(non_contig.is_contiguous())
contig = torchfn(contig)
non_contig = torchfn(non_contig)
for i in range(3):
self.assertEqual(contig, non_contig[i], 'non-contiguous expand[' + str(i) + ']')
# Expand is not defined for in-place operations
if test_expand:
# The size 1 case is special as it leads to 0 stride and needs to persists
check_non_contiguous_expand((1, 3), torch.double)
check_non_contiguous_expand((1, 7), torch.double)
check_non_contiguous_expand((5, 7), torch.float)
# If size(dim) == 1, stride(dim) is not defined.
# The code needs to be able to handle this
def check_contiguous_size1(dtype):
contig = torch.randn((5, 100), dtype=dtype)
contig = contig[:1, :50]
contig2 = torch.empty(contig.size(), dtype=dtype)
contig2.copy_(contig)
self.assertTrue(contig.is_contiguous())
self.assertTrue(contig2.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(contig2), 'contiguous size1')
check_contiguous_size1(torch.double)
check_contiguous_size1(torch.float)
def check_contiguous_size1_largedim(dtype):
contig = torch.randn((5, 2, 3, 1, 4, 5, 3, 2, 1, 2, 3, 4), dtype=dtype)
contig = contig[:1, :, :, :, :, :, :, :, :, :, :, :]
contig2 = torch.empty(contig.size(), dtype=dtype)
contig2.copy_(contig)
self.assertTrue(contig.is_contiguous())
self.assertTrue(contig2.is_contiguous())
self.assertEqual(torchfn(contig), torchfn(contig2), 'contiguous size1')
check_contiguous_size1_largedim(torch.double)
check_contiguous_size1_largedim(torch.float)
def check_large(dtype):
input = torch.randn(1024, 512, dtype=dtype)
actual = torchfn(input)
expected = torch.stack([torchfn(slice) for slice in input])
self.assertEqual(actual, expected, 'large')
# compare large tensor vs. repeated small applications to expose
# possible parallelism bugs.
check_large(torch.double)
check_large(torch.float)
def __test_math_by_name(self, function_name, mathfn, selffn):
mathfn = getattr(math, mathfn)
if selffn:
def torchfn(x):
return getattr(x, function_name)()
else:
torchfn = getattr(torch, function_name)
self._test_math(torchfn, mathfn, test_expand=(not selffn))
def _test_math_by_name(self, function_name, test_self=True):
if test_self:
self.__test_math_by_name(function_name + "_", function_name, True)
self.__test_math_by_name(function_name, function_name, False)
def test_sin(self):
self._test_math_by_name('sin')
def test_sinh(self):
def sinh(x):
try:
return math.sinh(x)
except OverflowError:
return inf if x > 0 else -inf
self._test_math(torch.sinh, sinh)
def test_lgamma(self):
def lgamma(x):
if x <= 0 and x == int(x):
return inf
return math.lgamma(x)
self._test_math(torch.lgamma, lgamma)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_mvlgamma(self):
from scipy.special import multigammaln
for d in range(1, 5):
input = torch.empty(10).uniform_(d, 10)
res_torch = torch.mvlgamma(input, d)
res_scipy = multigammaln(input.numpy(), d)
self.assertEqual(res_torch.numpy(), res_scipy)
def test_mvlgamma_argcheck(self):
def run_test(d):
input = torch.linspace((d - 2) / 2, 10, 10)
torch.mvlgamma(input, d)
with self.assertRaisesRegex(RuntimeError, "Condition for computing multivariate log-gamma not met"):
run_test(3)
def _digamma_input(self, test_poles=True):
input = []
input.append((torch.randn(10).abs() + 1e-4).tolist())
input.append((torch.randn(10).abs() + 1e6).tolist())
zeros = torch.linspace(-9.5, -0.5, 10)
input.append(zeros.tolist())
input.append((zeros - 0.49).tolist())
input.append((zeros + 0.49).tolist())
input.append((zeros + (torch.rand(10) * 0.99) - 0.5).tolist())
if test_poles:
input.append([-0.999999994, -1.999999994, -2.0000000111,
-100.99999994, -1931.99999994, 0.000000111,
-0.000000111, 0, -2, -329])
return input
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_digamma(self):
from scipy.special import digamma
# scipy 1.1.0 changed when it returns +/-inf vs. NaN
def torch_digamma_without_inf(inp):
res = torch.digamma(inp)
res[(res == -inf) | (res == inf)] = nan
return res
def scipy_digamma_without_inf(inp):
res = digamma(inp)
if np.isscalar(res):
return res if np.isfinite(res) else nan
res[np.isinf(res)] = nan
return res
self._test_math(torch_digamma_without_inf, scipy_digamma_without_inf, self._digamma_input())
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_polygamma(self):
from scipy.special import polygamma
for n in [0, 1]:
self._test_math(lambda x: torch.polygamma(n, x),
lambda x: polygamma(n, x).item(),
self._digamma_input(test_poles=False))
with self.assertRaisesRegex(RuntimeError, r'polygamma\(n, x\) does not support negative n\.'):
torch.polygamma(-1, torch.tensor([1.0, 2.0]))
def test_asin(self):
self._test_math(torch.asin, lambda x: math.asin(x) if abs(x) <= 1 else nan)
def test_cos(self):
self._test_math_by_name('cos')
def test_cosh(self):
def cosh(x):
try:
return math.cosh(x)
except OverflowError:
# Return inf on overflow.
# See http://en.cppreference.com/w/cpp/numeric/math/cosh
return inf
self._test_math(torch.cosh, cosh)
def test_acos(self):
self._test_math(torch.acos, lambda x: math.acos(x) if abs(x) <= 1 else nan)
def test_tan(self):
self._test_math_by_name('tan')
def test_tanh(self):
self._test_math_by_name('tanh')
def test_atan(self):
self._test_math_by_name('atan')
def test_log(self):
def log(x):
if x == 0:
return -inf
elif x < 0:
return nan
return math.log(x)
self._test_math(torch.log, log)
def test_log10(self):
def log10(x):
if x == 0:
return -inf
elif x < 0:
return nan
return math.log10(x)
self._test_math(torch.log10, log10)
def test_log1p(self):
def log1p(x):
if x == -1:
return -inf
elif x < -1:
return nan
return math.log1p(x)
self._test_math(torch.log1p, log1p)
def test_log2(self):
def log2(x):
if x == 0:
return -inf
elif x < 0:
return nan
try:
return math.log2(x)
except AttributeError:
return math.log(x, 2)
self._test_math(torch.log2, log2)
def test_sqrt(self):
self._test_math(torch.sqrt, lambda x: math.sqrt(x) if x >= 0 else nan)
def test_erf(self):
self._test_math_by_name('erf')
def test_erfc(self):
self._test_math_by_name('erfc')
def test_exp(self):
def exp(x):
try:
return math.exp(x)
except OverflowError:
return inf
self._test_math(torch.exp, exp)
@slowTest
def test_exp_slow(self):
# Test for https://github.com/pytorch/pytorch/issues/17271
# This is pretty slow on my Macbook but it only takes a few
# seconds on a beefy Xeon server
a = torch.exp(torch.ones(2 ** 31, dtype=torch.float32))
b = torch.exp(torch.ones(1, dtype=torch.float32))
self.assertEqual(a, b.expand(2 ** 31))
def test_expm1(self):
def expm1(x):
try:
return math.expm1(x)
except OverflowError:
return inf
self._test_math(torch.expm1, expm1)
def test_floor(self):
self._test_math_by_name('floor')
def test_ceil(self):
self._test_math_by_name('ceil')
def test_rsqrt(self):
def rsqrt(x):
if x == 0:
return inf
elif x < 0:
return nan
return 1.0 / math.sqrt(x)
self._test_math(torch.rsqrt, rsqrt)
def test_sigmoid(self):
# TODO: why not simulate math.sigmoid like with rsqrt?
inputValues = [-1000, -1, 0, 0.5, 1, 2, 1000]
expectedOutput = [0.0000, 0.2689, 0.5, 0.6225, 0.7311, 0.8808, 1.000]
precision_4dps = 0.0002
def checkType(tensor):
self.assertEqual(tensor(inputValues).sigmoid(), tensor(expectedOutput), precision_4dps)
checkType(torch.FloatTensor)
checkType(torch.DoubleTensor)
def test_frac(self):
self._test_math(torch.frac, lambda x: math.fmod(x, 1))
def test_trunc(self):
self._test_math(torch.trunc, lambda x: x - math.fmod(x, 1))
def test_round(self):
self._test_math(torch.round, round)
def test_has_storage(self):
self.assertIsNotNone(torch.Tensor().storage())
self.assertIsNotNone(torch.Tensor(0).storage())
self.assertIsNotNone(torch.Tensor([]).storage())
self.assertIsNotNone(torch.Tensor().clone().storage())
self.assertIsNotNone(torch.Tensor([0, 0, 0]).nonzero().storage())
self.assertIsNotNone(torch.Tensor().new().storage())
def _testSelection(self, torchfn, mathfn):
# contiguous
m1 = torch.randn(100, 100)
res1 = torchfn(m1)
res2 = m1[0, 0]
for i, j in iter_indices(m1):
res2 = mathfn(res2, m1[i, j])
self.assertEqual(res1, res2)
# non-contiguous
m1 = torch.randn(10, 10, 10)
m2 = m1[:, 4]
res1 = torchfn(m2)
res2 = m2[0, 0]
for i, j in iter_indices(m2):
res2 = mathfn(res2, m2[i][j])
self.assertEqual(res1, res2)
# with indices
m1 = torch.randn(100, 100)
res1val, res1ind = torchfn(m1, 1, False)
res2val = m1[:, 0:1].clone().squeeze()
res2ind = res1ind.clone().fill_(0)
for i, j in iter_indices(m1):
if mathfn(res2val[i], m1[i, j]) != res2val[i]:
res2val[i] = m1[i, j]
res2ind[i] = j
maxerr = 0
for i in range(res1val.size(0)):
maxerr = max(maxerr, abs(res1val[i] - res2val[i]))
self.assertEqual(res1ind[i], res2ind[i])
self.assertLessEqual(abs(maxerr), 1e-5)
# NaNs
for index in (0, 4, 99):
m1 = torch.randn(100)
m1[index] = nan
res1val, res1ind = torch.max(m1, 0)
self.assertTrue(math.isnan(res1val))
self.assertEqual(res1ind, index)
res1val = torchfn(m1)
self.assertTrue(math.isnan(res1val))
# Bool
m1 = torch.tensor([True, False, True], dtype=torch.bool)
res1 = torchfn(m1)
res2 = m1[0]
for i in iter_indices(m1):
res2 = mathfn(res2, m1[i])
self.assertEqual(res1, res2)
def test_max(self):
self._testSelection(torch.max, max)
@staticmethod
def _test_max_with_inf(self, dtypes=(torch.float, torch.double), device='cpu'):
for dtype in dtypes:
a = torch.tensor([[-inf, -inf, inf, 3], [inf, inf, -inf, -1]], dtype=dtype, device=device)
self.assertTrue(torch.all(torch.max(a, dim=1)[0] == inf).item())
self.assertTrue(torch.max(a).item() == inf)
def test_max_with_inf(self):
self._test_max_with_inf(self)
def test_min(self):
self._testSelection(torch.min, min)
@staticmethod
def _test_min_with_inf(self, dtypes=(torch.float, torch.double), device='cpu'):
for dtype in dtypes:
a = torch.tensor([[-inf, -inf, inf, 3], [inf, inf, -inf, -1]], dtype=dtype, device=device)
self.assertTrue(torch.all(torch.min(a, dim=1)[0] == (-inf)).item())
self.assertTrue(torch.min(a).item() == -inf)
def test_min_with_inf(self):
self._test_min_with_inf(self)
def test_dim_reduction_uint8_overflow(self):
example = [[-1, 2, 1], [5, 3, 6]]
x = torch.tensor(example, dtype=torch.uint8)
self.assertEqual(x.sum(dtype=torch.uint8).item(), 16)
self.assertEqual(x.sum(0, dtype=torch.uint8), torch.FloatTensor([4, 5, 7]))
self.assertEqual(x.sum(1, dtype=torch.uint8), torch.FloatTensor([2, 14]))
y = torch.tensor(example, dtype=torch.uint8)
torch.sum(x, 0, out=y)
self.assertEqual(x.sum(0, dtype=torch.uint8), y)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found")
def test_logsumexp(self):
from scipy.special import logsumexp
a = torch.randn(5, 4)
a[0, 0] = inf
a[1, :] = -inf
actual = a.logsumexp(1)
expected = logsumexp(a.numpy(), 1)
self.assertEqual(expected.shape, actual.shape)
self.assertTrue(np.allclose(expected, actual.numpy()))
# check that out is actually inplace
b = torch.zeros(5, 2)
c = b[:, 0]
torch.logsumexp(a, 1, out=c)
self.assertTrue(np.allclose(expected, b[:, 0].numpy()))
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
def test_cpu_parallel(self):
# To use parallel branches we'll need to compare on tensors
# that are relatively large. Even if this is run on a single
# core machine these tests will still give you signal on
# the correctness
def _run_test(size):
for dim in range(len(size) + 1):
nv = np.round(np.random.rand(*size)) # 0s and 1s
tv = torch.from_numpy(nv)
# Parallelisim is only used if numel is
# larger than grainsize defined in Parallel.h
self.assertTrue(tv.numel() > 32768)
if dim == len(size):
nvs = nv.sum()
tvs = tv.sum()
else:
nvs = nv.sum(dim)
tvs = tv.sum(dim)
diff = np.abs(nvs - tvs.numpy()).sum()
self.assertEqual(diff, 0)
_run_test([2, 3, 3, 3, 3, 2, 2, 3, 2, 3, 2, 3, 3])
_run_test([4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
_run_test([1, 32 * 8 * 32 * 8])
_run_test([1, 32770])
def _testCSelection(self, torchfn, mathfn):
# Two tensors
size = (100, 100)
a = torch.rand(*size)
b = torch.rand(*size)
c = torchfn(a, b)
expected_c = torch.zeros(*size)
expected_c.map2_(a, b, lambda _, a, b: mathfn(a, b))
self.assertEqual(expected_c, c, 0)
def test_max_elementwise(self):
self._testCSelection(torch.max, max)
def test_min_elementwise(self):
self._testCSelection(torch.min, min)
def test_all_any(self):
def test(size):
x = torch.ones(*size).byte()
self.assertTrue(x.all())
self.assertTrue(x.any())
x[3] = 0
self.assertFalse(x.all())
self.assertTrue(x.any())
x.zero_()
self.assertFalse(x.all())
self.assertFalse(x.any())
x.fill_(2)
self.assertTrue(x.all())
self.assertTrue(x.any())
x = torch.ones(*size).bool()
self.assertTrue(x.all())
self.assertTrue(x.any())
x[3] = False
self.assertFalse(x.all())
self.assertTrue(x.any())
test((10,))
test((5, 5))
def test_where_bool_tensor(self):
for d in torch.testing.get_all_device_types():
a = torch.tensor([True, False], device=d)
res = torch.where(a > 0)
self.assertEqual(1, len(res))
def test_all_any_with_dim(self):
def test(x):
r1 = x.prod(dim=0, keepdim=False).byte()
r2 = x.all(dim=0, keepdim=False)
self.assertEqual(r1.shape, r2.shape)
self.assertTrue((r1 == r2).all())
r3 = x.sum(dim=1, keepdim=True).clamp(0, 1).byte()
r4 = x.any(dim=1, keepdim=True)
self.assertEqual(r3.shape, r4.shape)
self.assertTrue((r3 == r4).all())
test(torch.ByteTensor([[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1]]))
def test_mv(self):
def _test_mv(m1, v1):
res1 = torch.mv(m1, v1)
res2 = res1.clone().zero_()
for i, j in iter_indices(m1):
res2[i] += m1[i][j] * v1[j]
self.assertEqual(res1, res2)
_test_mv(torch.randn(100, 100, dtype=torch.float32), torch.randn(100, dtype=torch.float32))
_test_mv(torch.randn(100, 100, dtype=torch.float64), torch.randn(100, dtype=torch.float64))
_test_mv(torch.randint(0, 100, (100, 100), dtype=torch.int32), torch.randint(0, 100, (100, ), dtype=torch.int32))
_test_mv(torch.randint(0, 100, (100, 100), dtype=torch.int64), torch.randint(0, 100, (100, ), dtype=torch.int64))
_test_mv(torch.randn(100, 100, dtype=torch.float32).bfloat16(), torch.randn(100, dtype=torch.float32).bfloat16())
def test_numpy_args(self):
x1 = torch.randn(10)
x2 = torch.randn(10)