forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_torch.py
8263 lines (7116 loc) · 380 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
# -*- coding: utf-8 -*-
import torch
import numpy as np
import contextlib
import io
import inspect
import math
import random
import re
import copy
import os
import tempfile
import unittest
import warnings
import types
import pickle
import textwrap
import subprocess
import sys
from torch.utils.dlpack import from_dlpack, to_dlpack
from torch._six import inf, nan, string_classes
from itertools import product, combinations, permutations
from functools import partial
from torch import multiprocessing as mp
from torch.testing._internal.common_utils import (
TestCase, TEST_WITH_ROCM, run_tests,
IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN,
do_test_dtypes, IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest,
skipCUDAMemoryLeakCheckIf, BytesIOContext, noarchTest,
skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName,
wrapDeterministicFlagAPITest, DeterministicGuard, make_tensor, _wrap_warn_once)
from multiprocessing.reduction import ForkingPickler
from torch.testing._internal.common_device_type import (
instantiate_device_type_tests,
skipCUDAVersionIn,
onlyCUDA, onlyCPU,
dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast,
skipMeta,
PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyOnCPUAndCUDA,
expectedAlertNondeterministic)
from typing import Dict, List, Tuple
import torch.backends.quantized
import torch.testing._internal.data
from torch.testing._internal.common_cuda import tf32_on_and_off, tf32_is_not_fp32
# Protects against includes accidentally setting the default dtype
assert torch.get_default_dtype() is torch.float32
# load_tests from torch.testing._internal.common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32()
# Wrap base test class into a class to hide it from testing
# See https://stackoverflow.com/a/25695512
class AbstractTestCases:
# This is intentionally prefixed by an underscore. Otherwise pytest will try to
# run its methods as test cases.
class _TestTorchMixin(TestCase):
def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True,
use_complex=False) -> Dict[str, List[torch.Tensor]]:
float_types = [torch.double,
torch.float]
int_types = [torch.int64,
torch.int32,
torch.int16]
complex_types = [torch.complex64,
torch.complex128]
def make_contiguous(shape, dtype) -> torch.Tensor:
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) -> torch.Tensor:
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) -> torch.Tensor:
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
if use_complex:
types += complex_types
tensors: Dict[str, List[torch.Tensor]] = {"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)
@wrapDeterministicFlagAPITest
def test_deterministic_flag(self):
for deterministic in [True, False]:
torch.use_deterministic_algorithms(deterministic)
self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled())
with self.assertRaisesRegex(RuntimeError, r"use_deterministic_algorithms expects a bool, but got int"):
torch.use_deterministic_algorithms(1)
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)
cfloat = x.cfloat()
self.assertEqual(cfloat.dtype, torch.complex64)
self.assertEqual(cfloat.real, x.float())
self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag))
cdouble = x.cdouble()
self.assertEqual(cdouble.dtype, torch.complex128)
self.assertEqual(cdouble.real, x.double())
self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag))
def test_doc_template(self) -> None:
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", encoding="utf-8") 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
if name in ['real', 'imag']:
y = torch.randn(1, dtype=torch.cfloat)
var = getattr(y, name)
else:
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)_?$'),
'is_distributed',
'is_nonzero',
'is_same_size',
'log_softmax',
'map2_',
'new',
'reinforce',
'relu',
'relu_',
'prelu',
'resize',
'resize_as',
'softmax',
'split_with_sizes',
'unsafe_split_with_sizes',
)
test_namespace(torch.nn)
test_namespace(torch.nn.functional, 'assert_int_or_pair')
# TODO: add torch.* tests when we have proper namespacing on ATen functions
# test_namespace(torch)
def test_msnpu_error(self):
with self.assertRaisesRegex(RuntimeError,
"Could not run 'aten::empty.memory_format' with arguments from the 'MSNPU' backend"):
torch.zeros(1, device=torch.device('msnpu'))
def test_has_storage(self):
self.assertIsNotNone(torch.tensor([]).storage())
self.assertIsNotNone(torch.empty(0).storage())
self.assertIsNotNone(torch.tensor([]).clone().storage())
self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage())
self.assertIsNotNone(torch.tensor([]).new().storage())
def test_where_invalid_device(self):
if torch.cuda.is_available():
for devices in [('cpu', 'cuda', 'cuda'), ('cuda', 'cpu', 'cpu'),
('cuda', 'cpu', 'cuda'), ('cpu', 'cuda', 'cpu')]:
condition = torch.rand(16, device=devices[0])
x = torch.rand(16, device=devices[1])
y = torch.rand(16, device=devices[2])
with self.assertRaisesRegex(RuntimeError,
"Expected condition, x and y to be on the same device"):
torch.where(condition, x, y)
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_where_tensor(self):
def rand_tensor(size, dtype, device):
if dtype.is_floating_point or dtype.is_complex:
return torch.rand(size=size, dtype=dtype, device=device)
elif dtype == torch.uint8:
return torch.randint(1, 5, size=size, dtype=dtype, device=device)
elif dtype == torch.bool:
return torch.randint(0, 1, size=size, dtype=dtype, device=device).bool()
else:
return torch.randint(-5, 5, size=size, dtype=dtype, device=device)
def get_tensor(size, dtype, device, contiguous):
if not contiguous and len(size) < 2:
raise RuntimeError("Unable to generate non contiguous tensor with size < 2")
t = rand_tensor(size, dtype, device)
if contiguous:
return t
else:
return t.transpose(0, 1)
height = 5
width = 5
for device in torch.testing.get_all_device_types():
for dt1 in torch.testing.get_all_dtypes():
for dt2 in torch.testing.get_all_dtypes():
for contiguous in [True, False]:
x1 = get_tensor((height, width), dt1, device, contiguous)
x2 = get_tensor((height, width), dt2, device, contiguous)
if dt1 != dt2:
self.assertRaisesRegex(RuntimeError, "expected scalar type", lambda: torch.where(x1 == 1, x1, x2))
else:
if x1.is_floating_point():
condition = (x1 < 0.5)
elif x1.is_complex():
condition = (x1.abs() < 0.5)
else:
condition = (x1 == 1)
expected = condition.to(x1.dtype) * x1 + (~condition).to(x2.dtype) * x2
result = torch.where(condition, x1, x2)
self.assertEqual(expected, result)
def test_dtypes(self):
all_dtypes = torch.testing.get_all_dtypes()
do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cpu'))
if torch.cuda.is_available():
all_dtypes.remove(torch.bfloat16) # Remove once _th_zero_ is enabled on cuda for bfloat16
do_test_dtypes(self, all_dtypes, torch.strided, torch.device('cuda:0'))
def test_copy_dtypes(self):
all_dtypes = torch.testing.get_all_dtypes()
for dtype in all_dtypes:
copied_dtype = copy.deepcopy(dtype)
self.assertIs(dtype, copied_dtype)
def test_copy_transpose(self):
x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t()
y = torch.empty(100, 100, dtype=torch.float)
y.copy_(x)
self.assertEqual(y[:, 0], range(100))
self.assertEqual(y[:, 40], range(4000, 4100))
y = torch.empty(100, 100, dtype=torch.double)
y.copy_(x)
self.assertEqual(y[:, 0], range(100))
self.assertEqual(y[:, 40], range(4000, 4100))
# Validates regression reported in https://github.com/pytorch/pytorch/issues/45269
x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t()
y = torch.empty(100, 100, dtype=torch.cfloat)
y.copy_(x)
self.assertEqual(y[:, 0], range(100))
self.assertEqual(y[:, 40], range(4000, 4100))
def test_device(self):
cpu = torch.device('cpu')
self.assertEqual('cpu', str(cpu))
self.assertEqual('cpu', cpu.type)
self.assertEqual(None, cpu.index)
cpu0 = torch.device('cpu:0')
self.assertEqual('cpu:0', str(cpu0))
self.assertEqual('cpu', cpu0.type)
self.assertEqual(0, cpu0.index)
cpu0 = torch.device('cpu', 0)
self.assertEqual('cpu:0', str(cpu0))
self.assertEqual('cpu', cpu0.type)
self.assertEqual(0, cpu0.index)
cuda = torch.device('cuda')
self.assertEqual('cuda', str(cuda))
self.assertEqual('cuda', cuda.type)
self.assertEqual(None, cuda.index)
cuda1 = torch.device('cuda:1')
self.assertEqual('cuda:1', str(cuda1))
self.assertEqual('cuda', cuda1.type)
self.assertEqual(1, cuda1.index)
cuda1 = torch.device('cuda', 1)
self.assertEqual('cuda:1', str(cuda1))
self.assertEqual('cuda', cuda1.type)
self.assertEqual(1, cuda1.index)
cuda90 = torch.device('cuda', 90)
self.assertEqual('cuda:90', str(cuda90))
self.assertEqual('cuda', cuda90.type)
self.assertEqual(90, cuda90.index)
self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 '))
self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3'))
self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3'))
self.assertRaises(RuntimeError, lambda: torch.device(-1))
self.assertRaises(RuntimeError, lambda: torch.device('other'))
self.assertRaises(RuntimeError, lambda: torch.device('other:0'))
device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'}
device_hash_set = set()
for device in list(device_set):
device_hash_set.add(hash(torch.device(device)))
self.assertEqual(len(device_set), len(device_hash_set))
def get_expected_device_repr(device):
if device.index is not None:
return "device(type='{type}', index={index})".format(
type=device.type, index=device.index)
return "device(type='{type}')".format(type=device.type)
for device in device_set:
dev = torch.device(device)
self.assertEqual(repr(dev), get_expected_device_repr(dev))
def test_to(self):
def test_copy_behavior(t, non_blocking=False):
self.assertIs(t, t.to(t, non_blocking=non_blocking))
self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking))
self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking))
self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True))
devices = [t.device]
if t.device.type == 'cuda':
if t.device.index == -1:
devices.append('cuda:{}'.format(torch.cuda.current_device()))
elif t.device.index == torch.cuda.current_device():
devices.append('cuda')
for device in devices:
self.assertIs(t, t.to(device, non_blocking=non_blocking))
self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking))
self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True))
self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True))
a = torch.tensor(5)
test_copy_behavior(a)
self.assertEqual(a.device, a.to('cpu').device)
self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device)
self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype)
self.assertEqual(a.device, a.to(torch.float32).device)
self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype)
self.assertEqual(a.data_ptr(), a.to('cpu').data_ptr())
self.assertEqual(a.data_ptr(), a.to(dtype=a.dtype, device=a.device, copy=False).data_ptr())
self.assertEqual(a.data_ptr(), a.to('cpu', copy=False).data_ptr())
self.assertNotEqual(a.data_ptr(), a.to('cpu', copy=True).data_ptr())
if torch.cuda.is_available():
for non_blocking in [True, False]:
for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:
b = torch.tensor(5., device=cuda)
test_copy_behavior(b, non_blocking)
self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device)
self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device)
self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device)
self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype)
self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device)
self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype)
self.assertEqual(b.device, b.to(dtype=torch.int32).device)
def test_to_with_tensor(self):
a = torch.tensor(5)
self.assertEqual(a.device, a.to(a).device)
if torch.cuda.is_available():
for non_blocking in [True, False]:
for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:
b = torch.tensor(5., device=cuda)
self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device)
self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device)
self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device)
def test_as_subclass(self):
class SubTensor(torch.Tensor):
member_var = object()
t0 = torch.tensor(0)
t1 = torch.tensor([1, 2])
t2 = torch.tensor([[3, 4], [5, 6]])
s0 = t0.as_subclass(SubTensor)
s1 = t1.as_subclass(SubTensor)
s2 = t2.as_subclass(SubTensor)
# Check that the correct type is returned.
self.assertTrue(type(s0) is SubTensor)
self.assertTrue(type(s1) is SubTensor)
self.assertTrue(type(s2) is SubTensor)
# Check that the data is equal.
self.assertEqual(t0, s0)
self.assertEqual(t1, s1)
self.assertEqual(t2, s2)
t0[()] = 1
t1[1] = 3
t2[1, 1] = 7
# Check that the data is equal even after modification.
self.assertEqual(t0, s0)
self.assertEqual(t1, s1)
self.assertEqual(t2, s2)
# Check that member variables are passed through.
self.assertTrue(s0.member_var is SubTensor.member_var)
self.assertTrue(s1.member_var is SubTensor.member_var)
self.assertTrue(s2.member_var is SubTensor.member_var)
# Test that autograd is propagated.
t = torch.tensor(5, dtype=torch.float32, requires_grad=True)
# Run a calculation on the tensor.
exp_t = torch.exp(t)
# Cast exp_t to a subclass.
exp_s = exp_t.as_subclass(SubTensor)
# Make sure that t.grad was initially None
self.assertTrue(t.grad is None)
# Run the autograd calculation.
exp_s.backward()
# Make sure autograd was propagated to the original tensor
# declared with requires_grad.
self.assertTrue(t.grad is not None)
def test_type(self):
x = torch.randn(3, 3).double()
self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32)
self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32)
self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype())
self.assertEqual(x.type(torch.int32).dtype, torch.int32)
def test_qengine(self):
qengines = torch.backends.quantized.supported_engines
original_qe = torch.backends.quantized.engine
for qe in qengines:
torch.backends.quantized.engine = qe
assert torch.backends.quantized.engine == qe, 'qengine not set successfully'
torch.backends.quantized.engine = original_qe
def _spawn_method(self, method, arg):
try:
mp.set_start_method('spawn')
except RuntimeError:
pass
with mp.Pool(1) as pool:
out: list = pool.map(method, [arg])
self.assertTrue(out[0])
@staticmethod
def _test_multinomial_invalid_probs(probs):
try:
# n_sample = 1 is a special case, test n_sample=2 which is more general
torch.multinomial(probs.to('cpu'), 2)
return False # Should not be reached
except RuntimeError as e:
return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e)
@slowTest
@unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \
don't support multiprocessing with spawn start method")
@unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows')
def test_multinomial_invalid_probs(self):
test_method = AbstractTestCases._TestTorchMixin._test_multinomial_invalid_probs
self._spawn_method(test_method, torch.tensor([1., -1., 1.]))
self._spawn_method(test_method, torch.tensor([1., inf, 1.]))
self._spawn_method(test_method, torch.tensor([1., -inf, 1.]))
self._spawn_method(test_method, torch.tensor([1., 1., nan]))
def test_copy_broadcast(self):
torch.zeros(5, 6).copy_(torch.zeros(6))
self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30)))
def test_copy_many_to_one(self):
# Testing in-place copy where it attempt to write from many memory
# storage to a single storage would cause RuntimeError to be thrown
self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6)))
def test_slice(self):
empty = torch.empty(0, 4)
x = torch.arange(0., 16).view(4, 4)
self.assertEqual(x[:], x)
self.assertEqual(x[:4], x)
# start and stop are clamped to the size of dim
self.assertEqual(x[:5], x)
# if start >= stop then the result is empty
self.assertEqual(x[2:1], empty)
self.assertEqual(x[2:2], empty)
# out of bounds is also empty
self.assertEqual(x[10:12], empty)
# additional correctness checks
self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]])
self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]])
self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]])
self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]])
@unittest.skip("Not implemented yet")
def test_conv2(self):
x = torch.rand(math.floor(torch.uniform(50, 100)), math.floor(torch.uniform(50, 100)))
k = torch.rand(math.floor(torch.uniform(10, 20)), math.floor(torch.uniform(10, 20)))
imvc = torch.conv2(x, k)
imvc2 = torch.conv2(x, k, 'V')
imfc = torch.conv2(x, k, 'F')
ki = k.clone()
ks = k.storage()
kis = ki.storage()
for i in range(ks.size() - 1, 0, -1):
kis[ks.size() - i + 1] = ks[i]
# for i=ks.size(), 1, -1 do kis[ks.size()-i+1]=ks[i] end
imvx = torch.xcorr2(x, ki)
imvx2 = torch.xcorr2(x, ki, 'V')
imfx = torch.xcorr2(x, ki, 'F')
self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv2')
self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr2(x, x)[0][0]), 1e-10, 'torch.conv2')
xx = torch.empty(2, x.size(1), x.size(2))
xx[1].copy_(x)
xx[2].copy_(x)
kk = torch.empty(2, k.size(1), k.size(2))
kk[1].copy_(k)
kk[2].copy_(k)
immvc = torch.conv2(xx, kk)
immvc2 = torch.conv2(xx, kk, 'V')
immfc = torch.conv2(xx, kk, 'F')
self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv2')
self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv2')
@unittest.skip("Not implemented yet")
def test_conv3(self):
x = torch.rand(math.floor(torch.uniform(20, 40)),
math.floor(torch.uniform(20, 40)),
math.floor(torch.uniform(20, 40)))
k = torch.rand(math.floor(torch.uniform(5, 10)),
math.floor(torch.uniform(5, 10)),
math.floor(torch.uniform(5, 10)))
imvc = torch.conv3(x, k)
imvc2 = torch.conv3(x, k, 'V')
imfc = torch.conv3(x, k, 'F')
ki = k.clone()
ks = k.storage()
kis = ki.storage()
for i in range(ks.size() - 1, 0, -1):
kis[ks.size() - i + 1] = ks[i]
imvx = torch.xcorr3(x, ki)
imvx2 = torch.xcorr3(x, ki, 'V')
imfx = torch.xcorr3(x, ki, 'F')
self.assertEqual(imvc, imvc2, atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(imvc, imvx, atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(imvc, imvx2, atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(imfc, imfx, atol=0, rtol=0, msg='torch.conv3')
self.assertLessEqual(math.abs(x.dot(x) - torch.xcorr3(x, x)[0][0][0]), 4e-10, 'torch.conv3')
xx = torch.empty(2, x.size(1), x.size(2), x.size(3))
xx[1].copy_(x)
xx[2].copy_(x)
kk = torch.empty(2, k.size(1), k.size(2), k.size(3))
kk[1].copy_(k)
kk[2].copy_(k)
immvc = torch.conv3(xx, kk)
immvc2 = torch.conv3(xx, kk, 'V')
immfc = torch.conv3(xx, kk, 'F')
self.assertEqual(immvc[0], immvc[1], atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(immvc[0], imvc, atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(immvc2[0], imvc2, atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(immfc[0], immfc[1], atol=0, rtol=0, msg='torch.conv3')
self.assertEqual(immfc[0], imfc, atol=0, rtol=0, msg='torch.conv3')
@unittest.skip("Not implemented yet")
def _test_conv_corr_eq(self, fn, fn_2_to_3):
ix = math.floor(random.randint(20, 40))
iy = math.floor(random.randint(20, 40))
iz = math.floor(random.randint(20, 40))
kx = math.floor(random.randint(5, 10))
ky = math.floor(random.randint(5, 10))
kz = math.floor(random.randint(5, 10))
x = torch.rand(ix, iy, iz)
k = torch.rand(kx, ky, kz)
o3 = fn(x, k)
o32 = torch.zeros(o3.size())
fn_2_to_3(x, k, o3, o32)
self.assertEqual(o3, o32)
@unittest.skip("Not implemented yet")
def test_xcorr3_xcorr2_eq(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.xcorr2(x[i + j - 1], k[j]))
self._test_conv_corr_eq(torch.xcorr3, reference)
@unittest.skip("Not implemented yet")
def test_xcorr3_xcorr2_eq_full(self):
def reference(x, k, o3, o32):
for i in range(x.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.xcorr2(x[i], k[k.size(1) - j + 1], 'F'))
self._test_conv_corr_eq(lambda x, k: torch.xcorr3(x, k, 'F'), reference)
@unittest.skip("Not implemented yet")
def test_conv3_conv2_eq_valid(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i].add(torch.conv2(x[i + j - 1], k[k.size(1) - j + 1]))
self._test_conv_corr_eq(torch.conv3, reference)
@unittest.skip("Not implemented yet")
def test_fconv3_fconv2_eq(self):
def reference(x, k, o3, o32):
for i in range(o3.size(1)):
for j in range(k.size(1)):
o32[i + j - 1].add(torch.conv2(x[i], k[j], 'F'))
self._test_conv_corr_eq(lambda x, k: torch.conv3(x, k, 'F'), reference)
def test_dtype_is_signed(self):
for dtype in torch.testing.get_all_dtypes():
self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype)))
self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed)
self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed)
self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed)
def test_RNGState(self):
state = torch.get_rng_state()
stateCloned = state.clone()
before = torch.rand(1000)
self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0)
torch.set_rng_state(state)
after = torch.rand(1000)
self.assertEqual(before, after, atol=0, rtol=0)
def test_RNGStateAliasing(self):
# Fork the random number stream at this point
gen = torch.Generator()
gen.set_state(torch.get_rng_state())
self.assertEqual(gen.get_state(), torch.get_rng_state())
target_value = torch.rand(1000)
# Dramatically alter the internal state of the main generator
_ = torch.rand(100000)
forked_value = torch.rand(1000, generator=gen)
self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg="RNG has not forked correctly.")
def test_RNG_after_pickle(self):
torch.random.manual_seed(100)
before = torch.rand(10)
torch.random.manual_seed(100)
buf = io.BytesIO()
tensor = torch.tensor([1, 2, 3])
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor)
after = torch.rand(10)
self.assertEqual(before, after, atol=0, rtol=0)
def test_boxMullerState(self):
torch.manual_seed(123)
odd_number = 101
seeded = torch.randn(odd_number)
state = torch.get_rng_state()
midstream = torch.randn(odd_number)
torch.set_rng_state(state)
repeat_midstream = torch.randn(odd_number)
torch.manual_seed(123)
reseeded = torch.randn(odd_number)
self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0,
msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers')
self.assertEqual(seeded, reseeded, atol=0, rtol=0,
msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers')
def test_manual_seed(self):
rng_state = torch.get_rng_state()
torch.manual_seed(2)
x = torch.randn(100)
self.assertEqual(torch.initial_seed(), 2)
torch.manual_seed(2)
y = torch.randn(100)
self.assertEqual(x, y)
max_int64 = 0x7fff_ffff_ffff_ffff
min_int64 = -max_int64 - 1
max_uint64 = 0xffff_ffff_ffff_ffff
# Check all boundary cases of valid seed value inputs
test_cases = [
# (seed, expected_initial_seed)
# Positive seeds should be unchanged
(max_int64, max_int64),
(max_int64 + 1, max_int64 + 1),
(max_uint64, max_uint64),
(0, 0),
# Negative seeds wrap around starting from the largest seed value
(-1, max_uint64),
(min_int64, max_int64 + 1)
]
for seed, expected_initial_seed in test_cases:
torch.manual_seed(seed)
actual_initial_seed = torch.initial_seed()
msg = "expected initial_seed() = %x after calling manual_seed(%x), but got %x instead" % (
expected_initial_seed, seed, actual_initial_seed)
self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg)
for invalid_seed in [min_int64 - 1, max_uint64 + 1]:
with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'):
torch.manual_seed(invalid_seed)
torch.set_rng_state(rng_state)
def test_numel(self):
b = torch.ByteTensor(3, 100, 100)
self.assertEqual(b.nelement(), 3 * 100 * 100)
self.assertEqual(b.numel(), 3 * 100 * 100)
def test_empty_storage_view(self):
# we should be able to "modify" slices of a 0-element
# array without an error being raised due to
# trying to resize its storage
t = torch.from_numpy(np.empty((0, 4)))
t[:, 1::2] *= 1
def test_newaxis_numpy_comparison(self):
def run_test(tensor, *idx):
npt = tensor.numpy()
self.assertEqual(tensor[idx], npt[idx])
# 1D Tensor Tests
x = torch.arange(0, 10)
cases = [
[None],
[None, None],
[Ellipsis, None],
[None, Ellipsis],
[2, None],
[None, 2],
[Ellipsis, None, 2],
[Ellipsis, 2, None],
[2, Ellipsis, None],
[2, None, Ellipsis],
[None, 2, Ellipsis],
[None, Ellipsis, 2],
]
for case in cases:
run_test(x, *case)
# 2D Tensor Tests
x = torch.arange(0, 12).view(3, 4)
cases = [
[None],
[None, None],
[None, None, None],
[Ellipsis, None],
[Ellipsis, None, None],
[None, Ellipsis],
[None, Ellipsis, None],
[None, None, Ellipsis],
[2, None],
[2, None, Ellipsis],
[2, Ellipsis, None],
[None, 2, Ellipsis],
[Ellipsis, 2, None],
[Ellipsis, None, 2],
[None, Ellipsis, 2],
[1, 2, None],
[1, 2, Ellipsis, None],
[1, Ellipsis, 2, None],
[Ellipsis, 1, None, 2],
[Ellipsis, 1, 2, None],
[1, None, 2, Ellipsis],
[None, 1, Ellipsis, 2],
[None, 1, 2, Ellipsis],
]
for case in cases:
run_test(x, *case)
def _consecutive(self, size, start=1):
sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0)
sequence.add_(start - 1)
return sequence.resize_(*size)
def test_newindex(self):
reference = self._consecutive((3, 3, 3))
# This relies on __index__() being correct - but we have separate tests for that
def checkPartialAssign(index):
reference = torch.zeros(3, 3, 3)
reference[index] = self._consecutive((3, 3, 3))[index]
self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0)
reference[index] = 0
self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0)
checkPartialAssign(0)
checkPartialAssign(1)
checkPartialAssign(2)
checkPartialAssign((0, 1))
checkPartialAssign((1, 2))
checkPartialAssign((0, 2))
checkPartialAssign(torch.LongTensor((0, 2)))
with self.assertRaises(IndexError):
reference[1, 1, 1, 1] = 1
with self.assertRaises(IndexError):
reference[1, 1, 1, (1, 1)] = 1
with self.assertRaises(IndexError):
reference[3, 3, 3, 3, 3, 3, 3, 3] = 1
with self.assertRaises(IndexError):
reference[0.0] = 1
with self.assertRaises(TypeError):
reference[0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, :, 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, ..., 0.0:2.0] = 1
with self.assertRaises(IndexError):
reference[0.0, :, 0.0] = 1
def test_index_add(self):
for device in torch.testing.get_all_device_types():
for dest_contig, src_contig, index_contig in product([True, False], repeat=3):
for other_sizes in ((), (4, 5)):
for dtype in [torch.int, torch.long]:
num_copy, num_dest = 3, 3
dest = torch.randn(num_dest, *other_sizes, device=device)
if not dest_contig:
dest = torch.testing.make_non_contiguous(dest)
src = torch.randn(num_copy, *other_sizes, device=device)
if not src_contig:
src = torch.testing.make_non_contiguous(src)
idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy)
if not index_contig:
idx = torch.testing.make_non_contiguous(idx)
# index_add_ without alpha argument
dest2 = dest.clone()
dest.index_add_(0, idx, src)
for i in range(idx.size(0)):
dest2[idx[i]] += src[i]
self.assertEqual(dest, dest2)
# index_add_ with alpha argument
dest2 = dest.clone()
dest.index_add_(0, idx, src, alpha=2)
for i in range(idx.size(0)):
dest2[idx[i]] += src[i] * 2
self.assertEqual(dest, dest2)
# add coverage for issue with atomic add that appeared only for
# specific dtypes on cuda:
# https://github.com/pytorch/pytorch/issues/29153
def test_index_add_all_dtypes(self):
for device in torch.testing.get_all_device_types():
for dtype in torch.testing.get_all_math_dtypes(device):
for idx_dtype in [torch.int, torch.long]:
size = [5, 5]
if dtype.is_floating_point or dtype.is_complex:
tensor = torch.rand(size, dtype=dtype, device=device)
elif dtype.is_signed:
tensor = torch.randint(-5, 15, size, dtype=dtype, device=device)
else:
tensor = torch.randint(0, 10, size, dtype=dtype, device=device)
# index_add calls atomicAdd on cuda.
zeros = torch.zeros(size, dtype=dtype, device=device)
added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor)
self.assertEqual(added, tensor)
added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1)
self.assertEqual(added, -tensor)
# Fill idx with valid indices.
@staticmethod
def _fill_indices(self, idx, dim, dim_size, elems_per_row, m, n, o):
for i in range(1 if dim == 0 else m):
for j in range(1 if dim == 1 else n):
for k in range(1 if dim == 2 else o):
ii = [i, j, k]
ii[dim] = slice(0, idx.size(dim) + 1)
idx[tuple(ii)] = torch.randperm(dim_size)[0:elems_per_row]
def test_unflatten(self):
# test args: tensor, int, sizes
self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1))
self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]]))
self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]]))
self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]]))
self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]]))
self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2))
self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)),
torch.tensor([[1, 2], [3, 4]]))
self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)),
torch.ones(2, 5, 2))
self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)),
torch.ones(2, 10))
self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)),
torch.ones(2, 3, 4, 5, 6))
self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)),
torch.ones(2, 3, 0, 4, 5, 2))
# test invalid args: tensor, str, sizes
with self.assertRaisesRegex(TypeError, r"received an invalid combination of arguments"):
torch.tensor([1]).unflatten('A', (1, 1))