forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_torch.py
8371 lines (7175 loc) · 361 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 -*-
# 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
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 import make_tensor
from torch.testing._internal.common_utils import (
TestCase, TEST_WITH_ROCM, run_tests,
IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN,
IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest,
skipCUDAMemoryLeakCheckIf, BytesIOContext, noarchTest,
skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName,
wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard,
skipIfNotRegistered, bytes_to_scalar, parametrize)
from multiprocessing.reduction import ForkingPickler
from torch.testing._internal.common_device_type import (
expectedFailureMeta,
expectedFailureXLA,
instantiate_device_type_tests,
skipCUDAVersionIn,
onlyCUDA, onlyCPU,
dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast,
skipMeta,
PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyNativeDeviceTypes,
expectedAlertNondeterministic, 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)
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,
)
# 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())
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)
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)
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))
@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))
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)
@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)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape)
self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape)
self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape)
# 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)
# multilabel_margin_loss
for input in (zero_d, one_d, torch.randn(1, 1, device=device)):
for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)):
if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2):
output_shape = (target.shape[0],) if target.dim() == 2 else ()
self.assertEqual(output_shape,
torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape)
self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape)
self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape)
else:
self.assertRaises(RuntimeError,
lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none'))
self.assertRaises(RuntimeError,
lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean'))
self.assertRaises(RuntimeError,
lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum'))
# multi_margin_loss
for input in (zero_d, one_d, torch.randn(1, 1, device=device)):
for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)):
self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape)
self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape)
self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape)
# Uses mismatched arange out size to trigger a warning
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.+"
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
self.assertTrue(re.search(s, str(warning.message)) 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
self.assertTrue(re.search(s, str(warning.message)) 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)
# 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)
in_channels = 64
out_channels = 128
kernel_size = 5
conv = torch.nn.ConvTranspose3d(
in_channels, out_channels, kernel_size=kernel_size,
stride=2, padding=2, output_padding=1).to(device)
x = torch.rand([1, 64, 8, 128, 172]).to(device)
y = conv(x)
def test_is_set_to(self, device):
t1 = torch.empty(3, 4, 9, 10, device=device)
t2 = torch.empty(3, 4, 9, 10, device=device)
t3 = torch.tensor([], device=device).set_(t1)
t4 = t3.clone().resize_(12, 90)
self.assertFalse(t1.is_set_to(t2))
self.assertTrue(t1.is_set_to(t3))
self.assertTrue(t3.is_set_to(t1), "is_set_to should be symmetric")
self.assertFalse(t1.is_set_to(t4))
self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])),
"Tensors with no storages should not appear to be set "
"to each other")
t1 = torch.tensor([True, True], dtype=torch.bool, device=device)
t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1)
self.assertTrue(t1.is_set_to(t2))
# test that sizes must match
t1 = torch.empty([2, 3, 4], device=device)
t2 = t1.view(4, 3, 2)
self.assertFalse(t1.is_set_to(t2))
self.assertFalse(t2.is_set_to(t1))
# test that legacy empty size behavior used to be respected (i.e. all
# empty tensors were logically collapsed to size [0]).
t1 = torch.empty([2, 5, 0], device=device)
t2 = t1.view([0])
self.assertFalse(t1.is_set_to(t2))
self.assertFalse(t2.is_set_to(t1))
# See https://github.com/pytorch/pytorch/issues/72650
@skipMeta
@parametrize(
"fn",
[
"dist", "atan2", "pow", "lerp", "add", "sub", "mul", "div", "fmod", "remainder", "eq", "ge", "gt", "le",
"lt", "max", "min", "ne", "addcdiv", "addcmul", "masked_scatter", "masked_select", "masked_fill", "map",
"map2", "copy",
],
)
def test_broadcast(self, fn, device):
# functions with three tensor arguments
fns_3_args = {"map2"}
fns_value_kwarg = {"addcdiv", "addcmul"}
(dims_small, dims_large, dims_full) = self._select_broadcastable_dims()
full1d = torch.randn(*dims_full, device=device).flatten().float()
small = torch.randn(*dims_small, device=device).float()
large = torch.randn(*dims_large, device=device).float()
small_expanded = small.expand(*dims_full)
large_expanded = large.expand(*dims_full)
small2 = None
small2_expanded = None
if fn in fns_3_args or fn in fns_value_kwarg:
# create another smaller tensor
(dims_small2, _, _) = self._select_broadcastable_dims(dims_full)
small2 = torch.randn(*dims_small2, device=device).float()
small2_expanded = small2.expand(*dims_full)
if small.is_cuda and fn in ['map', 'map2']:
# map and map2 are not implementd on CUDA tensors
return
if hasattr(large_expanded, fn):
# run through tensor versions of functions
# and verify fully expanded inputs give same results
expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded}
def tensorfn(myfn, t1, t2):
if fn == "lerp":
return myfn(t1, 0.5)
elif fn == "masked_select":
return myfn(t1 < 0)
elif fn == "masked_scatter":
return myfn(t1 < 0.5, full1d)
elif fn == "masked_fill":
return myfn(t1 < 0.5, 1.0)
elif fn in fns_3_args:
return myfn(1, t1, t2)
elif fn in fns_value_kwarg:
return myfn(t1, t2, value=1)
else:
return myfn(t1)
# test various orders
for first, second, third in [(large, small, small2), (small, large, small2),
(small2, small, large), (small2, large, small)]:
if first is None:
break # ignore last iter when small2 is None
method_expanded = getattr(expanded[first], fn)
method = getattr(first, fn)
r1 = tensorfn(method_expanded, expanded[second], expanded[third])
r2 = tensorfn(method, second, third)
self.assertEqual(r1, r2)
# now for torch. versions of functions
if hasattr(torch, fn):
fntorch = getattr(torch, fn)
expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded}
def torchfn(t1, t2, t3):
if fn == "lerp":
return fntorch(t1, t2, 0.5)
elif fn == "masked_select":
return fntorch(t1, t2 < 0)
elif fn == "masked_scatter":
return fntorch(t1, t2 < 0.5, full1d)
elif fn == "masked_fill":
return fntorch(t1, t2 < 0.5, 1.0)
elif fn in fns_3_args:
return fntorch(t1, 1.0, t2, t3)
elif fn in fns_value_kwarg:
return fntorch(t1, t2, t3, value=1.0)
else:
return fntorch(t1, t2)
# test various orders
for first, second, third in [(large, small, small2), (small, large, small2),
(small2, small, large), (small2, large, small)]:
if first is None:
break # ignore last iter when small2 is None
r1 = torchfn(expanded[first], expanded[second], expanded[third])
r2 = torchfn(first, second, third)
self.assertEqual(r1, r2)
# now for in place functions
# in-place tensor is not broadcastable; test only guaranteed
# to work by broadcasting other argument(s)
if not hasattr(large_expanded, fn + "_"):
return
# need to clone largeExpanded so we can reuse, since functions are in-place
large_expanded_clone = large_expanded.clone()
def tensorfn_inplace(t0, t1, t2=None):
t0_fn = getattr(t0, fn + "_")
if fn == "lerp":
return t0_fn(t1, 0.5)
elif fn == "masked_scatter":
return t0_fn(t1 < 0.5, full1d)
elif fn == "masked_fill":
return t0_fn(t1 < 0.5, 1.0)
elif fn == "map":
return t0_fn(t1, lambda x, y: x + y)
elif fn == "map2":
return t0_fn(t1, t2, lambda x, y, z: x + y + z)
elif fn in fns_3_args:
return t0_fn(1.0, t1, t2)
elif fn in fns_value_kwarg:
return t0_fn(t1, t2, value=1.0)
else:
return t0_fn(t1)
# in-place pointwise operations don't actually work if the in-place
# tensor is 0-strided (numpy has the same issue)
if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()):
r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded)
r2 = tensorfn_inplace(large_expanded_clone, small, small2)
self.assertEqual(r1, r2)
def broadcastable(t0, t1, t2=None):
try:
t1.expand_as(t0)
if t2 is not None:
t2.expand_as(t0)
except RuntimeError:
return False
return True
def _test_in_place_broadcastable(t0, t1, t2=None):
if not broadcastable(t0, t1, t2):
same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True)
if not same_size:
self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2))
else:
tensorfn_inplace(t0, t1, t2)
if fn not in fns_3_args and fn not in fns_value_kwarg:
_test_in_place_broadcastable(small, large_expanded)
_test_in_place_broadcastable(small, large)
else:
_test_in_place_broadcastable(small2, small_expanded, large_expanded)
_test_in_place_broadcastable(small2, small, large)
@unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "cublas runtime error")
@onlyCUDA
@wrapDeterministicFlagAPITest
def test_cublas_config_nondeterministic_alert(self, device):
test_cases = [
# (function, (tensor sizes))
('mm', ((2, 2), (2, 2),)),
('mv', ((2, 2), (2,),)),
('bmm', ((1, 2, 2), (1, 2, 2),))]
test_configs = [
# (CuBLAS workspace config, is deterministic)
('garbage', False),
(None, False),
(':4096:8', True),
(':16:8', True)]
cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG'
is_cuda10_2_or_higher = (
(torch.version.cuda is not None)
and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2]))
def test_case_info(fn_name, config):
return f'function "{fn_name}" with config "{"" if config is None else config}"'
# Create processes to test each combination of test cases and config settings
processes = []
for fn_name, arg_sizes in test_cases:
for config, is_config_deterministic in test_configs:
env = os.environ.copy()
if config is None:
if env.get(cublas_var_name) is not None:
del env[cublas_var_name]
else:
env[cublas_var_name] = config
should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic
script = f"""
import torch
torch.use_deterministic_algorithms(True)
fn = torch.{fn_name}
arg_sizes = {arg_sizes}
device = '{device}'
should_throw_error = {should_throw_error}
args = []
for arg_size in arg_sizes:
args.append(torch.randn(*arg_size, device=device))
try:
fn(*args)
except RuntimeError as e:
if not should_throw_error:
raise RuntimeError('Did not expect any error to be raised')
elif 'Deterministic behavior was enabled with either' not in str(e):
raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error')
else:
if should_throw_error:
raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised')
"""
try:
subprocess.check_output(
[sys.executable, '-c', script],
stderr=subprocess.STDOUT,
# On Windows, opening the subprocess with the default CWD makes `import torch`
# fail, so just set CWD to this script's directory
cwd=os.path.dirname(os.path.realpath(__file__)),
env=env)
except subprocess.CalledProcessError as e:
self.fail(msg=(
f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\n'
+ e.output.decode("utf-8")))