forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_cuda.py
3000 lines (2494 loc) · 116 KB
/
test_cuda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import tempfile
import unittest
import sys
from itertools import repeat
import os
from contextlib import contextmanager
import threading
import math
if sys.version_info[0] == 3:
import queue
else:
import Queue as queue
import torch
import torch.cuda
import torch.cuda.comm as comm
from torch import multiprocessing as mp
from torch._six import inf, nan
from test_torch import _TestTorchMixin
from common_methods_invocations import tri_tests_args, tri_large_tests_args, \
_compare_trilu_indices, _compare_large_trilu_indices
from common_utils import TestCase, get_gpu_type, to_gpu, freeze_rng_state, run_tests, \
PY3, IS_WINDOWS, NO_MULTIPROCESSING_SPAWN, skipIfRocm, TEST_NUMPY, TEST_WITH_ROCM, \
load_tests, slowTest, skipCUDANonDefaultStreamIf
# load_tests from common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
# We cannot import TEST_CUDA and TEST_MULTIGPU from common_cuda here,
# because if we do that, the TEST_CUDNN line from common_cuda will be executed
# multiple times as well during the execution of this test suite, and it will
# cause CUDA OOM error on Windows.
TEST_CUDA = torch.cuda.is_available()
TEST_MULTIGPU = TEST_CUDA and torch.cuda.device_count() >= 2
if not TEST_CUDA:
print('CUDA not available, skipping tests')
TestCase = object # noqa: F811
TEST_MAGMA = TEST_CUDA
TEST_LARGE_TENSOR = TEST_CUDA
if TEST_CUDA:
torch.ones(1).cuda() # has_magma shows up after cuda is initialized
TEST_MAGMA = torch.cuda.has_magma
TEST_LARGE_TENSOR = torch.cuda.get_device_properties(0).total_memory >= 12e9
floating_set = {torch.FloatTensor, torch.DoubleTensor, torch.cuda.FloatTensor,
torch.cuda.DoubleTensor, torch.HalfTensor, torch.cuda.HalfTensor}
def is_floating(t):
if not isinstance(t, type):
raise TypeError('t should be an instance of type')
assert t != torch.autograd.Variable
return t in floating_set
def is_half(t):
if isinstance(t, torch.Tensor):
return t.dtype == torch.float16
assert isinstance(t, type)
assert t != torch.autograd.Variable
return t in [torch.HalfTensor, torch.cuda.HalfTensor]
types = [
torch.FloatTensor,
torch.DoubleTensor,
torch.LongTensor,
torch.IntTensor,
torch.ShortTensor,
torch.CharTensor,
torch.ByteTensor,
torch.HalfTensor,
]
signed_types = [
torch.FloatTensor,
torch.DoubleTensor,
torch.LongTensor,
torch.IntTensor,
torch.ShortTensor,
torch.CharTensor,
]
unsigned_types = [
torch.ByteTensor,
]
float_types = [
torch.FloatTensor,
torch.DoubleTensor,
torch.HalfTensor,
]
float_types_no_half = [
torch.FloatTensor,
torch.DoubleTensor,
]
def number(floating, integer, t):
return floating if is_floating(t) else integer
def cast_tensor(tensor, t):
return t(tensor.size()).copy_(tensor)
S = 10
M = 50
G = 275000000
def make_tensor(t, *sizes):
if 'Half' in t.__name__:
return t(*sizes).copy_(torch.randn(*sizes))
else:
tensor = t(*sizes)
if tensor.is_floating_point():
return tensor.normal_()
else:
return tensor.random_(0, 10)
def make_sparse_tensor(t, n, *sizes):
assert t.is_sparse
tensor = t()
i = tensor._indices()
i = i.new(len(sizes), n).copy_(
torch.cat([torch.LongTensor(1, n).random_(s) for s in sizes], 0))
v = tensor._values()
v = v.new(n).copy_(torch.randn(n))
return t(i, v, torch.Size(sizes))
def tensor_clamp(t, min, max):
if is_half(t):
return t.float().clamp(min, max).half()
else:
return t.clamp(min, max)
def tensor_mul(t, scale):
if is_half(t):
return t.float().mul(scale).half()
else:
return t.mul(scale)
def tensor_abs_(t):
if is_half(t):
return t.float().abs_().half()
else:
return t.abs_()
def constant_tensor_sub(a, b):
# helper function to address const - torch.HalfTensor where it doesn't
# have resize_as()
if is_half(b):
return (a - b.float()).half()
else:
return a - b
def constant_tensor_add(a, b):
# helper function to address const + torch.HalfTensor where it doesn't
# have add()
if is_half(b):
return (a + b.float()).half()
else:
return a + b
def small_0d(t):
return make_tensor(t, (1,)).squeeze()
def small_2d(t):
return make_tensor(t, S, S)
def small_2d_scaled(t, scale=10):
return tensor_mul(make_tensor(t, S, S), scale)
def small_2d_oneish(t):
if is_floating(t):
return tensor_clamp(make_tensor(t, S, S), min=0.99, max=1.01)
else:
return t(S, S).fill_(1)
def small_3d(t):
return make_tensor(t, S, S, S)
def medium_1d(t):
return make_tensor(t, M)
def medium_2d(t):
return make_tensor(t, M, M)
def medium_2d_expanded(t):
return t(1).expand(M, M)
def medium_2d_scaled(t, scale=10):
return tensor_mul(make_tensor(t, M, M), scale)
def small_3d_ones(t):
return t(S, S, S).copy_(torch.ones(S, S, S))
def small_3d_positive(t):
# In div_tensor(), half cannot achieve float precision
min_val = 1e-3 if is_floating(t) and not is_half(t) else 2
return tensor_clamp(make_tensor(t, S, S, S), min_val, 120)
def small_3d_unique(t):
return t(S, S, S).copy_(torch.arange(1, S * S * S + 1).view(S, S, S))
def small_1d_lapack(t):
return t(1, 3).copy_(torch.arange(1, 4).view(3))
def small_2d_lapack(t):
return t(3, 3).copy_(torch.arange(1, 10).view(3, 3))
def small_2d_lapack_skinny(t):
return t(3, 4).copy_(torch.arange(1, 13).view(3, 4))
def small_2d_lapack_fat(t):
return t(4, 3).copy_(torch.arange(1, 13).view(4, 3))
def large_2d_lapack(t):
return t(1000, 1000).normal_()
def giant_1d_ones(t):
return t(G).copy_(torch.ones(G))
def long_type(t):
return torch.cuda.LongTensor if 'cuda' in t.__module__ else torch.LongTensor
def new_t(*sizes):
def tmp(t):
return t(*sizes).copy_(torch.randn(*sizes))
return tmp
# Content of each tuple:
# - function name
# - constructor for the tensor, signature: fn(tensor_type) -> tensor
# - constructor for the arguments, signature: fn(tensor_type) -> list
# - postfix name for the test (must be unique for a given function) (default='')
# - tensor types to use (default=types)
# - disable inplace test, if set to True, no inplace test will be done (default=False)
# - decorator, e.g., unittest.skipIf (default is no decorator)
tests = [
('add', small_3d, lambda t: [number(3.14, 3, t)]),
('add', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('add', small_3d, lambda t: [number(0.2, 2, t), small_3d_positive(t)], 'scalar_tensor'),
('sub', small_3d, lambda t: [number(3.14, 3, t)]),
('sub', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('mul', small_3d, lambda t: [number(3.14, 3, t)]),
('mul', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('mul', small_0d, lambda t: [small_0d(torch.IntTensor)], 'scalar', types, True),
('div', small_3d, lambda t: [number(3.14, 3, t)]),
('div', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('pow', small_3d, lambda t: [number(3.14, 3, t)], None, float_types),
('pow', small_3d, lambda t: [number(1., 1, t)], 'pow1'),
('pow', small_3d, lambda t: [number(2., 2, t)], 'pow2'),
('pow', small_3d, lambda t: [number(3., 3, t)], 'pow3'),
('pow', small_3d, lambda t: [number(-1., -1, t)], 'pow-1', float_types),
# HalfTensor gives bad result at pow-2 with data sampled from torch.randn
('pow', small_3d, lambda t: [number(-2., -2, t)], 'pow-2', float_types_no_half, False,
"skipIfRocm:FloatTensor"),
('pow', small_3d, lambda t: [tensor_abs_(small_3d(t))], 'tensor', float_types),
('addbmm', small_2d, lambda t: [small_3d(t), small_3d(t)], None, float_types),
('addbmm', small_2d, lambda t: [number(0.4, 2, t), small_3d(t), small_3d(t)], 'scalar'),
('addbmm', small_2d, lambda t: [number(0.5, 3, t), number(0.4, 2, t), small_3d(t), small_3d(t)], 'two_scalars'),
('baddbmm', small_3d, lambda t: [small_3d(t), small_3d(t)],),
('baddbmm', small_3d, lambda t: [number(0.4, 2, t), small_3d(t), small_3d(t)], 'scalar'),
('baddbmm', small_3d, lambda t: [number(0.5, 3, t), number(0.4, 2, t), small_3d(t), small_3d(t)], 'two_scalars'),
('bmm', small_3d, lambda t: [small_3d(t)], '', float_types_no_half),
('addcdiv', small_2d_lapack, lambda t: [tensor_mul(small_2d_lapack(t), 2), small_2d_lapack(t)]),
('addcdiv', small_2d_lapack, lambda t: [number(2.8, 1, t), tensor_mul(small_2d_lapack(t), 2), small_2d_lapack(t)],
'scalar'),
('addcmul', small_3d, lambda t: [small_3d(t), small_3d(t)]),
('addcmul', small_3d, lambda t: [number(0.4, 2, t), small_3d(t), small_3d(t)], 'scalar'),
('addmm', medium_2d, lambda t: [medium_2d(t), medium_2d(t)]),
('addmm', medium_2d, lambda t: [number(0.4, 2, t), medium_2d(t), medium_2d(t)], 'scalar'),
('addmm', medium_2d, lambda t: [number(0.5, 3, t), number(0.4, 2, t), medium_2d(t), medium_2d(t)], 'two_scalars'),
('addmv', medium_1d, lambda t: [medium_2d(t), medium_1d(t)],),
('addmv', medium_1d, lambda t: [number(0.4, 2, t), medium_2d(t), medium_1d(t)], 'scalar'),
('addmv', medium_1d, lambda t: [number(0.5, 3, t), number(0.4, 2, t), medium_2d(t), medium_1d(t)], 'two_scalars'),
('addr', medium_2d, lambda t: [medium_1d(t), medium_1d(t)]),
('addr', medium_2d, lambda t: [number(0.4, 2, t), medium_1d(t), medium_1d(t)], 'scalar'),
('addr', medium_2d, lambda t: [number(0.5, 3, t), number(0.4, 2, t), medium_1d(t), medium_1d(t)], 'two_scalars'),
('atan2', medium_2d, lambda t: [medium_2d(t)], None, float_types + [torch.HalfTensor]),
('fmod', small_3d, lambda t: [3], 'value',),
('fmod', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('chunk', medium_2d, lambda t: [4],),
('chunk', medium_2d, lambda t: [4, 1], 'dim'),
('chunk', medium_2d, lambda t: [4, -2], 'neg_dim'),
('clamp', medium_2d_scaled, lambda t: [-1, 5], None, signed_types),
('clamp', medium_2d_scaled, lambda t: [1, 5], None, unsigned_types),
('clone', medium_2d, lambda t: [],),
('contiguous', medium_2d, lambda t: [],),
('cross', new_t(M, 3, M), lambda t: [new_t(M, 3, M)(t)],),
('cumprod', small_3d, lambda t: [1]),
('cumprod', small_3d, lambda t: [-1], 'neg_dim'),
('cumsum', small_3d, lambda t: [1]),
('cumsum', small_3d, lambda t: [-1], 'neg_dim'),
('dim', small_3d, lambda t: [],),
('dist', small_2d, lambda t: [small_2d(t)]),
('dist', small_2d, lambda t: [small_2d(t), 3], '3_norm'),
('dist', small_2d, lambda t: [small_2d(t), 2.5], '2_5_norm'),
('dot', medium_1d, lambda t: [medium_1d(t)], '', types, False, "skipIfRocm:HalfTensor"),
('element_size', medium_1d, lambda t: [],),
('eq', small_3d_ones, lambda t: [small_3d(t)],),
('eq', small_3d_ones, lambda t: [small_3d_ones(t)], 'equal'),
('ne', small_3d_ones, lambda t: [small_3d(t)],),
('ne', small_3d_ones, lambda t: [small_3d_ones(t)], 'equal'),
('equal', small_3d_ones, lambda t: [small_3d_ones(t)], 'equal'),
('equal', small_3d_ones, lambda t: [small_3d(t)],),
('expand', new_t(M, 1, M), lambda t: [M, 4, M],),
('expand_as', new_t(M, 1, M), lambda t: [new_t(M, 4, M)(t)],),
('fill', medium_2d, lambda t: [number(3.14, 3, t)]),
('ge', medium_2d, lambda t: [medium_2d(t)],),
('le', medium_2d, lambda t: [medium_2d(t)],),
('gt', medium_2d, lambda t: [medium_2d(t)],),
('lt', medium_2d, lambda t: [medium_2d(t)],),
('is_contiguous', medium_2d, lambda t: [],),
# TODO: can't check negative case - GPU copy will be contiguous
('is_same_size', medium_2d, lambda t: [small_3d(t)], 'negative'),
('is_same_size', medium_2d, lambda t: [medium_2d(t)], 'positive'),
('is_set_to', medium_2d, lambda t: [medium_2d(t)],),
# TODO: positive case
('kthvalue', small_3d_unique, lambda t: [3],),
('kthvalue', small_3d_unique, lambda t: [3, 1], 'dim'),
('kthvalue', small_3d_unique, lambda t: [3, -1], 'neg_dim'),
('lerp', small_3d, lambda t: [small_3d(t), 0.3]),
('max', small_3d_unique, lambda t: []),
('max', small_3d_unique, lambda t: [1], 'dim'),
('max', small_3d_unique, lambda t: [-1], 'neg_dim'),
('max', medium_2d, lambda t: [medium_2d(t)], 'elementwise'),
('min', small_3d_unique, lambda t: []),
('min', small_3d_unique, lambda t: [1], 'dim'),
('min', small_3d_unique, lambda t: [-1], 'neg_dim'),
('min', medium_2d, lambda t: [medium_2d(t)], 'elementwise'),
('mean', small_3d, lambda t: []),
('mean', small_3d, lambda t: [-1], 'neg_dim'),
('mean', small_3d, lambda t: [1], 'dim'),
('mean', giant_1d_ones, lambda t: [], '64bit_indexing',
# Double here because otherwise the CPU result will be
# wrong.
[torch.DoubleTensor]),
('mode', small_3d, lambda t: []),
('mode', small_3d, lambda t: [1], 'dim'),
('mode', small_3d, lambda t: [-1], 'neg_dim'),
('mvlgamma', lambda t: tensor_clamp(small_2d(t), 0.1, 10), lambda t: [1], '2d_p=1', float_types_no_half),
('mvlgamma', lambda t: tensor_clamp(small_2d(t), 0.6, 10), lambda t: [2], '2d_p=2', float_types_no_half),
('remainder', small_3d, lambda t: [3], 'value',),
('remainder', small_3d, lambda t: [-3], 'negative_value', signed_types),
('remainder', small_3d, lambda t: [small_3d_positive(t)], 'tensor'),
('remainder', small_3d, lambda t: [constant_tensor_sub(0, small_3d_positive(t))], 'negative_tensor', signed_types),
('std', small_3d, lambda t: []),
('std', small_3d, lambda t: [1], 'dim', types, False),
('std', small_3d, lambda t: [-1], 'neg_dim', types, False),
('var', small_3d, lambda t: []),
('var', small_3d, lambda t: [1], 'dim'),
('var', small_3d, lambda t: [-1], 'neg_dim'),
('ndimension', small_3d, lambda t: [],),
('nelement', small_3d, lambda t: [],),
('numel', small_3d, lambda t: [],),
('narrow', small_3d, lambda t: [1, 3, 2],),
('narrow', small_3d, lambda t: [-1, 3, 2], 'neg_dim'),
('nonzero', small_3d, lambda t: [], '', types, False),
('norm', small_3d, lambda t: []),
('norm', small_3d, lambda t: [3], '3_norm'),
('norm', small_3d, lambda t: [3, 0], '3_norm_dim'),
('norm', small_3d, lambda t: [3, -2], '3_norm_neg_dim'),
('ones', small_3d, lambda t: [1, 2, 3, 4, 5],),
('permute', new_t(1, 2, 3, 4), lambda t: [2, 1, 3, 0],),
('put_', new_t(2, 5, 3), lambda t: [long_type(t)([[0], [-2]]), t([[3], [4]])], '', types, False),
('put_', new_t(2, 3), lambda t: [long_type(t)([]), t([])], 'empty'),
('put_', new_t(2, 2), lambda t: [long_type(t)([[1], [-3]]), t([[1], [2]]), True], 'accumulate'),
('prod', small_2d_oneish, lambda t: []),
('prod', small_3d, lambda t: [1], 'dim'),
('prod', small_3d, lambda t: [-1], 'neg_dim'),
('sum', small_2d, lambda t: []),
('sum', small_3d, lambda t: [1], 'dim'),
('sum', small_3d, lambda t: [-1], 'neg_dim'),
('renorm', small_3d, lambda t: [2, 1, 1], '2_norm'),
('renorm', small_3d, lambda t: [2, -1, 1], '2_norm_neg_dim'),
('renorm', small_3d, lambda t: [1.5, 1, 1], '1_5_norm'),
('repeat', small_2d, lambda t: [2, 2, 2],),
('size', new_t(1, 2, 3, 4), lambda t: [],),
('size', new_t(1, 2, 3, 4), lambda t: [1], 'dim'),
('size', new_t(1, 2, 3, 4), lambda t: [-2], 'neg_dim'),
('sort', small_3d_unique, lambda t: [], ''),
('sort', small_3d_unique, lambda t: [1], 'dim'),
('sort', small_3d_unique, lambda t: [-1], 'neg_dim'),
('sort', small_3d_unique, lambda t: [1, True], 'dim_descending'),
('sort', small_3d_unique, lambda t: [-1, True], 'neg_dim_descending'),
('split', small_3d, lambda t: [2],),
('split', small_3d, lambda t: [2, 1], 'dim'),
('split', small_3d, lambda t: [2, -3], 'neg_dim'),
('squeeze', new_t(1, 2, 1, 4), lambda t: [],),
('squeeze', new_t(1, 2, 1, 4), lambda t: [2], 'dim'),
('squeeze', new_t(1, 2, 1, 4), lambda t: [-2], 'neg_dim'),
('t', new_t(1, 2), lambda t: [],),
('take', new_t(3, 4), lambda t: [long_type(t)([[0], [-2]])], '', types, False),
('transpose', new_t(1, 2, 3, 4), lambda t: [1, 2],),
('transpose', new_t(1, 2, 3, 4), lambda t: [-1, -2], 'neg_dim'),
('to_list', small_3d, lambda t: [],),
('topk', small_3d_unique, lambda t: [2, 1, False, True], 'dim_sort',),
('topk', small_3d_unique, lambda t: [2, -1, False, True], 'neg_dim_sort',),
('topk', small_3d_unique, lambda t: [2, 1, True, True], 'dim_desc_sort',),
('trace', medium_2d, lambda t: []),
('tril', medium_2d, lambda t: [],),
('tril', medium_2d_expanded, lambda t: [], 'zero_stride', types, True),
('tril', medium_2d, lambda t: [2], 'positive'),
('tril', medium_2d, lambda t: [-2], 'negative'),
('triu', medium_2d, lambda t: [],),
('triu', medium_2d_expanded, lambda t: [], 'zero_stride', types, True),
('triu', medium_2d, lambda t: [2], 'positive'),
('triu', medium_2d, lambda t: [-2], 'negative'),
('unsqueeze', new_t(2, 3, 4), lambda t: [2],),
('unsqueeze', new_t(2, 3, 4), lambda t: [-2], 'neg_dim'),
('view', small_3d, lambda t: [100, 10], 'contiguous'),
('view_as', small_3d, lambda t: [make_tensor(t, 100, 10)],),
('zero', small_3d, lambda t: [],),
('zeros', small_3d, lambda t: [1, 2, 3, 4],),
('eye', small_2d, lambda t: [3, 4],),
('flip', small_3d, lambda t: [0], 'd0', types, True),
('flip', small_3d, lambda t: [0, 1, 2], 'd012', types, True),
('flip', small_3d, lambda t: [0, 2], 'd02', types, True),
('flip', small_3d, lambda t: [2, 0], 'd20', types, True),
('flip', small_3d, lambda t: [-1], 'neg_d', types, True),
('rot90', small_2d, lambda t: [1, [0, 1]], 'k1_d01', types, True),
('rot90', small_3d, lambda t: [1, [1, 2]], 'k1_d12', types, True),
('rot90', small_3d, lambda t: [1, [1, -1]], 'k1_neg_d', types, True),
('rot90', small_3d, lambda t: [], 'default', types, True),
('rsqrt', lambda t: constant_tensor_add(1, small_3d(t)), lambda t: [], None, float_types),
('sinh', lambda t: tensor_clamp(small_3d(t), -1, 1), lambda t: [], None, float_types),
('tan', lambda t: tensor_clamp(small_3d(t), -1, 1), lambda t: [], None, float_types),
('__lshift__', lambda t: torch.pow(2, cast_tensor(torch.arange(1, 5), t)),
lambda t: [2], None, signed_types),
('__rshift__', lambda t: torch.pow(2, cast_tensor(torch.arange(3, 7), t)),
lambda t: [2], None, signed_types),
# lapack tests
('qr', small_2d_lapack, lambda t: [], 'square', float_types, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('qr', small_2d_lapack_skinny, lambda t: [], 'skinny', float_types, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('qr', small_2d_lapack_fat, lambda t: [], 'fat', float_types, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('qr', large_2d_lapack, lambda t: [], 'big', float_types, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('geqrf', new_t(20, 20), lambda t: [], None, float_types, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', new_t(10, 10), lambda t: [], 'square', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', lambda t: new_t(10, 10)(t).t(), lambda t: [True], 'square_col_maj',
float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', new_t(20, 5), lambda t: [True], 'tall_some', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', new_t(20, 5), lambda t: [False], 'tall_all', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', lambda t: new_t(5, 20)(t).t(), lambda t: [True],
'tall_some_col_maj', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('svd', lambda t: new_t(5, 20)(t).t(), lambda t: [False],
'tall_all_col_maj', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
('eig', new_t(10, 10), lambda t: [True], 'with_eigvec', float_types_no_half, False,
unittest.skipIf(not TEST_MAGMA, "no MAGMA library detected")),
]
# TODO: random functions, cat, gather, scatter, index*, masked*,
# resize, resizeAs, storage_offset, storage, stride, unfold
custom_precision = {
'addbmm': 1e-4,
'addmm': 1e-4,
'addmv': 1e-4,
'addr': 1e-4,
'baddbmm': 1e-4,
'rsqrt': 1e-4,
'cumprod': 1e-4,
'qr': 3e-4,
'digamma': 1e0, # large values lead to large absolute error but small relative error
}
custom_half_precision = {
'add': 1e-2,
'acos': 1e-3,
'addbmm': 1e-1,
'addcdiv': 1e-2,
'addcmul': 1e-2,
'addmm': 1e-1,
'addmv': 1e-2,
'addr': 1e-2,
'asin': 1e-3,
'atan2': 1e-3,
'atan': 1e-3,
'baddbmm': 1e-2,
'cos': 1e-3,
'cosh': 1e-2,
'cross': 1e-2,
'cumprod': 1e-2,
'cumsum': 1e-2,
'dist': 1e-2,
'div': 1e-3,
'dot': 1e-2,
'erf': 1e-3,
'erfc': 1e-3,
'erfinv': 1e-3,
'exp': 1e-2,
'expm1': 1e-2,
'fill': 1e-3,
'lerp': 1e-2,
'lgamma': 1e-2,
'log': 1e-2,
'log10': 1e-2,
'log1p': 1e-3,
'log2': 1e-2,
'mean': 1e-3,
'mul': 1e-2,
'norm': 1e-1,
'pow': 1e-1,
'prod': 1e-3,
'reciprocal': 1e-1,
'remainder': 1e-3,
'renorm': 1e-3,
'rsqrt': 1e-2,
'sigmoid': 1e-3,
'sin': 1e-3,
'sinh': 1e-3,
'sqrt': 1e-3,
'std': 1e-3,
'sub': 1e-2,
'sum': 1e-2,
'tan': 1e-3,
'tanh': 1e-3,
'trace': 1e-3,
'var': 1e-3,
'__lshift__': 1e-3,
'__rshift__': 1e-3,
}
simple_pointwise = [
'abs',
'sign',
]
for fn in simple_pointwise:
tests.append((fn, small_3d, lambda t: []))
simple_pointwise_float = [
'log',
'log10',
'log1p',
'log2',
'sigmoid',
'sin',
'sqrt',
'tanh',
'acos',
'asin',
'atan',
'cos',
'cosh',
'erf',
'erfc',
'erfinv',
'exp',
'expm1',
'reciprocal',
'floor',
'frac',
'neg',
'round',
'trunc',
'ceil',
'lgamma',
'digamma',
'trigamma',
]
for fn in simple_pointwise_float:
tests.append((fn, small_3d, lambda t: [], None, float_types))
_cycles_per_ms = None
def get_cycles_per_ms():
"""Approximate number of cycles per millisecond for torch.cuda._sleep"""
global _cycles_per_ms
if _cycles_per_ms is None:
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
torch.cuda._sleep(1000000)
end.record()
end.synchronize()
_cycles_per_ms = 1000000 / start.elapsed_time(end)
return _cycles_per_ms
def compare_cpu_gpu(tensor_constructor, arg_constructor, fn, t, precision=1e-5):
def tmp(self):
cpu_tensor = tensor_constructor(t)
gpu_tensor = to_gpu(cpu_tensor)
cpu_args = arg_constructor(t)
gpu_args = [to_gpu(arg) for arg in cpu_args]
if is_half(t):
cpu_tensor = cpu_tensor.float()
cpu_args = [arg.float() if isinstance(arg, torch.Tensor) and is_half(arg) else arg for arg in cpu_args]
cpu_result = getattr(cpu_tensor, fn)(*cpu_args)
try:
gpu_result = getattr(gpu_tensor, fn)(*gpu_args)
except RuntimeError as e:
reason = e.args[0]
data_type_reasons = {'only supports floating-point types',
'unimplemented data type',
'not implemented for'}
if any(data_type_reason in reason for data_type_reason in data_type_reasons):
raise unittest.SkipTest('unimplemented data type')
raise
except AttributeError as e:
reason = e.args[0]
if 'object has no attribute' in reason:
raise unittest.SkipTest('unimplemented data type')
raise
# If one changes, another should change as well
self.assertEqual(cpu_tensor, gpu_tensor, precision)
self.assertEqual(cpu_args, gpu_args, precision)
# Compare results
if fn == 'element_size' and t.__name__ == 'HalfTensor':
# Workaround since cpu_result is float
self.assertEqual(2, gpu_result)
else:
self.assertEqual(cpu_result, gpu_result, precision)
return tmp
class TestCuda(TestCase):
_do_cuda_memory_leak_check = True
# See https://github.com/pytorch/pytorch/issues/21589
# We used to have this turned on for the tests in this file which
# we had tested to be OK, but when people added new tests to
# this file, it would trigger nondeterministic failures that
# are hard to debug. Since there are KNOWN bugs with our
# stream handling, we shouldn't turn this on by default.
# If you decide to make this True, be sure to run the test suite
# under cuda-memcheck
_do_cuda_non_default_stream = False
FIFTY_MIL_CYCLES = 50000000
@staticmethod
def _test_memory_stats_generator(self, device=None, N=35):
if device is None:
device = torch.cuda.current_device()
m0 = torch.cuda.memory_allocated(device)
last_m_arr = [torch.cuda.memory_allocated(device)]
max_m_arr = [torch.cuda.max_memory_allocated(device)]
last_c_arr = [torch.cuda.memory_cached(device)]
max_c_arr = [torch.cuda.max_memory_cached(device)]
def alloc(*size):
with torch.cuda.device(device):
# NOTE: do **not** use methods that can have additional
# memory overhead, e.g., inplace random sampling methods.
# they can leave some memory occupied even after being
# deallocated, e.g., initialized RNG state, causing some
# memory checks below to fail.
return torch.cuda.FloatTensor(*size)
def assert_change(comp=1, empty_cache=False, reset_max_alloc=False, reset_max_cached=False):
# comp > 0: increased
# comp = 0: equal
# comp < 0: decreased
new_m = torch.cuda.memory_allocated(device)
new_max_m = torch.cuda.max_memory_allocated(device)
if comp > 0:
self.assertGreater(new_m, last_m_arr[0])
elif comp < 0:
self.assertLess(new_m, last_m_arr[0])
else:
self.assertEqual(new_m, last_m_arr[0])
self.assertLessEqual(new_m, new_max_m)
self.assertGreaterEqual(new_max_m, max_m_arr[0])
last_m_arr[0] = new_m
max_m_arr[0] = new_max_m
new_c = torch.cuda.memory_cached(device)
new_max_c = torch.cuda.max_memory_cached(device)
# emptying cache may happen (due to allocation or empty_cache), so
# we can't assert new_c >= last_c
self.assertLessEqual(new_c, new_max_c)
self.assertGreaterEqual(new_max_c, max_c_arr[0])
last_c_arr[0] = new_c
max_c_arr[0] = new_max_c
if empty_cache:
torch.cuda.empty_cache()
new_c = torch.cuda.memory_cached(device)
new_max_c = torch.cuda.max_memory_cached(device)
self.assertLessEqual(new_c, last_c_arr[0])
self.assertLessEqual(new_c, new_max_c)
self.assertEqual(new_max_c, max_c_arr[0])
last_c_arr[0] = new_c
if reset_max_alloc:
torch.cuda.reset_max_memory_allocated(device)
self.assertEqual(torch.cuda.memory_allocated(device), last_m_arr[0])
self.assertEqual(torch.cuda.max_memory_allocated(device), last_m_arr[0])
max_m_arr[0] = last_m_arr[0]
self.assertEqual(torch.cuda.memory_cached(device), last_c_arr[0])
self.assertEqual(torch.cuda.max_memory_cached(device), max_c_arr[0])
if reset_max_cached:
torch.cuda.reset_max_memory_cached(device)
self.assertEqual(torch.cuda.memory_allocated(device), last_m_arr[0])
self.assertEqual(torch.cuda.max_memory_allocated(device), max_m_arr[0])
self.assertEqual(torch.cuda.memory_cached(device), last_c_arr[0])
self.assertEqual(torch.cuda.max_memory_cached(device), last_c_arr[0])
max_c_arr[0] = last_c_arr[0]
assert_change(0)
assert_change(0, reset_max_alloc=True)
assert_change(0, empty_cache=True)
assert_change(0, reset_max_cached=True)
assert_change(0)
yield
tensors1 = [alloc(1), alloc(10, 20), alloc(200, 300, 2000)]
m1 = torch.cuda.memory_allocated(device)
assert_change(1)
yield
tensors2 = []
for i in range(1, int(N / 2) + 1):
# small ones
tensors2.append(alloc(i, i * 4))
assert_change(1)
yield
for i in range(5, int(N / 2) + 5):
# large ones
tensors2.append(alloc(i, i * 7, i * 9, i * 11))
assert_change(1, reset_max_alloc=(i % 2 == 0), reset_max_cached=(i % 2 == 1))
yield
tensors2.append(alloc(0, 0, 0))
assert_change(0)
yield
permute = []
for i in torch.randperm(len(tensors2)):
permute.append(tensors2[i])
assert_change(0)
yield
del tensors2
assert_change(0)
yield
tensors2 = permute
assert_change(0)
yield
del permute
assert_change(0, reset_max_alloc=True)
yield
for i in range(int(N / 2)):
x = tensors2[i].numel()
del tensors2[i]
assert_change(-x) # in case that tensors2[i] is empty
yield
for i in range(2, int(2 * N / 3) + 2):
tensors2.append(alloc(i, i * 3, i * 8))
assert_change(1)
yield
del tensors2
assert_change(-1, reset_max_cached=True)
assert_change(0)
self.assertEqual(torch.cuda.memory_allocated(device), m1)
yield True
del tensors1
assert_change(-1, reset_max_alloc=True)
self.assertEqual(torch.cuda.memory_allocated(device), m0)
# test empty_cache and reset_max_memory_*
assert_change(0, empty_cache=True)
assert_change(0, reset_max_cached=True)
assert_change(0, reset_max_alloc=True)
def test_memory_stats(self):
torch.cuda.empty_cache()
for _ in self._test_memory_stats_generator(self):
pass
def test_cuda_get_device_name(self):
# Testing the behaviour with None as an argument
current_device = torch.cuda.current_device()
current_device_name = torch.cuda.get_device_name(current_device)
device_name_None = torch.cuda.get_device_name(None)
self.assertEqual(current_device_name, device_name_None)
# Testing the behaviour for No argument
device_name_no_argument = torch.cuda.get_device_name()
self.assertEqual(current_device_name, device_name_no_argument)
def test_cuda_get_device_capability(self):
# Testing the behaviour with None as an argument
current_device = torch.cuda.current_device()
current_device_capability = torch.cuda.get_device_capability(current_device)
device_capability_None = torch.cuda.get_device_capability(None)
self.assertEqual(current_device_capability, device_capability_None)
# Testing the behaviour for No argument
device_capability_no_argument = torch.cuda.get_device_capability()
self.assertEqual(current_device_capability, device_capability_no_argument)
@unittest.skipIf(not TEST_MULTIGPU, "only one GPU detected")
def test_memory_stats_multigpu(self):
# advance a generator with a end flag
def advance(gen, end):
if not end:
try:
next(gen)
except StopIteration:
end = True
return end
# interlace
torch.cuda.empty_cache()
gen0 = self._test_memory_stats_generator(self, device='cuda:0', N=35)
gen1 = self._test_memory_stats_generator(self, device=torch.device('cuda:1'), N=35)
end0 = end1 = False
while not (end0 and end1):
end0 = advance(gen0, end0)
end1 = advance(gen1, end1)
# semi-random order
torch.cuda.empty_cache()
gen0 = self._test_memory_stats_generator(self, device=0, N=35)
gen1 = self._test_memory_stats_generator(self, device=torch.device('cuda:1'), N=35)
end0 = end1 = False
while not (end0 and end1):
end0 = advance(gen0, end0)
if not end0:
gen1_max_times = torch.LongTensor(1).random_(0, 3)[0]
else:
gen1_max_times = inf
t = 0
while t < gen1_max_times and not end1:
end1 = advance(gen1, end1)
t += 1
def test_out_of_memory(self):
tensor = torch.zeros(1024, device='cuda')
with self.assertRaisesRegex(RuntimeError, "Tried to allocate 80.00 GiB"):
torch.empty(1024 * 1024 * 1024 * 80, dtype=torch.int8, device='cuda')
# ensure out of memory error doesn't disturb subsequent kernel
tensor.fill_(1)
self.assertTrue((tensor == 1).all())
@unittest.skipIf(not TEST_MULTIGPU, "only one GPU detected")
def test_autogpu(self):
x = torch.randn(5, 5).cuda()
y = torch.randn(5, 5).cuda()
self.assertEqual(x.get_device(), 0)
self.assertEqual(x.get_device(), 0)
with torch.cuda.device(1):
z = torch.randn(5, 5).cuda()
self.assertEqual(z.get_device(), 1)
q = x.add(y)
self.assertEqual(q.get_device(), 0)
w = torch.randn(5, 5).cuda()
self.assertEqual(w.get_device(), 1)
self.assertEqual(y.cuda().get_device(), 1)
z = z.cuda()
self.assertEqual(z.get_device(), 0)
@unittest.skipIf(not TEST_MULTIGPU, "only one GPU detected")
def test_new(self):
x = torch.randn(3, 3).cuda()
self.assertEqual(x.new([0, 1, 2]).get_device(), 0)
self.assertEqual(x.new([0, 1, 2], device=1).get_device(), 1)
with torch.cuda.device(1):
self.assertEqual(x.new([0, 1, 2]).get_device(), 0)
self.assertEqual(x.new([0, 1, 2], device=1).get_device(), 1)
@unittest.skipIf(not TEST_MULTIGPU, "only one GPU detected")
def test_copy_device(self):
x = torch.randn(5, 5).cuda()
with torch.cuda.device(1):
y = x.cuda()
self.assertEqual(y.get_device(), 1)
self.assertIs(y.cuda(), y)
z = y.cuda(0)
self.assertEqual(z.get_device(), 0)
self.assertIs(z.cuda(0), z)
x = torch.randn(5, 5)
with torch.cuda.device(1):
y = x.cuda()
self.assertEqual(y.get_device(), 1)
self.assertIs(y.cuda(), y)
z = y.cuda(0)
self.assertEqual(z.get_device(), 0)
self.assertIs(z.cuda(0), z)
def _test_copy_sync_current_stream(self, x, y):
x_plus_one = x + 1
s0 = torch.cuda.Stream(device=x.device)
s1 = torch.cuda.Stream(device=y.device)
s2 = torch.cuda.Stream(device=x.device)
s3 = torch.cuda.Stream(device=y.device)
# same dst stream different src streams
with torch.cuda.stream(s0):
torch.cuda._sleep(TestCuda.FIFTY_MIL_CYCLES)
with torch.cuda.stream(s1):
y.copy_(x_plus_one)
with torch.cuda.stream(s2), torch.cuda.stream(s1):
y.copy_(x)
s1.synchronize()
# The copy() is synchronized on the current streams of both src and dst.
# In the above test, the _sleep() op on s0 will not block the copy() on
# s2, but both copies are synchronized on s1 in the dst device. Hence,
# x is copied to y after x_plus_one is copied to y. If x and y are on
# the same device, both copy() ops are synchronized on s1.
self.assertEqual(y, x)
# same src stream different dst streams
with torch.cuda.stream(s1):
torch.cuda._sleep(TestCuda.FIFTY_MIL_CYCLES)
with torch.cuda.stream(s0):
y.copy_(x_plus_one)
with torch.cuda.stream(s3), torch.cuda.stream(s0):
y.copy_(x)
s0.synchronize()
# Similarly, both copy() ops are synchronized on s0.
self.assertEqual(y, x)
@unittest.skipIf(not TEST_MULTIGPU, "only one GPU detected")
def test_copy_streams(self):
d0 = torch.device('cuda:0')
x0 = torch.zeros(5, 5, device=d0)
d1 = torch.device('cuda:1')
x1 = torch.zeros(5, 5, device=d1)
self._test_copy_sync_current_stream(x0, x1)
x2 = torch.zeros(5, 5, device=d0)
self._test_copy_sync_current_stream(x0, x2)
def test_copy_non_blocking(self):
def _test_copy_non_blocking(a, b):
event = torch.cuda.Event()
a.copy_(b, non_blocking=True)
event.record()
self.assertFalse(event.query())
event.synchronize()
self.assertEqual(a, b)
# 10MB copies
x = torch.ones(10000000, dtype=torch.uint8).cuda()