forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 55
/
test_torch.py
10863 lines (9298 loc) · 467 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
# mypy: allow-untyped-decorators
# mypy: allow-untyped-defs
# Owner(s): ["module: tests"]
import torch
import torch.utils.data
import numpy as np
import contextlib
import gc
import io
import inspect
import itertools
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 weakref
import sys
import copyreg
from torch import inf, nan
from itertools import product, combinations, permutations, chain
from functools import partial
from torch import multiprocessing as mp
from torch.testing import make_tensor
from torch.testing._internal.common_optimizers import (
optim_db, optims, _get_optim_inputs_including_global_cliquey_kwargs)
from torch.testing._internal.common_utils import ( # type: ignore[attr-defined]
TEST_WITH_TORCHINDUCTOR, TEST_WITH_ROCM, run_tests, IS_JETSON,
IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN,
IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, skipIfTorchInductor, load_tests, slowTest, slowTestIf,
TEST_WITH_CROSSREF, skipIfTorchDynamo, skipRocmIfTorchInductor, set_default_dtype,
skipCUDAMemoryLeakCheckIf, BytesIOContext,
skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName,
wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard,
bytes_to_scalar, parametrize, skipIfMps, noncontiguous_like,
AlwaysWarnTypedStorageRemoval, TEST_WITH_TORCHDYNAMO, xfailIfTorchDynamo)
from multiprocessing.reduction import ForkingPickler
from torch.testing._internal.common_device_type import (
expectedFailureMeta,
expectedFailureXLA,
instantiate_device_type_tests,
onlyCUDA, onlyCPU,
dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast,
skipMeta, PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyNativeDeviceTypes,
get_all_device_types, skipXLA)
from typing import 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, TEST_CUDNN, TEST_MULTIGPU,
_create_scaling_case, _create_scaling_models_optimizers)
from torch.testing._internal.common_mkldnn import bf32_on_and_off
from torch.testing._internal.common_dtype import (
floating_types_and, get_all_math_dtypes, all_types_and_complex_and, complex_types,
all_types_and, floating_types, floating_and_complex_types, integral_types_and,
get_all_qint_dtypes, all_types_complex_float8_and,
)
from torch.testing._internal.two_tensor import TwoTensor
if TEST_WITH_TORCHINDUCTOR:
from torch._inductor.test_case import TestCase
else:
from torch.testing._internal.common_utils import TestCase # type: ignore[assignment]
# 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()
@contextlib.contextmanager
def torch_vital_set(value):
stash = None
if 'TORCH_VITAL' in os.environ:
stash = os.environ['TORCH_VITAL']
os.environ['TORCH_VITAL'] = value
try:
yield
finally:
if stash:
os.environ['TORCH_VITAL'] = stash
else:
del os.environ['TORCH_VITAL']
# Tests Vital Signs for Torch
# FIXME: document or deprecate whatever this is
class TestBasicVitalSigns(TestCase):
def test_basic_vitals(self):
with torch_vital_set(''):
self.assertFalse(torch.vitals_enabled())
with torch_vital_set('ON'):
self.assertTrue(torch.vitals_enabled())
def test_basic_vitals_read_write(self):
with torch_vital_set('ON'):
self.assertTrue(torch.vitals_enabled())
# This tests the code path of setting a vital
self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING'))
self.assertIn('TEST_VALUE_STRING', torch.read_vitals())
self.assertIn('CUDA.used', torch.read_vitals())
def test_dataloader_vitals(self):
with torch_vital_set('ON'):
inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
dataset = torch.utils.data.TensorDataset(inps, tgts)
loader = torch.utils.data.DataLoader(dataset, batch_size=2)
self.assertIn('Dataloader.enabled\t\t True', torch.read_vitals())
# FIXME: document or deprecate whatever this is
class TestVitalSignsCuda(TestCase):
@onlyCUDA
def test_cuda_vitals_gpu_only(self, device):
with torch_vital_set('ON'):
self.assertIn('CUDA.used\t\t true', torch.read_vitals())
is_cuda_sm86 = torch.cuda.is_available() and torch.cuda.get_device_capability(0) == (8, 6)
class TestTorchDeviceType(TestCase):
exact_dtype = True
# TODO: move all tensor creation to common ops
def _rand_shape(self, dim, min_size, max_size):
shape = []
for i in range(dim):
shape.append(random.randint(min_size, max_size))
return tuple(shape)
# Validates that mathematical constants are defined properly, as required by
# the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html)
@onlyCPU
def test_constants(self, device):
self.assertIsInstance(torch.e, float)
self.assertEqual(torch.e, math.e, atol=0, rtol=0)
self.assertIsInstance(torch.pi, float)
self.assertEqual(torch.pi, math.pi, atol=0, rtol=0)
self.assertIsInstance(torch.nan, float)
self.assertEqual(torch.nan, math.nan, equal_nan=True)
self.assertIsInstance(torch.inf, float)
self.assertEqual(torch.inf, math.inf)
@onlyNativeDeviceTypes
@dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,
torch.bool, torch.float32, torch.complex64, torch.float64,
torch.complex128, torch.uint16, torch.uint32, torch.uint64)
def test_bytes_to_scalar(self, device, dtype):
def rand_byte():
if dtype == torch.bool:
return torch.randint(0, 2, ()).item()
else:
return torch.randint(0, 256, ()).item()
element_size = torch._utils._element_size(dtype)
for i in range(10):
bytes_list = [rand_byte() for _ in range(element_size)]
scalar = bytes_to_scalar(bytes_list, dtype, device)
self.assertEqual(scalar.storage().untyped().tolist(), bytes_list)
@dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,
torch.bool, torch.float32, torch.complex64, torch.float64,
torch.complex128, torch.uint16, torch.uint32, torch.uint64)
def test_storage(self, device, dtype):
v = make_tensor((3, 5), dtype=dtype, device=device, low=-9, high=9)
self.assertEqual(v.storage()[0], v[0][0])
self.assertEqual(v.storage()[14], v[2][4])
v_s = v.storage()
for el_num in range(v.numel()):
dim0 = el_num // v.size(1)
dim1 = el_num % v.size(1)
self.assertEqual(
v_s[el_num],
v[dim0][dim1])
v_s_byte = v.storage().untyped()
el_size = v.element_size()
for el_num in range(v.numel()):
start = el_num * el_size
end = start + el_size
dim0 = el_num // v.size(1)
dim1 = el_num % v.size(1)
self.assertEqual(
bytes_to_scalar(v_s_byte[start:end], dtype, device),
v[dim0][dim1])
@onlyNativeDeviceTypes
@dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,
torch.bool, torch.float32, torch.complex64, torch.float64,
torch.complex128, torch.quint8, torch.qint8, torch.qint32,
torch.quint4x2)
def test_storage_setitem(self, device, dtype):
# Skip quantized dtypes for CUDA, since they're not supported
if torch.device(device).type == 'cuda':
if dtype in [torch.quint8, torch.qint8, torch.qint32, torch.quint4x2]:
return
storage_type_name = torch.storage._dtype_to_storage_type_map()[dtype]
if torch.device(device).type == 'cuda':
storage_type = eval('torch.cuda.' + storage_type_name)
else:
storage_type = eval('torch.' + storage_type_name)
N = 10
s = storage_type(N)
s[:] = 0
l = [0] * N
self.assertEqual(s, storage_type(l))
for i in range(N):
s[i] = i
l[i] = i
self.assertEqual(s, storage_type(l))
l[2:7] = [1] * 5
s[2:7] = 1
self.assertEqual(s, storage_type(l))
@skipIfTorchDynamo("https://github.com/pytorch/torchdynamo/issues/1991")
@onlyNativeDeviceTypes
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_tensor_storage_type(self, device, dtype):
a = make_tensor((10,), dtype=dtype, device=device, low=-9, high=9)
module = torch.cuda if (torch.device(device).type == 'cuda') else torch
expected_storage_type = getattr(module, torch.storage._dtype_to_storage_type_map()[dtype])
self.assertEqual(a.storage_type(), expected_storage_type)
@onlyNativeDeviceTypes
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16, torch.uint16, torch.uint32, torch.uint64))
def test_tensor_from_storage(self, device, dtype):
a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9)
a_s = a.storage()
b = torch.tensor(a_s, device=device, dtype=dtype).reshape(a.size())
self.assertEqual(a, b)
c = torch.tensor(a_s.untyped(), device=device, dtype=dtype).reshape(a.size())
self.assertEqual(a, c)
for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):
if error_dtype == dtype:
continue
with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'):
error_storage = a.to(error_dtype).storage()
torch.tensor(error_storage, device=device, dtype=dtype)
@onlyNativeDeviceTypes
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_set_storage(self, device, dtype):
a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9)
a_s = a.storage()
b = torch.tensor([], device=device, dtype=dtype).set_(a_s).reshape(a.size())
self.assertEqual(a, b)
c = torch.tensor([], device=device, dtype=dtype).set_(a_s.untyped()).reshape(a.size())
self.assertEqual(a, c)
for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):
if error_dtype == dtype:
continue
with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'):
error_storage = a.to(error_dtype).storage()
b = torch.tensor([], device=device, dtype=dtype).set_(error_storage)
def _check_storage_meta(self, s, s_check):
self.assertTrue(
isinstance(s, (torch.UntypedStorage, torch.TypedStorage)) and
isinstance(s_check, type(s)),
(
's and s_check must both be one of UntypedStorage or '
'TypedStorage, but got'
f' {type(s).__name__} and {type(s_check).__name__}'))
self.assertEqual(s.device.type, 'meta')
self.assertEqual(s.nbytes(), s_check.nbytes())
self.assertEqual(s.size(), s_check.size())
self.assertEqual(s.data_ptr(), 0)
with self.assertRaisesRegex(NotImplementedError, r'Not available'):
s[0]
if isinstance(s, torch.TypedStorage):
self.assertEqual(s.dtype, s_check.dtype)
self._check_storage_meta(s.untyped(), s_check.untyped())
@onlyNativeDeviceTypes
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_typed_storage_meta(self, device, dtype):
args_list = [
[],
[0],
[100],
[[1, 2, 3, 4, 5, 6]],
]
for args in args_list:
s_check = torch.TypedStorage(*args, dtype=dtype, device=device)
s = torch.TypedStorage(*args, dtype=dtype, device='meta')
self._check_storage_meta(s, s_check)
@onlyNativeDeviceTypes
def test_untyped_storage_meta(self, device):
args_list = [
[],
[0],
[100],
[[1, 2, 3, 4, 5, 6]],
]
for args in args_list:
s_check = torch.UntypedStorage(*args, device=device)
s = torch.UntypedStorage(*args, device='meta')
self._check_storage_meta(s, s_check)
@onlyNativeDeviceTypes
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_storage_meta_from_tensor(self, device, dtype):
t_check = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9)
t = t_check.to('meta')
s_check = t_check.storage()
s = t.storage()
self._check_storage_meta(s, s_check)
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_storage_meta_errors(self, device, dtype):
s0 = torch.TypedStorage([1, 2, 3, 4], device='meta', dtype=dtype)
with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'):
s0.cpu()
with self.assertRaisesRegex(RuntimeError, r'only available on CPU'):
s0._share_fd_cpu_()
with self.assertRaisesRegex(RuntimeError, r'only available on CPU'):
s0._share_filename_cpu_()
if torch.cuda.is_available():
with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'):
s0.cuda()
with self.assertRaisesRegex(RuntimeError, r'only available on CUDA'):
s0._share_cuda_()
with self.assertRaisesRegex(TypeError, r"cannot pin 'torch.storage.UntypedStorage' only CPU memory can be pinned"):
s0.pin_memory()
with self.assertRaisesRegex(RuntimeError, r'only available on CPU'):
s0.share_memory_()
with self.assertRaisesRegex(NotImplementedError, r'Not available'):
s0.tolist()
with tempfile.NamedTemporaryFile() as f:
with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'):
s0._write_file(f, True, True, s0.element_size())
for device in ['cpu', 'cuda'] if torch.cuda.is_available() else ['cpu']:
s1 = torch.TypedStorage([1, 2, 3, 4], device=device, dtype=dtype)
with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'):
s1.copy_(s0)
@onlyCPU
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_storage_meta_ok(self, device, dtype):
s0 = torch.TypedStorage([1, 2, 3, 4], device='meta', dtype=dtype)
# This is OK, it changes the meta storage size without allocating
s0.resize_(10)
@onlyCUDA
def test_module_share_memory(self):
# Test fix for issue #80733
# See https://github.com/pytorch/pytorch/issues/80733
model = torch.nn.Linear(3, 1)
model_cuda = model.to('cuda')
model.share_memory()
@dtypes(torch.float32, torch.complex64)
def test_deepcopy(self, device, dtype):
from copy import deepcopy
a = torch.randn(5, 5, dtype=dtype, device=device)
b = torch.randn(5, 5, dtype=dtype, device=device)
c = a.view(25)
q = [a, [a.storage(), b.storage()], b, c]
w = deepcopy(q)
self.assertEqual(w[0], q[0], atol=0, rtol=0)
self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0)
self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0)
self.assertEqual(w[1], q[1], atol=0, rtol=0)
self.assertEqual(w[2], q[2], atol=0, rtol=0)
# Check that deepcopy preserves sharing
w[0].add_(1)
for i in range(a.numel()):
self.assertEqual(w[1][0][i], q[1][0][i] + 1)
self.assertEqual(w[3], c + 1)
w[2].sub_(1)
for i in range(a.numel()):
self.assertEqual(w[1][1][i], q[1][1][i] - 1)
# Check that deepcopy preserves attributes
a.foo = 3
self.assertEqual(deepcopy(a).foo, 3)
@dtypes(torch.float32, torch.complex64)
def test_deepcopy_scalar(self, device, dtype):
from copy import deepcopy
a = torch.tensor(5, dtype=dtype, device=device)
self.assertEqual(a.size(), deepcopy(a).size())
self.assertEqual(a, deepcopy(a))
def check_internal_mem_overlap(self, inplace_op, num_inputs,
dtype, device,
expected_failure=False):
if isinstance(inplace_op, str):
inplace_op = getattr(torch.Tensor, inplace_op)
input = torch.randn(1, dtype=dtype, device=device).expand(3, 3)
inputs = [input] + [torch.randn_like(input)
for i in range(num_inputs - 1)]
if not expected_failure:
with self.assertRaisesRegex(RuntimeError, 'single memory location'):
inplace_op(*inputs)
else:
with self.assertRaises(AssertionError):
with self.assertRaisesRegex(RuntimeError, 'single memory location'):
inplace_op(*inputs)
def unary_check_input_output_mem_overlap(self, data, sz, op,
expected_failure=False):
def _test(op, output, input):
output_exp = torch.empty_like(output)
op(input, out=output_exp)
self.assertEqual(op(input, out=output), output_exp, msg=op.__name__)
# output is identical to input:
_test(op, output=data[0:sz], input=data[0:sz])
# output and input are independent:
_test(op, output=data[0:sz], input=data[sz:2 * sz])
# output partially overlaps with input:
if not expected_failure:
with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):
_test(op, data[0:sz], data[1:sz + 1])
else:
with self.assertRaises(AssertionError):
with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):
_test(op, data[0:sz], data[1:sz + 1])
# output is transpose of input:
length = int(math.sqrt(sz))
input = data[:length**2].view([length, length])
out = input.t()
if not expected_failure:
with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):
_test(op, out, input)
else:
with self.assertRaises(AssertionError):
with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):
_test(op, out, input)
def ternary_check_input_output_mem_overlap(self, op, device,
expected_failure=False):
sz = 9
data = torch.randn(2 * sz, device=device)
other1 = torch.randn(sz, device=device)
other2 = torch.randn(sz, device=device)
self.unary_check_input_output_mem_overlap(
data, sz, lambda input, out:
op(input, other1.view(input.shape), other2.view(input.shape), out=out),
expected_failure=expected_failure)
self.unary_check_input_output_mem_overlap(
data, sz, lambda input, out:
op(other1.view(input.shape), input, other2.view(input.shape), out=out),
expected_failure=expected_failure)
self.unary_check_input_output_mem_overlap(
data, sz, lambda input, out:
op(other1.view(input.shape), other2.view(input.shape), input, out=out),
expected_failure=expected_failure)
def _select_broadcastable_dims(self, dims_full=None):
# select full dimensionality
if dims_full is None:
dims_full = []
ndims = random.randint(1, 4)
dims_full = [random.randint(1, 8) for _ in range(ndims)]
else:
ndims = len(dims_full)
# select actual dimensions for ops:
# larger: full ndims, individual sizes may be reduced
# smaller: possibly reduced ndims, sizes may be reduced
smaller_ndims = random.randint(1, ndims)
dims_small = []
dims_large = []
for i in range(ndims - 1, -1, -1):
j = random.randint(1, 3)
if j == 1: # no reduced singleton dimension
ds = dims_full[i]
dl = dims_full[i]
elif j == 2: # larger may have reduced singleton dimension
ds = dims_full[i]
dl = 1 if len(dims_small) < smaller_ndims else dims_full[i]
elif j == 3: # smaller may have reduced singleton dimension
ds = 1
dl = dims_full[i]
dims_large = [dl] + dims_large
if len(dims_small) < smaller_ndims:
dims_small = [ds] + dims_small
return (dims_small, dims_large, dims_full)
# collected tests of ops that used scalar_check in Declarations.cwrap for
# correctness
def test_scalar_check(self, device):
zero_d = torch.randn((), device=device)
one_d = torch.randn((1,), device=device)
# remainder
self.assertEqual((), torch.remainder(zero_d, zero_d).shape)
self.assertEqual((), torch.remainder(zero_d, 2).shape)
self.assertEqual((1,), torch.remainder(zero_d, one_d).shape)
self.assertEqual((1,), torch.remainder(one_d, zero_d).shape)
# fmod
self.assertEqual((), torch.fmod(zero_d, zero_d).shape)
self.assertEqual((), torch.fmod(zero_d, 2).shape)
self.assertEqual((1,), torch.fmod(zero_d, one_d).shape)
self.assertEqual((1,), torch.fmod(one_d, zero_d).shape)
# exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal
self.assertEqual((), torch.exp(zero_d).shape)
self.assertEqual((), torch.cos(zero_d).shape)
self.assertEqual((), torch.cosh(zero_d).shape)
self.assertEqual((), torch.tan(zero_d).shape)
self.assertEqual((), torch.atan(zero_d).shape)
self.assertEqual((), torch.acosh(zero_d).shape)
self.assertEqual((), torch.asinh(zero_d).shape)
self.assertEqual((), torch.atanh(zero_d).shape)
self.assertEqual((), torch.tanh(zero_d).shape)
self.assertEqual((), torch.erf(zero_d).shape)
self.assertEqual((), torch.erfc(zero_d).shape)
self.assertEqual((), torch.reciprocal(zero_d).shape)
self.assertEqual((1,), torch.exp(one_d).shape)
self.assertEqual((1,), torch.cos(one_d).shape)
self.assertEqual((1,), torch.cosh(one_d).shape)
self.assertEqual((1,), torch.tan(one_d).shape)
self.assertEqual((1,), torch.atan(one_d).shape)
self.assertEqual((1,), torch.acosh(one_d).shape)
self.assertEqual((1,), torch.asinh(one_d).shape)
self.assertEqual((1,), torch.atanh(one_d).shape)
self.assertEqual((1,), torch.tanh(one_d).shape)
self.assertEqual((1,), torch.erf(one_d).shape)
self.assertEqual((1,), torch.erfc(one_d).shape)
self.assertEqual((1,), torch.reciprocal(one_d).shape)
# clamp
self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape)
self.assertEqual((), torch.clamp(zero_d, min=0).shape)
self.assertEqual((), torch.clamp(zero_d, max=1).shape)
self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape)
self.assertEqual((1,), torch.clamp(one_d, min=0).shape)
self.assertEqual((1,), torch.clamp(one_d, max=1).shape)
# cumsum, cumprod, cummax, cummin
self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape)
self.assertEqual((), torch.cumsum(zero_d, 0).shape)
self.assertEqual((), torch.cumprod(zero_d, 0).shape)
self.assertEqual((), torch.cummax(zero_d, 0)[0].shape)
self.assertEqual((), torch.cummin(zero_d, 0)[0].shape)
# sort, topk
self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)])
self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)])
self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)])
self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)])
# max, min
self.assertEqual((), torch.max(zero_d, zero_d).shape)
self.assertEqual((1,), torch.max(one_d, zero_d).shape)
self.assertEqual((1,), torch.max(zero_d, one_d).shape)
self.assertEqual((), torch.min(zero_d, zero_d).shape)
self.assertEqual((1,), torch.min(one_d, zero_d).shape)
self.assertEqual((1,), torch.min(zero_d, one_d).shape)
zero_d_int = torch.tensor(1, device=device)
one_d_int = torch.tensor([1], device=device)
# lshift, rshift
self.assertEqual((), (zero_d_int >> zero_d_int).shape)
self.assertEqual((), (zero_d_int >> 1).shape)
self.assertEqual((1,), (one_d_int >> zero_d_int).shape)
self.assertEqual((1,), (zero_d_int >> one_d_int).shape)
self.assertEqual((1,), (one_d_int >> 1).shape)
self.assertEqual((), (zero_d_int << zero_d_int).shape)
self.assertEqual((), (zero_d_int << 1).shape)
self.assertEqual((1,), (one_d_int << zero_d_int).shape)
self.assertEqual((1,), (zero_d_int << one_d_int).shape)
self.assertEqual((1,), (one_d_int << 1).shape)
# or
self.assertEqual((), (zero_d_int | zero_d_int).shape)
self.assertEqual((), (zero_d_int | 1).shape)
self.assertEqual((1,), (one_d_int | zero_d_int).shape)
self.assertEqual((1,), (zero_d_int | one_d_int).shape)
self.assertEqual((1,), (one_d_int | 1).shape)
# and
self.assertEqual((), (zero_d_int & zero_d_int).shape)
self.assertEqual((), (zero_d_int & 1).shape)
self.assertEqual((1,), (one_d_int & zero_d_int).shape)
self.assertEqual((1,), (zero_d_int & one_d_int).shape)
self.assertEqual((1,), (one_d_int & 1).shape)
# clone
self.assertEqual((), zero_d.clone().shape)
zero_d_bool = torch.tensor(True, device=device)
one_d_bool = torch.tensor([True], device=device)
# masked_select
self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape)
self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape)
self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape)
zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device)
one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device)
# mode
self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)])
self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)])
# max
self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)])
self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)])
# amax
self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape)
self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape)
self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape)
self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape)
# min
self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)])
self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)])
self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)])
# amin
self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape)
self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape)
self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape)
self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape)
# set_
zero_d_clone = zero_d.clone()
one_d_clone = one_d.clone()
self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape)
self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape)
self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape)
self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape)
self.assertEqual((), zero_d.clone().set_(zero_d).shape)
self.assertEqual((), one_d.clone().set_(zero_d).shape)
self.assertEqual((1,), zero_d.clone().set_(one_d).shape)
self.assertEqual((1,), one_d.clone().set_(one_d).shape)
# take
self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape)
self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape)
# gather
self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape)
self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape)
self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape)
self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape)
# normal
# std must be >= 0
zero_d_ge_0 = torch.rand((), device=device)
# documentation says out shape matches shape of mean
self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape)
self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape)
self.assertEqual((), torch.normal(1, zero_d_ge_0).shape)
self.assertEqual((), torch.normal(zero_d, 1).shape)
self.assertEqual((1,), torch.normal(one_d, 1).shape)
# TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480.
# self.assertEqual((), torch.normal(zero_d, one_d).shape)
# self.assertEqual((), torch.normal(1, one_d).shape)
# convolutions. Yes, we are testing nn.functional here; seems justified
# given its similar to the other tests
w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_()
self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1))
self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2))
# nll_loss -- verify input can't be 0-dimensional.
self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none'))
self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none'))
# verify output is 0-dimensional when reduction != 'none'
for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)),
(torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))):
self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape)
self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape)
# Test that `torch._check_tensor_all` raises errors in the correct cases
def test_check_tensor_all(self, device):
default_message = 'Expected cond to be True'
check_fn = torch._check_tensor_all
expected_error = RuntimeError
# cond must be a tensor
with self.assertRaisesRegex(TypeError, 'cond must be a tensor'):
check_fn(True)
# cond tensor must be boolean
with self.assertRaisesRegex(TypeError, 'cond tensor must have dtype torch.bool'):
check_fn(torch.ones(1, device=device))
test_sizes = [
(),
(1,),
(10,),
(1, 1),
(1, 10),
(10, 1),
(10, 10),
(1, 1, 1),
(10, 1, 1),
(1, 10, 1),
(10, 10, 10),
]
for size in test_sizes:
t_all_true = torch.ones(size, dtype=torch.bool, device=device)
t_all_false = torch.zeros(size, dtype=torch.bool, device=device)
# Should not raise error
check_fn(t_all_true)
with self.assertRaisesRegex(expected_error, default_message):
check_fn(t_all_false)
if t_all_true.numel() > 1:
t_all_true_but_one = t_all_true.clone()
# Choose a random element to set to false
idx = (random.choice(range(dim_size)) for dim_size in size)
t_all_true_but_one[(..., *idx)] = False
with self.assertRaisesRegex(expected_error, default_message):
check_fn(t_all_true_but_one)
# Test a simple failure message
message = 'message'
with self.assertRaisesRegex(expected_error, message):
check_fn(t_all_false, lambda: message)
# Test message with tensor
def message():
return torch.arange(4)
with self.assertRaisesRegex(expected_error, re.escape(str(message()))):
check_fn(t_all_false, message)
# Test format string message
def message():
return f"{'test'} {[1, 2, 'a', True]} {True} {100} {torch.arange(4)}"
with self.assertRaisesRegex(expected_error, re.escape(str(message()))):
check_fn(t_all_false, message)
# Test that `TORCH_CHECK_TENSOR_ALL` raises errors that propagate from C++ to Python
def test_check_tensor_internal(self, device):
test_sizes = [
(),
(1,),
(10,),
(1, 1),
(1, 10),
(10, 1),
(10, 10),
(1, 1, 1),
(10, 1, 1),
(1, 10, 1),
(10, 10, 10),
]
for size in test_sizes:
t_all_true = torch.ones(size, dtype=torch.bool, device=device)
t_all_false = torch.zeros(size, dtype=torch.bool, device=device)
# Should not raise error
torch._test_check_tensor(t_all_true)
with self.assertRaisesRegex(RuntimeError, "Test message for TORCH_CHECK_TENSOR_ALL"):
torch._test_check_tensor(t_all_false)
if t_all_true.numel() > 1:
t_all_true_but_one = t_all_true.clone()
# Choose a random element to set to false
idx = (random.choice(range(dim_size)) for dim_size in size)
t_all_true_but_one[(..., *idx)] = False
with self.assertRaisesRegex(RuntimeError, "Test message for TORCH_CHECK_TENSOR_ALL"):
torch._test_check_tensor(t_all_true_but_one)
# Uses mismatched arange out size to trigger a warning
@skipIfTorchDynamo("Not a suitable test for TorchDynamo")
@unittest.skipIf(TEST_WITH_CROSSREF, "crossref perturbs line numbering")
def test_cpp_warnings_have_python_context(self, device):
# Creates long string in advance to avoid a too-long Python line
s = ".+Triggered internally at.+RangeFactories.+"
# nvfuser deprecation warning filter
warnings.filterwarnings("ignore", "torch::jit::fuser::cuda", UserWarning)
def cpp_warn_fn():
out = torch.empty((5,))
torch.arange(0, 3, out=out)
return out
# Checks eager-mode cpp warning
with warnings.catch_warnings(record=True) as w:
cpp_warn_fn()
frameinfo = inspect.getframeinfo(inspect.currentframe())
warning = w[0]
# Checks for cpp context in the warning message
escaped_warning_message = str(warning.message).encode('unicode_escape')
self.assertTrue(re.search(s, repr(escaped_warning_message), re.IGNORECASE) is not None)
# Checks the Python features of the warning
# Note: the eager mode warning refers to the line in the function
# that throws the warning.
self.assertEqual(frameinfo.lineno - 6, warning.lineno)
self.assertEqual(len(w), 1)
# Checks jitted cpp warning
with warnings.catch_warnings(record=True) as w:
scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn)
scripted_cpp_warn_fn()
warning = w[0]
# Checks for cpp context in the warning message
escaped_warning_message = str(warning.message).encode('unicode_escape')
self.assertTrue(re.search(s, repr(escaped_warning_message), re.IGNORECASE) is not None)
# Checks the Python features of the warning
# Note: the jitted warning's lineno refers to the call to the jitted
# function, which in our test suite has a layer of indirection
# that makes checking the Python lineno fragile
self.assertEqual(len(w), 1)
# Checks jitted Python warning
def warn_fn():
warnings.warn("Warning!")
# The jit mimics an eager-mode Python warning in this case
with warnings.catch_warnings(record=True) as w:
scripted_warn_fn = torch.jit.script(warn_fn)
scripted_warn_fn()
frameinfo = inspect.getframeinfo(inspect.currentframe())
warning = w[0]
self.assertTrue(re.search('Warning!', str(warning.message)) is not None)
# Checks the Python features of the warning
self.assertEqual(frameinfo.lineno - 6, warning.lineno)
self.assertEqual(len(w), 1)
# FIXME: move to test_testing
@onlyCPU
def test_warn_always_caught(self, device):
# Check that we can catch a TORCH_WARN_ONCE warning twice
# since assertWarnsOnceRegex uses set_warn_always(True) which changes
# TORCH_WARN_ONCE to TORCH_WARN
a = np.arange(10)
a.flags.writeable = False
with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):
torch.from_numpy(a)
# OK, got it once, now try again
with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):
torch.from_numpy(a)
# Make sure emitting two warnings will pass the assertWarnsOnceRegex
# context manager
with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):
torch.from_numpy(a)
torch.from_numpy(a)
@onlyNativeDeviceTypes
def test_complex_half_experimental_warning(self, device):
msg = 'ComplexHalf support is experimental'
with self.assertWarnsOnceRegex(UserWarning, msg):
t = torch.randn(3, dtype=torch.chalf, device=device)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.rand(3, dtype=torch.chalf, device=device)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.empty(3, dtype=torch.chalf, device=device)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.ones(3, dtype=torch.chalf, device=device)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.zeros(3, dtype=torch.chalf, device=device)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.randn_like(t)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.rand_like(t)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.empty_like(t)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.ones_like(t)
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.zeros_like(t)
with self.assertWarnsOnceRegex(UserWarning, msg):
# t + 1 allocates a new tensor for result using empty
t + 1
@onlyCUDA
def test_dtypetensor_warnings(self, device):
msg = 'The torch.cuda.*DtypeTensor constructors are no longer recommended'
with self.assertWarnsOnceRegex(UserWarning, msg):
t = torch.cuda.FloatTensor([0])
with self.assertWarnsOnceRegex(UserWarning, msg):
t = torch.cuda.DoubleTensor([0])
def test_set_default_tensor_type_warnings(self, device):
msg = '.*is deprecated as of PyTorch 2.1, please use torch.set_default_dtype().*'
default_type = torch.tensor([]).type()
try:
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.set_default_tensor_type(torch.FloatTensor)
if torch.cuda.is_available():
with self.assertWarnsOnceRegex(UserWarning, msg):
torch.set_default_tensor_type(torch.cuda.FloatTensor)
finally:
torch.set_default_tensor_type(default_type)
# TODO: this test should be in test_nn.py
def test_conv_transposed_backward_agnostic_to_memory_format(self, device):
in_channels = 64
out_channels = 128
scale_factor = 8
batch_size = 8
length = 16
conv = torch.nn.ConvTranspose1d(
in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device)
layer_norm = torch.nn.LayerNorm(out_channels).to(device)
input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous()
input_ = conv(input_).contiguous()
input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous()
input_.sum().backward()
# 3d
conv = torch.nn.ConvTranspose3d(3, 3, kernel_size=3).to(device)
input = torch.randn(batch_size, 3, length, length, length, device=device)
out = conv(input)
out.backward(torch.ones_like(out).transpose(-2, -1))
# TODO: this test should be in test_nn.py
@onlyCUDA
@largeTensorTest('12GB')
def test_conv_transposed_large(self, device):
# ConvTranspose3d works for large input tensors (gh-32866)