/
common_methods_invocations.py
3083 lines (2888 loc) · 161 KB
/
common_methods_invocations.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
from functools import reduce, wraps
from itertools import product
from operator import mul, itemgetter
import collections
import operator
import torch
import numpy as np
from torch._six import inf, istuple
from torch.autograd import Variable
import collections.abc
from typing import List, Tuple, Dict, Any
from torch.testing import \
(make_non_contiguous, _dispatch_dtypes, floating_types, floating_types_and,
floating_and_complex_types, floating_and_complex_types_and,
all_types_and_complex_and, all_types_and, all_types_and_complex)
from torch.testing._internal.common_device_type import \
(skipIf, skipCUDAIfNoMagma, skipCPUIfNoLapack, skipCPUIfNoMkl,
skipCUDAIfRocm, expectedAlertNondeterministic, precisionOverride)
from torch.testing._internal.common_cuda import tf32_is_not_fp32
from torch.testing._internal.common_utils import \
(prod_single_zero, random_square_matrix_of_rank,
random_symmetric_matrix, random_symmetric_psd_matrix,
random_symmetric_pd_matrix, make_nonzero_det,
random_fullrank_matrix_distinct_singular_value, set_rng_seed,
TEST_WITH_ROCM, IS_WINDOWS, IS_MACOS, make_tensor, TEST_SCIPY,
torch_to_numpy_dtype_dict, slowTest)
from distutils.version import LooseVersion
if TEST_SCIPY:
import scipy.special
class DecorateInfo(object):
"""Describes which test, or type of tests, should be wrapped in the given
decorators when testing an operator. Any test that matches all provided
arguments will be decorated. The decorators will only be applied if the
active_if argument is True."""
__slots__ = ['decorators', 'cls_name', 'test_name', 'device_type', 'dtypes', 'active_if']
def __init__(self, decorators, cls_name=None, test_name=None, *,
device_type=None, dtypes=None, active_if=True):
self.decorators = list(decorators) if isinstance(decorators, collections.abc.Sequence) else [decorators]
self.cls_name = cls_name
self.test_name = test_name
self.device_type = device_type
self.dtypes = dtypes
self.active_if = active_if
def is_active(self, cls_name, test_name, device_type, dtype):
return (
self.active_if and
(self.cls_name is None or self.cls_name == cls_name) and
(self.test_name is None or self.test_name == test_name) and
(self.device_type is None or self.device_type == device_type) and
(self.dtypes is None or dtype in self.dtypes)
)
class SkipInfo(DecorateInfo):
"""Describes which test, or type of tests, should be skipped when testing
an operator. Any test that matches all provided arguments will be skipped.
The skip will only be checked if the active_if argument is True."""
def __init__(self, cls_name=None, test_name=None, *,
device_type=None, dtypes=None, active_if=True):
super().__init__(decorators=skipIf(True, "Skipped!"), cls_name=cls_name,
test_name=test_name, device_type=device_type, dtypes=dtypes,
active_if=active_if)
class SampleInput(object):
"""Represents sample inputs to a function."""
# output_process_fn_grad is a function that modifies the output of op compatible with input
__slots__ = ['input', 'args', 'kwargs', 'output_process_fn_grad']
def __init__(self, input, *, args=tuple(), kwargs=None, output_process_fn_grad=None):
# test_ops.py expects input to be a tuple
self.input = input if isinstance(input, tuple) else (input,)
self.args = args
self.kwargs = kwargs if kwargs is not None else {}
self.output_process_fn_grad = output_process_fn_grad
def __repr__(self):
arguments = [
f'input[{len(self.input)}]',
f'args={self.args}' if len(self.args) > 0 else None,
f'kwargs={self.kwargs}' if len(self.kwargs) > 0 else None,
(f'output_process_fn_grad={self.output_process_fn_grad}'
if self.output_process_fn_grad is not None else None)]
return f'SampleInput({", ".join(a for a in arguments if a is not None)})'
_NOTHING = object() # Unique value to distinguish default from anything else
# Extension of getattr to support qualified names
# e.g. _getattr_qual(torch, 'linalg.norm') -> torch.linalg.norm
def _getattr_qual(obj, name, default=_NOTHING):
try:
for path in name.split('.'):
obj = getattr(obj, path)
return obj
except AttributeError:
if default is not _NOTHING:
return default
else:
raise
# Classes and methods for the operator database
class OpInfo(object):
"""Operator information and helper functions for acquiring it."""
def __init__(self,
name, # the string name of the function
*,
op=None, # the function variant of the operation, populated as torch.<name> if None
dtypes=floating_types(), # dtypes this function is expected to work with
dtypesIfCPU=None, # dtypes this function is expected to work with on CPU
dtypesIfCUDA=None, # dtypes this function is expected to work with on CUDA
dtypesIfROCM=None, # dtypes this function is expected to work with on ROCM
default_test_dtypes=None, # dtypes to test with by default. Gets intersected
# with the dtypes support on the tested device
test_inplace_grad=True, # whether to gradcheck and gradgradcheck the inplace variant
test_complex_grad=True, # whether to gradcheck and gradgradcheck for complex dtypes
skip_bfloat16_grad=False, # whether to skip grad and gradgradcheck for bfloat16 dtype
assert_autodiffed=False, # if a op's aten::node is expected to be symbolically autodiffed
autodiff_nonfusible_nodes=None, # a list of strings with node names that are expected to be in a
# DifferentiableGraph when autodiffed. Ex: ['aten::add', 'aten::mm'],
# default is populated to be ['aten::(name of Python operator)']
autodiff_fusible_nodes=None, # a list of strings with node names that are expected to be in FusionGroups
# inside of DifferentiableGraphs when this operation is autodiffed.
# Ex: ['aten::add', 'aten::mm'], defaults to an empty list
# Note: currently no ops use fusible nodes
output_func=lambda x: x, # fn mapping output to part that should be gradcheck'ed
supports_tensor_out=True, # whether the op supports the out kwarg, returning a Tensor
skips=tuple(), # information about which tests to skip
decorators=None, # decorators to apply to generated tests
safe_casts_outputs=False, # whether op allows safe casting when writing to out arguments
sample_inputs_func=None, # function to generate sample inputs
aten_name=None, # name of the corresponding aten:: operator
variant_test_name='', # additional string to include in the test name
supports_sparse=False, # supported for sparse
check_batched_grad=True, # check batched grad when doing gradcheck
check_batched_gradgrad=True, # check batched grad grad when doing gradgradcheck
):
# Validates the dtypes are generated from the dispatch-related functions
for dtype_list in (dtypes, dtypesIfCPU, dtypesIfCUDA, dtypesIfROCM):
assert isinstance(dtype_list, (_dispatch_dtypes, type(None)))
self.name = name
self.aten_name = aten_name if aten_name is not None else name
self.variant_test_name = variant_test_name
self.dtypes = set(dtypes)
self.dtypesIfCPU = set(dtypesIfCPU) if dtypesIfCPU is not None else self.dtypes
self.dtypesIfCUDA = set(dtypesIfCUDA) if dtypesIfCUDA is not None else self.dtypes
self.dtypesIfROCM = set(dtypesIfROCM) if dtypesIfROCM is not None else self.dtypes
self._default_test_dtypes = set(default_test_dtypes) if default_test_dtypes is not None else None
# NOTE: if the op is unspecified it is assumed to be under the torch namespace
self.op = op if op else _getattr_qual(torch, self.name)
self.method_variant = getattr(torch.Tensor, name, None)
inplace_name = name + "_"
self.inplace_variant = getattr(torch.Tensor, inplace_name, None)
self.operator_variant = getattr(operator, name, None)
self.skip_bfloat16_grad = skip_bfloat16_grad
self.test_inplace_grad = test_inplace_grad
self.test_complex_grad = test_complex_grad
self.supports_tensor_out = supports_tensor_out
self.safe_casts_outputs = safe_casts_outputs
self.skips = skips
self.decorators = decorators
self.output_func = output_func
self.sample_inputs_func = sample_inputs_func
self.assert_autodiffed = assert_autodiffed
self.autodiff_fusible_nodes = autodiff_fusible_nodes if autodiff_fusible_nodes else []
if autodiff_nonfusible_nodes is None:
self.autodiff_nonfusible_nodes = ['aten::' + self.name]
else:
self.autodiff_nonfusible_nodes = autodiff_nonfusible_nodes
self.supports_sparse = supports_sparse
self.check_batched_grad = check_batched_grad
self.check_batched_gradgrad = check_batched_gradgrad
def __call__(self, *args, **kwargs):
"""Calls the function variant of the operator."""
return self.op(*args, **kwargs)
def get_op(self):
"""Returns the function variant of the operator, torch.<op_name>."""
return self.op
def get_method(self):
"""Returns the method variant of the operator, torch.Tensor.<op_name>.
Returns None if the operator has no method variant.
"""
return self.method_variant
def get_inplace(self):
"""Returns the inplace variant of the operator, torch.Tensor.<op_name>_.
Returns None if the operator has no inplace variant.
"""
return self.inplace_variant
def get_operator_variant(self):
"""Returns operator variant of the operator, e.g. operator.neg
Returns None if the operator has no operator variant.
"""
return self.operator_variant
def sample_inputs(self, device, dtype, requires_grad=False):
"""Returns an iterable of SampleInputs.
These samples should be sufficient to test the function works correctly
with autograd, TorchScript, etc.
"""
return self.sample_inputs_func(self, device, dtype, requires_grad)
# Returns True if the test should be skipped and False otherwise
def should_skip(self, cls_name, test_name, device_type, dtype):
return any(si.is_active(cls_name, test_name, device_type, dtype)
for si in self.skips)
def supported_dtypes(self, device_type):
if device_type == 'cpu':
return self.dtypesIfCPU
if device_type == 'cuda':
return self.dtypesIfROCM if TEST_WITH_ROCM else self.dtypesIfCUDA
else:
return self.dtypes
def supports_dtype(self, dtype, device_type):
return dtype in self.supported_dtypes(device_type)
def default_test_dtypes(self, device_type):
"""Returns the default dtypes used to test this operator on the device.
Equal to the operator's default_test_dtypes filtered to remove dtypes
not supported by the device.
"""
supported = self.supported_dtypes(device_type)
return (supported if self._default_test_dtypes is None
else supported.intersection(self._default_test_dtypes))
L = 20
M = 10
S = 5
def sample_inputs_unary(op_info, device, dtype, requires_grad):
low, high = op_info.domain
low = low if low is None else low + op_info._domain_eps
high = high if high is None else high - op_info._domain_eps
return (SampleInput(make_tensor((L,), device, dtype,
low=low, high=high,
requires_grad=requires_grad)),
SampleInput(make_tensor((), device, dtype,
low=low, high=high,
requires_grad=requires_grad)))
# Metadata class for unary "universal functions (ufuncs)" that accept a single
# tensor and have common properties like:
class UnaryUfuncInfo(OpInfo):
"""Operator information for 'universal unary functions (unary ufuncs).'
These are functions of a single tensor with common properties like:
- they are elementwise functions
- the input shape is the output shape
- they typically have method and inplace variants
- they typically support the out kwarg
- they typically have NumPy or SciPy references
See NumPy's universal function documentation
(https://numpy.org/doc/1.18/reference/ufuncs.html) for more details
about the concept of ufuncs.
"""
def __init__(self,
name, # the string name of the function
*,
ref, # a reference function
dtypes=floating_types(),
dtypesIfCPU=floating_and_complex_types_and(torch.bfloat16),
dtypesIfCUDA=floating_and_complex_types_and(torch.half),
dtypesIfROCM=floating_types_and(torch.half),
domain=(None, None), # the [low, high) domain of the function
handles_large_floats=True, # whether the op correctly handles large float values (like 1e20)
handles_extremals=True, # whether the op correctly handles extremal values (like inf)
handles_complex_extremals=True, # whether the op correct handles complex extremals (like inf -infj)
supports_complex_to_float=False, # op supports casting from complex input to real output safely eg. angle
sample_inputs_func=sample_inputs_unary,
supports_sparse=False,
**kwargs):
super(UnaryUfuncInfo, self).__init__(name,
dtypes=dtypes,
dtypesIfCPU=dtypesIfCPU,
dtypesIfCUDA=dtypesIfCUDA,
dtypesIfROCM=dtypesIfROCM,
sample_inputs_func=sample_inputs_func,
supports_sparse=supports_sparse,
**kwargs)
self.ref = ref
self.domain = domain
self.handles_large_floats = handles_large_floats
self.handles_extremals = handles_extremals
self.handles_complex_extremals = handles_complex_extremals
self.supports_complex_to_float = supports_complex_to_float
# Epsilon to ensure grad and gradgrad checks don't test values
# outside a function's domain.
self._domain_eps = 1e-5
def sample_inputs_tensor_split(op_info, device, dtype, requires_grad):
return (SampleInput(make_tensor((S, S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
args=(torch.tensor([1, 2, 3]),),),
SampleInput(make_tensor((S, S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
args=(torch.tensor(1),),),
SampleInput(make_tensor((S, S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
args=(torch.tensor([1, 2, 3]),),
kwargs=dict(dim=1)),)
def sample_inputs_linalg_norm(op_info, device, dtype, requires_grad):
test_sizes = [
(S,),
(0,),
(S, S),
(0, 0),
(S, 0),
(0, S),
(S, S, S),
(0, S, S),
(S, 0, S),
(0, 0, 0),
]
vector_ords = (None, 0, 0.5, 1, 2, 3.5, inf, -0.5, -1, -2, -3.5)
matrix_ords = (None, 'fro', 'nuc', 1, 2, inf, -1, -2, -inf)
inputs = []
is_dtype_half = dtype in [torch.float16, torch.bfloat16]
for test_size in test_sizes:
is_vector_norm = len(test_size) == 1
is_matrix_norm = len(test_size) == 2
for keepdim in [False, True]:
inputs.append(SampleInput(
make_tensor(
test_size, device, dtype, low=None, high=None,
requires_grad=requires_grad),
kwargs=dict(
keepdim=keepdim)))
if not (is_vector_norm or is_matrix_norm):
continue
ords = vector_ords if is_vector_norm else matrix_ords
for ord in ords:
# TODO: remove this check when `max` is implemented for
# float16 and bfloat16. Issue:
# https://github.com/pytorch/pytorch/issues/50790
if is_vector_norm and is_dtype_half and ord == inf:
continue
inputs.append(SampleInput(
make_tensor(
test_size, device, dtype,
low=None, high=None,
requires_grad=requires_grad),
args=(ord,),
kwargs=dict(
keepdim=keepdim)))
if ord in ['nuc', 'fro']:
inputs.append(SampleInput(
make_tensor(
test_size, device, dtype,
low=None, high=None,
requires_grad=requires_grad),
kwargs=dict(
ord=ord,
keepdim=keepdim,
dim=(0, 1))))
return inputs
def sample_inputs_slogdet(op_info, device, dtype, requires_grad):
# original test cases from 'method_tests' have too many test_inputs
# we don't actually need all of them to check the autograd and jit correctness
# sample inputs with shapes 0x0, 0xSxS, 2x0x0 are added
test_inputs = (
torch.randn(0, 0, dtype=dtype, device=device), # '0x0'
torch.randn(S, S, dtype=dtype, device=device), # 'SxS'
torch.randn(0, S, S, dtype=dtype, device=device), # 'zero_batched_SxS'
torch.randn(2, 0, 0, dtype=dtype, device=device), # 'batched_0x0'
torch.randn(2, S, S, dtype=dtype, device=device), # 'batched_SxS'
)
out = []
for a in test_inputs:
a.requires_grad = requires_grad
out.append(SampleInput(a))
return out
def sample_inputs_addmm(op_info, device, dtype, requires_grad):
input = SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=False)))
if dtype.is_complex:
another_input = SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=False)),
kwargs=dict(beta=1 + 2j, alpha=2 + 3j))
return (input, another_input)
else:
return (input, )
def sample_inputs_addr(op_info, device, dtype, requires_grad):
input1 = SampleInput((make_tensor((S, M), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((M, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad)))
input2 = SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((M, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad)))
if dtype.is_complex:
alpha, beta = 0.1 + 0.3j, 0.4 + 0.6j
elif dtype.is_floating_point:
alpha, beta = 0.2, 0.6
else:
alpha, beta = 2, 3
input3 = SampleInput((make_tensor((S, M), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((M, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad)),
kwargs=dict(beta=beta, alpha=alpha))
input4 = SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((M, ), device, dtype,
low=None, high=None,
requires_grad=requires_grad)),
kwargs=dict(beta=beta, alpha=alpha))
return (input1, input2, input3, input4)
def sample_inputs_xlogy(self, device, dtype, requires_grad):
return (SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=0, high=None,
requires_grad=requires_grad))),)
def sample_inputs_trace(self, device, dtype, requires_grad):
return (SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad))),)
def sample_inputs_linalg_inv(op_info, device, dtype, requires_grad=False):
"""
This function generates always invertible input for torch.linalg.inv using
random_fullrank_matrix_distinct_singular_value.
The input is generated as the itertools.product of 'batches' and 'ns'.
In total this function generates 8 SampleInputs
'batches' cases include:
() - single input,
(0,) - zero batched dimension,
(2,) - batch of two matrices,
(2, 3) - 2x3 batch of matrices
'ns' gives 0x0 and 5x5 matrices.
Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.
"""
from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value
batches = [(), (0, ), (2, ), (2, 3)]
ns = [0, 5]
out = []
for batch, n in product(batches, ns):
a = random_fullrank_matrix_distinct_singular_value(n, *batch, dtype=dtype).to(device)
a.requires_grad = requires_grad
out.append(SampleInput(a))
return out
def np_sinc_with_fp16_as_fp32(x):
# Wraps numpy's sinc function so that fp16 values are promoted to fp32
# before sinc is invoked. Context: numpy's sinc returns NaN when evaluated
# at 0 for fp16.
if x.dtype == np.float16:
return np.sinc(x.astype(np.float32))
else:
return np.sinc(x)
def sample_inputs_broadcast_to(op_info, device, dtype, requires_grad):
test_cases = (
((S, 1, 1), (S, S, S)),
((S, 1, S), (S, S, S)),
((S, 1), (S, S, S)),
((1,), (S, S, S)),
((1, S), (1, 1, S)),
((), ()),
((), (1, 3, 2)),
)
return tuple(SampleInput((make_tensor(size, device, dtype,
low=None, high=None,
requires_grad=requires_grad), shape))
for size, shape in test_cases)
def sample_inputs_stack(op_info, device, dtype, requires_grad):
return (SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad)), kwargs=dict(idx=0)),)
def sample_inputs_hstack_dstack_vstack(op_info, device, dtype, requires_grad):
return (SampleInput((make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
make_tensor((S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad))),)
def sample_inputs_gather(op_info, device, dtype, requires_grad):
return (SampleInput((make_tensor((M, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, gather_variable((S, S), 1, M, True, device=device))),
SampleInput((make_tensor((M, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
1, gather_variable((M, S // 2), 0, S, True, device=device))),
SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, torch.tensor([0], dtype=torch.int64, device=device))),
SampleInput((make_tensor((S,), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, torch.tensor(0, dtype=torch.int64, device=device))),
SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, torch.tensor(0, dtype=torch.int64, device=device))),
)
def sample_inputs_index_select(op_info, device, dtype, requires_grad):
return (SampleInput((make_tensor((S, S, S), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, index_variable(2, S, device=device))),
SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, torch.tensor([0], dtype=torch.int64, device=device))),
SampleInput((make_tensor((), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
0, torch.tensor(0, dtype=torch.int64, device=device))),
)
def sample_movedim_moveaxis(op_info, device, dtype, requires_grad):
return (SampleInput((make_tensor((4, 3, 2, 1), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
(0, 1, 2, 3), (3, 2, 1, 0))),
SampleInput((make_tensor((4, 3, 2, 1), device, dtype,
low=None, high=None,
requires_grad=requires_grad),
(0, -1, -2, -3), (-3, -2, -1, -0))))
def sample_repeat_tile(op_info, device, dtype, requires_grad):
rep_dims = ((), (0, ), (1, ), (0, 2), (1, 1), (2, 3), (2, 3, 2), (0, 2, 3), (2, 1, 1, 1),)
shapes = ((), (0,), (2,), (3, 0), (3, 2), (3, 0, 1))
if requires_grad:
# Tests for variant_consistency_jit, grad, gradgrad
# are slower. Use smaller bags of `rep_dims` and `shapes`
# in this case.
rep_dims = ((), (0, ), (0, 2), (1, 1), (2, 3), (1, 3, 2), (3, 1, 1)) # type: ignore
shapes = ((), (0,), (2,), (3, 2)) # type: ignore
tensors = [make_tensor(shape, device, dtype,
low=None, high=None,
requires_grad=requires_grad) for shape in shapes]
samples = []
for rep_dim, tensor in product(rep_dims, tensors):
for t in (tensor, tensor.T):
if op_info.name == 'repeat' and len(rep_dim) >= t.dim():
# `torch.repeat` errors for `len(rep_dims) < t.dim()`,
# so we filter such combinations.
samples.append(SampleInput((t, rep_dim),))
elif op_info.name == 'tile':
samples.append(SampleInput((t, rep_dim),))
return samples
def np_unary_ufunc_integer_promotion_wrapper(fn):
# Wrapper that passes PyTorch's default scalar
# type as an argument to the wrapped NumPy
# unary ufunc when given an integer input.
# This mimicks PyTorch's integer->floating point
# type promotion.
#
# This is necessary when NumPy promotes
# integer types to double, since PyTorch promotes
# integer types to the default scalar type.
# Helper to determine if promotion is needed
def is_integral(dtype):
return dtype in [np.bool, np.uint8, np.int8, np.int16, np.int32, np.int64]
# NOTE: Promotion in PyTorch is from integer types to the default dtype
np_dtype = torch_to_numpy_dtype_dict[torch.get_default_dtype()]
@wraps(fn)
def wrapped_fn(x):
if is_integral(x.dtype):
return fn(x, dtype=np_dtype)
return fn(x)
return wrapped_fn
# Metadata class for Fast Fourier Transforms in torch.fft.
class SpectralFuncInfo(OpInfo):
"""Operator information for torch.fft transforms. """
def __init__(self,
name, # the string name of the function
*,
ref=None, # Reference implementation (probably in np.fft namespace)
dtypes=floating_and_complex_types(),
ndimensional: bool, # Whether dim argument can be a tuple
decorators=None,
**kwargs):
decorators = list(decorators) if decorators is not None else []
decorators += [
skipCPUIfNoMkl,
skipCUDAIfRocm,
# gradgrad is quite slow
DecorateInfo(slowTest, 'TestGradients', 'test_fn_gradgrad'),
]
super().__init__(name=name,
dtypes=dtypes,
decorators=decorators,
**kwargs)
self.ref = ref if ref is not None else _getattr_qual(np, name)
self.ndimensional = ndimensional
def sample_inputs(self, device, dtype, requires_grad=False):
nd_tensor = make_tensor((S, S + 1, S + 2), device, dtype, low=None, high=None,
requires_grad=requires_grad)
tensor = make_tensor((31,), device, dtype, low=None, high=None,
requires_grad=requires_grad)
if self.ndimensional:
return [
SampleInput(nd_tensor, kwargs=dict(s=(3, 10), dim=(1, 2), norm='ortho')),
SampleInput(nd_tensor, kwargs=dict(norm='ortho')),
SampleInput(nd_tensor, kwargs=dict(s=(8,))),
SampleInput(tensor),
*(SampleInput(nd_tensor, kwargs=dict(dim=dim))
for dim in [-1, -2, -3, (0, -1)]),
]
else:
return [
SampleInput(nd_tensor, kwargs=dict(n=10, dim=1, norm='ortho')),
SampleInput(nd_tensor, kwargs=dict(norm='ortho')),
SampleInput(nd_tensor, kwargs=dict(n=7)),
SampleInput(tensor),
*(SampleInput(nd_tensor, kwargs=dict(dim=dim))
for dim in [-1, -2, -3]),
]
class ShapeFuncInfo(OpInfo):
"""Early version of a specialized OpInfo for Shape manipulating operations like tile and roll"""
def __init__(self,
name, # the string name of the function
*,
ref, # a reference function
dtypes=floating_types(),
dtypesIfCPU=None,
dtypesIfCUDA=None,
dtypesIfROCM=None,
sample_inputs_func=None,
**kwargs):
super(ShapeFuncInfo, self).__init__(name,
dtypes=dtypes,
dtypesIfCPU=dtypesIfCPU,
dtypesIfCUDA=dtypesIfCUDA,
dtypesIfROCM=dtypesIfROCM,
sample_inputs_func=sample_inputs_func,
**kwargs)
self.ref = ref
class HermitianOpInfo(OpInfo):
"""Operator information for Hermitian functions
These are functions that take Hermitian matrices as input.
They require a modified function to be tested for gradcheck, because the finite-difference algorithm
for calculating derivatives does not preserve the Hermitian property of the input and returning incorrect results.
"""
def get_op(self):
"""
Returns the function variant of the operator, torch.<op_name>,
compatible with gradcheck for Hermitian functions.
It works only for single input argument.
"""
def hermitian_func(non_hermitian_input, **kwargs):
hermitian_input = non_hermitian_input + non_hermitian_input.conj().transpose(-2, -1)
return self.op(hermitian_input, **kwargs)
return hermitian_func
def sample_inputs_linalg_pinv(op_info, device, dtype, requires_grad=False):
"""
This function generates input for torch.linalg.pinv with distinct singular values so that autograd is always stable
Implementation of torch.linalg.pinv depends on torch.svd and torch.linalg.eigh, therefore it's sufficient to
check only square S x S matrix and the batched (3 x S x S) input.
"""
from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value
test_cases = (
random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device), # single matrix
random_fullrank_matrix_distinct_singular_value(S, 3, dtype=dtype).to(device), # batch of matrices
)
out = []
for a in test_cases:
a.requires_grad = requires_grad
out.append(SampleInput(a))
return out
def sample_inputs_linalg_pinv_hermitian(op_info, device, dtype, requires_grad=False):
"""
This function generates input for torch.linalg.pinv with hermitian=True keyword argument.
"""
out = sample_inputs_linalg_pinv(op_info, device, dtype, requires_grad)
for o in out:
o.kwargs = {"hermitian": True}
return out
def sample_inputs_linalg_solve(op_info, device, dtype, requires_grad=False):
"""
This function generates always solvable input for torch.linalg.solve
Using random_fullrank_matrix_distinct_singular_value gives a non-singular (=invertible, =solvable) matrices 'a'.
The first input to torch.linalg.solve is generated as the itertools.product of 'batches' and 'ns'.
The second input is generated as the product of 'batches', 'ns' and 'nrhs'.
In total this function generates 18 SampleInputs
'batches' cases include:
() - single input,
(0,) - zero batched dimension,
(2,) - batch of two matrices.
'ns' gives 0x0 and 5x5 matrices.
and 'nrhs' controls the number of vectors to solve for:
() - using 1 as the number of vectors implicitly
(1,) - same as () but explicit
(3,) - solve for 3 vectors.
Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.
"""
from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value
batches = [(), (0, ), (2, )]
ns = [0, 5]
nrhs = [(), (1, ), (3, )]
out = []
for n, batch, rhs in product(ns, batches, nrhs):
a = random_fullrank_matrix_distinct_singular_value(n, *batch, dtype=dtype).to(device)
a.requires_grad = requires_grad
b = torch.randn(*batch, n, *rhs, dtype=dtype, device=device)
b.requires_grad = requires_grad
out.append(SampleInput((a, b)))
return out
def _sample_inputs_svd(op_info, device, dtype, requires_grad=False, is_linalg_svd=False):
"""
This function generates input for torch.svd with distinct singular values so that autograd is always stable.
Matrices of different size:
square matrix - S x S size
tall marix - S x (S-2)
wide matrix - (S-2) x S
and batched variants of above are generated.
Each SampleInput has a function 'output_process_fn_grad' attached to it that is applied on the output of torch.svd
It is needed for autograd checks, because backward of svd doesn't work for an arbitrary loss function.
"""
from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value
# svd and linalg.svd returns V and V.T, respectively. So we need to slice
# along different dimensions when needed (this is used by
# test_cases2:wide_all and wide_all_batched below)
if is_linalg_svd:
def slice_V(v):
return v[..., :(S - 2), :]
else:
def slice_V(v):
return v[..., :, :(S - 2)]
test_cases1 = ( # some=True (default)
# loss functions for complex-valued svd have to be "gauge invariant",
# i.e. loss functions shouldn't change when sigh of the singular vectors change.
# the simplest choice to satisfy this requirement is to apply 'abs'.
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),
lambda usv: usv[1]), # 'check_grad_s'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),
lambda usv: abs(usv[0])), # 'check_grad_u'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),
lambda usv: abs(usv[2])), # 'check_grad_v'
# TODO: replace lambda usv: usv[0][0, 0] * usv[2][0, 0] with lambda usv: usv[0][0, 0] * usv[2][0, 0].conj()
# once https://github.com/pytorch/pytorch/issues/45821 is resolved
# this test is important as it checks the additional term that is non-zero only for complex-valued inputs
# and when the loss function depends both on 'u' and 'v'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),
lambda usv: usv[0][0, 0] * usv[2][0, 0]), # 'check_grad_uv'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:(S - 2)],
lambda usv: (abs(usv[0]), usv[1], abs(usv[2][..., :, :(S - 2)]))), # 'wide'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:, :(S - 2)],
lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'tall'
(random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device),
lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'batched'
(random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :(S - 2), :],
lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'wide_batched'
(random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :, :(S - 2)],
lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'tall_batched'
)
test_cases2 = ( # some=False
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:(S - 2)],
lambda usv: (abs(usv[0]), usv[1], abs(slice_V(usv[2])))), # 'wide_all'
(random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:, :(S - 2)],
lambda usv: (abs(usv[0][:, :(S - 2)]), usv[1], abs(usv[2]))), # 'tall_all'
(random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :(S - 2), :],
lambda usv: (abs(usv[0]), usv[1], abs(slice_V(usv[2])))), # 'wide_all_batched'
(random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :, :(S - 2)],
lambda usv: (abs(usv[0][..., :, :(S - 2)]), usv[1], abs(usv[2]))), # 'tall_all_batched'
)
out = []
for a, out_fn in test_cases1:
a.requires_grad = requires_grad
if is_linalg_svd:
kwargs = {'full_matrices': False}
else:
kwargs = {'some': True}
out.append(SampleInput(a, kwargs=kwargs, output_process_fn_grad=out_fn))
for a, out_fn in test_cases2:
a.requires_grad = requires_grad
if is_linalg_svd:
kwargs = {'full_matrices': True}
else:
kwargs = {'some': False}
out.append(SampleInput(a, kwargs=kwargs, output_process_fn_grad=out_fn))
return out
def sample_inputs_svd(op_info, device, dtype, requires_grad=False):
return _sample_inputs_svd(op_info, device, dtype, requires_grad, is_linalg_svd=False)
def sample_inputs_linalg_svd(op_info, device, dtype, requires_grad=False):
return _sample_inputs_svd(op_info, device, dtype, requires_grad, is_linalg_svd=True)
def sample_inputs_pinverse(op_info, device, dtype, requires_grad=False):
"""
This function generates input for torch.pinverse with distinct singular values so that autograd is always stable.
Implementation of torch.pinverse depends on torch.svd, therefore it's sufficient to check only square S x S matrix
and the batched (3 x S x S) input.
"""
from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value
test_cases = (
random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device), # pinverse
random_fullrank_matrix_distinct_singular_value(S, 3, dtype=dtype).to(device), # pinverse 'batched'
)
out = []
for a in test_cases:
a.requires_grad = requires_grad
out.append(SampleInput(a))
return out
def sample_inputs_flip(op_info, device, dtype, requires_grad):
tensors = (
make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad),
make_tensor((S, 0, M), device, dtype, low=None, high=None, requires_grad=requires_grad)
)
dims = ((0, 1, 2), (0,), (0, 2), (-1,), ())
samples = [SampleInput(tensor, kwargs={'dims': dim}) for tensor, dim in product(tensors, dims)]
return samples
def sample_inputs_fliplr_flipud(op_info, device, dtype, requires_grad):
tensors = (
make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad),
make_tensor((S, 0, M), device, dtype, low=None, high=None, requires_grad=requires_grad)
)
return [SampleInput(tensor) for tensor in tensors]
# Operator database (sorted alphabetically)
op_db: List[OpInfo] = [
# NOTE: CPU complex acos produces incorrect outputs (https://github.com/pytorch/pytorch/issues/42952)
UnaryUfuncInfo('acos',
ref=np.arccos,
domain=(-1, 1),
handles_complex_extremals=False,
dtypes=all_types_and_complex_and(torch.bool),
dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16),
dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half),
default_test_dtypes=[torch.long, torch.half, torch.bfloat16, torch.float32, torch.cfloat],
skip_bfloat16_grad=True,
assert_autodiffed=True,
decorators=(precisionOverride({torch.float16: 1e-2,
torch.bfloat16: 1e-1,
torch.complex64: 1e-2}),),
safe_casts_outputs=True,
skips=(
SkipInfo('TestUnaryUfuncs', 'test_reference_numerics',
device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),
SkipInfo('TestUnaryUfuncs', 'test_reference_numerics',
dtypes=[torch.cfloat, torch.cdouble], active_if=IS_WINDOWS),
SkipInfo('TestGradients', 'test_fn_grad',
dtypes=[torch.cdouble], active_if=IS_WINDOWS),
SkipInfo('TestGradients', 'test_method_grad',
dtypes=[torch.cdouble], active_if=IS_WINDOWS),
SkipInfo('TestGradients', 'test_inplace_grad',
dtypes=[torch.cdouble], active_if=IS_WINDOWS),